通过第三方库登录 http://python-social-auth.readthedocs.io/en/latest/configuration/django.html
安装pip
`pip install social-auth-app-django`
配置settings
~~~
INSTALLED_APPS = (
...
'social_django',
...
)
~~~
TEMPLATES 增加
~~~
TEMPLATES = [
{
...
'OPTIONS' : {
...
'context_processors' : [
...
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
...
]
}
}
]
~~~
AUTHENTICATION_BACKENDS 设置
~~~
#第三方登录
AUTHENTICATION_BACKENDS = (
'social_core.backends.weibo.WeiboOAuth2',
'social_core.backends.weixin.WeixinOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
#微博密匙
SOCIAL_AUTH_WEIBO_KEY = '你申请的key'
SOCIAL_AUTH_WEIBO_SECRET = '密匙'
#微信密匙
SOCIAL_AUTH_WEIXIN_KEY = '你申请的key'
SOCIAL_AUTH_WEIXIN_SECRET = '密匙'
#登录后跳转
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/./'
~~~
生成数据库
~~~
migrate
~~~
生成了5个数据表
`“social_auth_association”“social_auth_code”“social_auth_nonce”“social_auth_partial”“social_auth_usersocialauth”`
注意:如果不能生成请注意mysql数据库的配置,是否指定数据库类型INNODB
`'OPTIONS': { 'init_command': 'SET storage_engine=INNODB;' }`
URLS配置
`url('', include('social_django.urls', namespace='social')),`
第三方登录url
http://***/login/weixin
回调地址
http://***/complete/weixin
**weixin.WeixinOAuth2修改**
~~~
class WeixinOAuth2(BaseOAuth2):
"""Weixin OAuth authentication backend"""
name = 'weixin'
ID_KEY = 'openid'
AUTHORIZATION_URL = 'https://open.weixin.qq.com/connect/oauth2/authorize'
ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/oauth2/access_token'
ACCESS_TOKEN_METHOD = 'POST'
#授权
DEFAULT_SCOPE = ['snsapi_userinfo']
REDIRECT_STATE = False
#获取数组
EXTRA_DATA = [
('nickname', 'username'),
('headimgurl', 'headimgurl'),
('province', 'province'),
('city', 'city'),
('sex', 'sex'),
]
~~~
**新建app myuser**
view文件
~~~
# _*_ coding:utf-8 * _*_
from django.shortcuts import render
#新增用户信息,required引入装饰器,判断用户登录
from django.contrib.auth.decorators import login_required
#引入django自带用户中心
from django.contrib.auth.models import User
#引入第三方登录models
from social_django.models import UserSocialAuth
# Create your views here.
#个人信息
@login_required(login_url='/login/weixin')
def myself(request):
user = User.objects.get(username=request.user.username)
userinfo = UserSocialAuth.objects.get(user=user)
return render(request, "me.html", {"user": user, "uid":userinfo})
~~~
urls文件
~~~
# _*_ coding:utf-8 _*_
from django.conf.urls import url
#引入app项目 view
from .import views
urlpatterns = [
url(r'^$', views.myself, name="user_login"),
]
~~~
项目urls新增
~~~
url(r'^blog/', include('myuser.urls', namespace='blog')),
~~~
me.html文件
~~~
<div>用户名</div>
<div>{{ user.username }}</div>
<img src="{{ uid.extra_data.profile_image_url }}">
<div>Uid:{{ uid.uid }}</div>
<div>编号:{{ uid.user_id }}</div>
<div>微信昵称:{{ uid.extra_data.username }}</div>
~~~