1. 创建apps/oauth
模块进行oauth认证
'''2.1 在apps文件夹下新建应用: oauth'''
cd syl/apps
python ../manage.py startapp oauth
'''2.2 添加子路由:oauth/urls.py'''
from django.urls import path
from . import views
urlpatterns = [
]
'''2.3 在syl/settings.py中添加应用'''
INSTALLEN_APPS = [
'oauth.apps.OauthConfig',
]
'''2.4 在syl/urls.py主路由中添加'''
urlpatterns = [
path('oauth/', include('oauth.urls')),
]
2. 生成微博授权URL接口
1.1 添加子路由:oauth/urls.py
urlpatterns = [
path('weibo/', views.WeiboUrl.as_view()),
]
1.2 syl/settings.py
中配微博地址
1.3 视图函数:oauth/views.py
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from urllib.parse import urlencode
class WeiboUrl(APIView):
'''
生成微博的登录页面路由地址
https://api.weibo.com/ouath2/authorize? # 微博oauth认证地址
client_id=4152203003& # 注册开发者id
response_type=code&
redirect_uri=http://127.0.0.1:8888/oauth/callback/ # 获取code后将code回调给后端地址
'''
permission_classes = (AllowAny, )
def post(self, request):
url = 'https://api.weibo.com/oauth2/authorize?'
data = {
'client_id': '3630488439',
'response_type': 'code',
'redirect_uri': 'http://127.0.0.1:8888/oauth/callback/',
}
weibo_url = url + urlencode(data)
return Response({'code': '0','msg':'成功', 'data': {'url': weibo_url}})
3. 测试生成微博授权URL接口
- 测试接口获取新浪微博地址
- 在浏览器访问返回地址即可回到新浪扫码界面
https://api.weibo.com/oauth2/authorize?
client_id=3516473472&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A808
0%2Fweibo_callback