Skip to main content
 首页 » 编程设计

Python 社交验证 : How to define a different username scheme

2025年05月04日15zengkefu

Python Social Auth 中默认的用户名生成方案是采用经过身份验证的社交网络的用户名,如果已经采用,则向其添加一些随机值(或者是哈希值?)。

无论如何,我想改变这种行为,我想定义我自己的用户名生成方法。例如用户名+提供者+随机数。

想法?

请您参考如下方法:

您只需将 SOCIAL_AUTH_PIPELINE 中的 social.pipeline.user.get_username 替换为您自己返回生成的用户名的函数的路径。

例如:

project/myapp/settings.py

SOCIAL_AUTH_PIPELINE = ( 
    'social.pipeline.social_auth.social_details', 
    'social.pipeline.social_auth.social_uid', 
    'social.pipeline.social_auth.auth_allowed', 
    'social.pipeline.social_auth.social_user', 
    'project.myapp.utils.get_username', 
    'social.pipeline.social_auth.associate_by_email', 
    'social.pipeline.user.create_user', 
    'social.pipeline.social_auth.associate_user', 
    'social.pipeline.social_auth.load_extra_data', 
    'social.pipeline.user.user_details', 
) 

项目/myapp/utils.py:

from social.pipeline.user import get_username as social_get_username 
from random import randrange 
 
def get_username(strategy, details, user=None, *args, **kwargs): 
    result = social_get_username(strategy, details, user=user, *args, **kwargs) 
    result['username'] = '-'.join([ 
        result['username'], strategy.backend.name, str(randrange(0, 1000)) 
    ]) 
    return result 

在上面的函数中,我从 python-social-auth 模块调用默认的 get_username 方法,结果附加提供者名称和 0 到 1000 之间的随机数。

您可以查看social.pipeline.user.get_username on GitHub 的源代码.