1. 程式人生 > 實用技巧 >生成微博授權url

生成微博授權url

1,建立apps/oauth模組進oauth認證

'''2.1 在apps資料夾下新建應用: oauth''' cd syl/apps python ../manage.py startapp oauth  # 切換到apps資料夾下執行建立命令
'''2.2 新增子路由: oauth/urls.py''' from django.urls import path from . import views urlpatterns = [
]
'''2.3 在syl/settings.py中新增應用''' INSTALLED_APPS = [  'oauth.apps.OauthConfig', ]
'''
2.4 在syl/urls.py主路由中新增''' urlpatterns = [ path('oauth/', include('oauth.urls')), ]

生成微博授權URL介面

  1,新增子路由: oauth/urls.py

  

urlpatterns = [  path('weibo/', views.WeiboUrl.as_view()), # /oauth/weibo/ 返回微博登入地址 ]

  2, syl/settings.py配置微博地址

 3, 檢視函式: oauth/views.py

  

1 from rest_framework.permissions import
AllowAny 2 from rest_framework.respons 3 import Response from rest_framework.views import APIView from urllib.parse import urlencode 4 class WeiboUrl(APIView): 5 https://api.weibo.com/oauth2/authorize? # 微博oauth認證地址 client_id=4152203033& # 註冊開發者id

permission_classes = (AllowAny,)
def post(self, request): url = 'https://api.weibo.com/oauth2/authorize?' # 微博授權的 url地址 data = { 'client_id': '3516473472', # WEIBO_APP_KEY, 'response_type': 'code', 'redirect_uri': 'http://127.0.0.1:8888/oauth/callback/', # VUE的回 調,微博後臺授權的回撥地址 } weibo_url = url + urlencode(data) # https://api.weibo.com/oauth2/authorize? client_id=4152203033&response_type=code&redirect_uri=http://127.0.0.1:8000/api/we ibo_back/ # return Response({'weibo_url': weibo_url}) return Response({'code': '0', 'msg': '成功', 'data': {'url': weibo_url}})

3.測試生成微博售前URL介面