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')), ]

2.生成微博授權URL介面

1.1 新增子路由: oauth/urls.py

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

1.2 檢視函式: oauth/views.py

from urllib.parse import urlencode

from rest_framework.permissions import
AllowAny from rest_framework.response import Response from rest_framework.views import APIView # 生成前端跳轉到微博掃碼頁面的url class WeiboUrl(APIView): ''' 生成微博的登陸頁面路由地址 https://api.weibo.com/oauth2/authorize? # 微博oauth認證地址 client_id=4152203033& # 註冊開發者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?' # 微博授權的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/weibo_back/ # return Response({'weibo_url': weibo_url}) return Response({'code': '0', 'msg': '成功', 'data': {'url': weibo_url}})

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

  ·測試介面獲取新浪微博地址

http://192.168.56.100:8888/oauth/weibo/

  · 在瀏覽器訪問返回地址即可回到新浪掃碼介面

https://api.weibo.com/oauth2/authorize?client_id=3516473472&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2Fweibo_callback