【Python】Django整合Github登陸
阿新 • • 發佈:2019-01-26
開發環境
- python3.5
- django1.11.6
- pip install social-auth-app-django
註冊Guthub賬號並獲取ID和SECRET
Django專案配置
- 開啟settings.py,配置如下內容
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages' ,
'django.contrib.staticfiles',
'social_django' # 新增第三方登入庫app
]
# 設定登入的方式,這裡是github
AUTHENTICATION_BACKENDS = (
'social_core.backends.github.GithubOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_URL_NAMESPACE = 'social'
# 填寫Github中獲取到的KEY和SECRET
SOCIAL_AUTH_GITHUB_KEY = '91c3a492abae2e8a9801'
SOCIAL_AUTH_GITHUB_SECRET = '2400fedbc47b59fda64e291cf78b31d2af5ba2f9'
SOCIAL_AUTH_GITHUB_USE_OPENID_AS_USERNAME = True
# 登陸成功後的回撥路由
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/index'
# 在TEMPLATES中的context_processors中增加兩項
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates' ,
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends', # 增加這兩項
'social_django.context_processors.login_redirect',
],
},
},
]
- 開啟urls.py,配置如下
url(r'', include('social_django.urls', namespace='social'))
- 開啟html模板檔案,在需要登入的地方加入如下內容
<a href="{% url "social:begin" "github" %}">Github登陸</a>