pt36項目短信OAth2.0

5、短信驗證碼

1、注冊容聯云賬號,登錄并查看開發文檔(以下分析來自接口文檔)
2、開發文檔【準備1】:請求URL地址1.示例:https://app.cloopen.com:8883/2013-12-26/Accounts/{}/SMS/TemplateSMS?sig={}ACCOUNT SID# sig:使用MD5加密(賬戶Id + 賬戶授權令牌 + 時間戳)【準備2】:請求頭headersAccept:application/xml;Content-Type:application/xml;charset=utf-8;Content-Length:256; Authorization: # 使用Base64編碼(賬戶Id + 冒號 + 時間戳【準備3】:請求體datato :短信接收端手機號碼集合appId :應用Id,官網控制臺應用列表獲取templateId :模板Id,測試模板id1。datas :補充模板短信中的內容[驗證碼 | 幾分鐘輸入]經過對接口文檔分析,最終需要準備:1.POST請求的地址:url2.POST請求的請求頭:headers3.POST請求的請求體:datahttps://app.cloopen.com:8883/2013-12-26/Accounts/{}/SMS/TemplateSMS?sig={}

容聯云

ACCOUNT SID:2c94812dgad3018872722dec086d
(主賬戶ID)
AUTH TOKEN:
222*******e929查看
(賬戶授權令牌)
Rest URL(生產):https://app.cloopen.com:8883
AppID(默認):2c948zdfe334gg8872722f1b0874未上線
(APP TOKEN 請到應用管理中獲取)
鑒權IP:   #關閉,未認證情況下開啟,無法發短信

設計添加接口路由

#user/urls.py# 短信驗證:v1/users/sms/codepath('sms/code', views.sms_view),

設計短信發送工具

#utils/sms.py
"""對接容聯云短信平臺,實現發送短信驗證碼
"""
import random
import time
import base64
import requests
from hashlib import md5class YunTongXunAPI:def __init__(self, accountSid, authToken, appId, templateId):"""差異化的內容做成應用:param accountSid: 賬號id,控制臺:param authToken: 授權令牌,控制臺:param appId: 控制臺:param templateId: 短信模板,測試為1"""self.accountSid = accountSidself.authToken = authTokenself.appId = appIdself.templateId = templateIddef get_url(self):"""生成url地址"""post_url = "https://app.cloopen.com:8883/2013-12-26/Accounts/{}/SMS/TemplateSMS?sig={}".format(self.accountSid, self.get_sig())return post_urldef get_headers(self):"""獲取請求頭"""# 使用Base64編碼(賬戶Id+冒號+時間戳)s = self.accountSid + ':' + time.strftime("%Y%m%d%H%M%S")auth = base64.b64encode(s.encode()).decode()headers = {"Accept": "application/json;","Content-Type": "application/json;charset=utf-8;",# "Content-Length": "256;",   #request模塊會自動添加"Authorization": auth}return headersdef get_body(self, phone, code):"""請求體"""data = {"to": phone,"appId": self.appId,"templateId": self.templateId,"datas": [code, '3']}return datadef run(self, phone, code):"""程序入口函數"""url = self.get_url()headers = self.get_headers()body = self.get_body(phone, code)# html: {"statusCode":"000000"}html = requests.post(url=url, headers=headers, json=body).json()#print(html)#未添加測試賬號   {'statusCode': '111188', 'statusMsg': '【賬號】主賬戶綁定的測試號碼個數為零'}#添加測試賬號{'statusCode': '000000', 'templateSMS': {'smsMessageSid': 'fa9de45f66ca4f5ca76833b9005b10e4', 'dateCreated': '20230602224219'}}return htmldef get_sig(self):"""功能函數:生成sig使用MD5加密(賬戶Id+賬戶授權令牌+時間戳)"""s = self.accountSid + self.authToken + time.strftime("%Y%m%d%H%M%S")m = md5()m.update(s.encode())return m.hexdigest().upper()if __name__ == '__main__':config = {"accountSid": "2c94812dgad3018872722dec086d","authToken": "22205d59b81465abbd26cf16e929","appId": "2c948zdfe334gg8872722f1b0874","templateId": "1"}ytx = YunTongXunAPI(**config)code = random.randint(1000, 9999)ytx.run("17723452345", code)#運行查看是否有短信收到

設計功能路由調用

#瀏覽器點擊獲取驗證碼,查看xhrheaders里:請求地址  http://127.0.0.1:8000/v1/users/sms/codepayload里:{"phone":""}: 
#user/urls.py# 短信驗證:v1/users/sms/codepath('sms/code', views.sms_view),
#dashopt/settings.py
...
#############短信驗證配置開始############
MSG_CONFIG = {"accountSid": "2c94811c88518872722dec086d","authToken": "2220db32a697754048bb97e929","appId": "2c94811c8853872722f1b0874","templateId": "1"}

設計發送功能

#user/views.py
...
from utils.sms import YunTongXunAPIdef sms_view(request):"""對接容聯云實現短信驗證碼發送1.獲取請求體數據2.生成短信驗證碼3.調用容聯云接口發送短信"""data = json.loads(request.body)phone = data.get("phone")code = random.randint(1000, 9999)smsapi = YunTongXunAPI(**settings.MSG_CONFIG)smsapi.run(phone,code)return JsonResponse({"code": 200, "data": "發送成功"})#http://localhost:7000/dadashop/templates/register_sms.html   發送驗證是否成功

調整下

#user/views.py
...
from utils.sms import YunTongXunAPIdef sms_view(request):"""對接容聯云實現短信驗證碼發送1.獲取請求體數據2.生成短信驗證碼3.調用容聯云接口發送短信"""data = json.loads(request.body)phone = data.get("phone")code = random.randint(1000, 9999)sms_html = send_msg(phone,code)if sms_html.get("statusCode") == "000000":return JsonResponse({"code": 200, "data": "發送成功"})return JsonResponse({"code": 10110, "error": {"message": "發送失敗"}})def send_msg(phone,code):smsapi = YunTongXunAPI(**settings.MSG_CONFIG)sms_html = smsapi.run(phone,code)return sms_html

發送并帶有驗證的功能

設計redis緩存
#dashopt/settings.py
...
CACHES = {# 緩存郵件激活隨機數"default": {
...},"msg_code": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": "redis://192.168.1.11:6379/2",# "TIMEOUT": None,  默認300s"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient","PASSWORD": "123456"}},
}
放入redis
#user/views.py
...
MSG_CACHE = caches["msg_code"]
...
def sms_view(request):"""對接容聯云實現短信驗證碼發送1.獲取請求體數據2.生成短信驗證碼3.調用容聯云接口發送短信"""data = json.loads(request.body)phone = data.get("phone")code = random.randint(1000, 9999)# 1.redis中確認: sms_13603263409key = "sms_%s" % phoneredis_code = MSG_CACHE.get(key)if redis_code:# 3分鐘之內已經發過return JsonResponse({"code": 10111, "error": {"message":"code already existed"}})# 3分鐘之內沒有發過:sms_html = send_msg(phone,code)# 2.存入redisif sms_html.get("statusCode") == "000000":MSG_CACHE.set(key, code, 180)return JsonResponse({"code": 200, "data": "發送成功"})return JsonResponse({"code": 10110, "error": {"message": "發送失敗"}})
短時間發送兩次短信,注意第二次發送是否成功,以及redis里的數據
      $.ajax({type: "post",url: baseUrl+"/v1/users",datatype: "json",contentType:"application/json",data: JSON.stringify({"uname": $('#uname').val(),"password": $('#upwd').val(),"phone": $('#phone').val(),"email": $('#email').val(),"verify": $('#verify').val(),"carts":localStorage.getItem('cart'),}),success: function (data) { //成功的回調函數if (data.code === 200){//window.localStorage.setItem('dashop_token', data.data.token);//window.localStorage.setItem('dashop_user', data.username);//window.localStorage.setItem('dashop_count', data.data.length);window.localStorage.setItem('dashop_token', data.data.token);window.localStorage.setItem('dashop_user', data.username);window.localStorage.setItem('dashop_count', data.carts_count);alert('注冊成功!');window.location.href = '/dadashop/templates/index.html';}else {alert(data.error.message); //返回后端message,彈窗code already existed}},
celery異步發送

...
from django.conf import settings
from utils.sms import YunTongXunAPI@app.task
def async_send_msg(phone, code):   #user/views.py send_msg不用了"""功能函數:發送短信驗證碼"""smsapi = YunTongXunAPI(**settings.MSG_CONFIG)sms_html = smsapi.run(phone, code)return sms_html
#user/views.py
from .tasks import async_send_active_email, async_send_msg
...# 3分鐘之內沒有發過:celery異步# sms_html = send_msg(phone,code)async_send_msg.delay(phone, code)# 2.存入redisMSG_CACHE.set(key, code, 180)return JsonResponse({"code": 200, "data": "發送成功"})

重啟celery

#發送短信,查看celery日志,查看redis存儲結果...: INFO/MainProcess] Task user.tasks.async_send_msg[36ca7635-b751-4948-b257-c5d422624d82] succeeded in 0.5160000000032596s: 

設計驗證

抓包請求

#注冊 查看xhr請求
Request URL: http://127.0.0.1:8000/v1/usersPayload:  {uname: "", password: "", phone: "17723452345", email: "", verify: "11111", carts: null}
#user/views.py
...
def users(request):"""注冊模塊視圖邏輯"""# 1.獲取請求體數據data = json.loads(request.body)uname = data.get('uname')password = data.get('password')phone = data.get('phone')email = data.get('email')# 獲取前端提交過來的短信驗證碼# 校驗短信驗證碼verify = data.get('verify')key = "sms_%s" % phoneredis_code = MSG_CACHE.get(key)if verify != str(redis_code):  # str 注意數據類型return JsonResponse({"code": 10112, "error": {"message": "code wrong"}})
...
#注冊驗證
http://localhost:7000/dadashop/templates/register_sms.html     

OAuth 2.0

授權碼模式(authorization code) 廣泛使用,其他了解

#微博   微連接創建網頁應用
https://open.weibo.com/apps/911505717/info/advanced
應用信息,高級信息,OAuth 2.0,授權回調頁:  編輯回調頁urlhttp://localhost:7000/dadashop/templates/callback.html#查看OAuth 2.0接口文檔
https://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI
"""
%E5%BE%AE%E5%8D%9A --》微博API  
涉及到url編碼問題,瀏覽器里帶中文的部分,通過urllib編碼使用如下
from urllib import parse
date = parse.urlencode(%E5%BE%AE%E5%8D%9A)
print(data)
"""    #授權頁示例,換成自己的client_id,和上面設置的回調url看是否進入授權頁面
https://api.weibo.com/oauth2/authorize?client_id=123456&redirect_uri=http://www.example.com/response&response_type=code#回調成功后查看url里是否多了code信息
http://www.example.com/response?code=CODE

請求授權

接口功能準備
#utils/weiboapi.py"""第三方微博登錄接口API
"""
import requests
from urllib import parse
from django.conf import settingsclass OAuthWeiboAPI:def __init__(self, client_id, client_secret, redirect_uri):self.client_id = client_idself.client_secret = client_secretself.redirect_uri = redirect_uridef get_grant_url(self):"""獲取微博授權登錄頁的地址"""# https://api.weibo.com/oauth2/authorize?client_id=123456&redirect_uri=http://www.example.com/response&response_type=codebase_url = "https://api.weibo.com/oauth2/authorize?"params = {"client_id": self.client_id,"redirect_uri": self.redirect_uri,"response_type": "code"}return base_url + parse.urlencode(params)if __name__ == '__main__':config = {"client_id": "22342872","client_secret": "e2a52dfasdg5d4b9185db1430735","redirect_uri": "http://localhost:7000/dadashop/templates/callback.html"}weibo_api = OAuthWeiboAPI(**config)grant_url = weibo_api.get_grant_url()print(grant_url)# 將打印的url放到瀏覽器里看是否跳到微博授權頁
抓包路由配置
#抓包路由 http://localhost:7000/dadashop/templates/login.html 
http://127.0.0.1:8000/v1/users/weibo/authorization        
#user/urls.py
...# 微博授權登錄頁: v1/users/weibo/authorizationpath('weibo/authorization', views.OAuthWeiboUrlView.as_view()),
功能函數設計
#user/views.py
...
from utils.weiboapi import OAuthWeiboAPIclass OAuthWeiboUrlView(View):def get(self, request):"""生成授權登錄頁的地址,返給前端由前端跳轉到授權登錄頁[window.location.href=]"""weibo_api = OAuthWeiboAPI(**settings.WEIBO_CONFIG)oauth_url = weibo_api.get_grant_url()# 返回響應result = {"code": 200, "oauth_url": oauth_url}return JsonResponse(result)

配置試圖函數使用的WEIBO_CONFIG

#dashopt/settings.py
...
#############微博登錄配置開始############
WEIBO_CONFIG = {"client_id": "9134235717","client_secret": "a6dbdca9b1b185bd762f6b8091","redirect_uri": "http://localhost:7000/dadashop/templates/callback.html"}
前端跳轉實現了解
//login.html 
...//異步獲取微博登陸地址$.ajax({type:'GET',url:baseUrl+'/v1/users/weibo/authorization',success:function(response){if(response.code==200){window.location.href=response.oauth_url//跳轉后端返回的oauth_url}else{alert('服務器異常')}
跳轉獲取授權碼
#注冊授權,查看是否跳轉
http://localhost:7000/dadashop/templates/callback.html #url跳轉授權回調頁,
http://localhost:7000/dadashop/templates/callback.html?code=1b710d828a02c3e506bedce5#xhr里自動請求到下一個路由(前端已經設計好了),需要進行下一步功能  
Request URL: http://127.0.0.1:8000/v1/users/weibo/users?code=1b710d828a02c3e506bedce5
前端跳轉實現了解
//callback.html
...
<script>var uid = ""var querystring = location.search   //獲取查詢部分 code=1b710d...window.onload=function(){$.ajax({url: baseUrl+'/v1/users/weibo/users'+querystring,type: 'get',dataType: "json",success: function (res) {if (res.code == 200) {//先清理本地存儲,再跳轉到主頁window.localStorage.clear();window.localStorage.setItem('dashop_token', res.token);window.localStorage.setItem('dashop_user', res.username);$('.query').css({display:"block"})$(".success").css({display:"none"})//none 隱藏了success  form_box注冊操作$('.form_box').css({display:"none"})setTimeout(()=>{window.location.href="index.html"//轉到主頁},3000)  // 3秒等待}else if(res.code == 201){$('.query').css({display:"none"})$(".success").css({display:"none"})$('.form_box').css({display:"block"})// access_token = res.access_tokenuid = res.uid}else{alert(res.error)}}})

獲取授權token

https://open.weibo.com/wiki/Oauth2/access_token

HTTP請求方式:POST,請求參數

參數必選類型說明
client_idtruestring第三方應用在微博開放平臺注冊的APPKEY。
client_secrettruestring在微博開放平臺注冊的應用所對應的AppSecret。
grant_typetruestring請求的類型,需填寫 authorization_code。
codetruestring調用第一步 authorize 接口所獲得的授權 code。
redirect_uritruestring授權回調地址,傳的值需與在開放平臺網站填寫的回調地址一致,設置填寫位置:“我的應用>應用信息>高級信息”。
配置獲取的路由
#user/urls.py  #自動跳轉需要的路由
...# 微博登錄[獲取授權令牌access_token]:v1/users/weibo/userspath('weibo/users', views.OAuthWeiboView.as_view()),
獲取toekn功能
#user/views.py
...
import requestsclass OAuthWeiboView(View):def get(self, request):"""生成授權登錄頁的地址,返給前端由前端跳轉到授權登錄頁[window.location.href=]"""# 1.獲取code[查詢字符串]code = request.GET.get("code")if not code:return JsonResponse({"code": 10112, "error": "Not code"})# 2.post請求post_url = "https://api.weibo.com/oauth2/access_token"post_data = {"client_id": settings.WEIBO_CONFIG["client_id"],"client_secret": "ab504366dbb185bd762f6b8091","code":code,"grant_type":"authorization_code","redirect_uri":"http://localhost:7000/dadashop/templates/callback.html",}access_html = requests.post(url=post_url,data=post_data).json()print('---------------get access token---------')print(access_html)return JsonResponse({'code': 200})
#瀏覽器里重新微博登錄下,授權3秒等待再跳轉到主頁  見上面的前端跳轉實現了解
xhr請求 Request URL: http://127.0.0.1:8000/v1/goods/index #需設計#終端查看獲得的token
...."GET /v1/users/weibo/authorization HTTP/1.1" 200 189
---------------get access token---------
{'access_token': '2.00mytczH0HRagz1699aJeq4NC', 'remind_in': '157679999', 'expires_in': 157679999, 'uid': '73207972', 'isRealName': 'true'}
優化到工具類里
#utils/weiboapi.py
import requests
from django.conf import settings
#...
class OAuthWeiboAPI:
#...def get_access_token(self, code):"""獲取access_token接口"""post_url = "https://api.weibo.com/oauth2/access_token"post_data = {"client_id": settings.WEIBO_CONFIG["client_id"],"client_secret": settings.WEIBO_CONFIG["client_secret"],"grant_type": "authorization_code","code": code,"redirect_uri":settings.WEIBO_CONFIG["redirect_uri"]}access_html = requests.post(url=post_url, data=post_data).json()# 獲取access_token成功if access_html.get("access_token"):return access_htmlraise Exception("get access token failed")
#user/views.py
#....# 2.post請求try:weibo_api = OAuthWeiboAPI(**settings.WEIBO_CONFIG)access_html = weibo_api.get_access_token(code)except Exception as e:print(e)return JsonResponse({"code": 10113, "error": "weibo server is busy"})# 成功獲取到access_tokenprint('---- get access token success ----')print(access_html)return JsonResponse({'code': 200})

驗證

#重新注冊,查看跳轉,token打印,準備設計表,入庫token
{'access_token': '2.00mytczH0HRagz1699aJeq4NC', 'remind_in': '157679999', 'expires_in': 157679999, 'uid': '73207972', 'isRealName': 'true'
}

token入庫表設計

#user/models.py
...
class WeiboProfile(BaseModel):"""微博用戶表"""# 外鍵 和用戶表一對一# 因為微博數據存入時,可能還沒有正式用戶,設置外鍵允許為nulluser_profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, null=True)# db_index:因為后期大量查詢wuid = models.CharField(verbose_name="微博uid", max_length=10, db_index=True, unique=True)access_token = models.CharField(verbose_name="微博授權令牌", max_length=32)class Meta:db_table = "user_weibo_profile"> python manage.py makemigrations
> python manage.py migrate        
前端根據返回狀態碼返回頁面
//callback.html
...
<script>var uid = ""var querystring = location.search   //獲取查詢部分 code=1b710d...window.onload=function(){$.ajax({url: baseUrl+'/v1/users/weibo/users'+querystring,type: 'get',dataType: "json",success: function (res) {if (res.code == 200) {//先清理本地存儲,再跳轉到主頁window.localStorage.clear();window.localStorage.setItem('dashop_token', res.token);window.localStorage.setItem('dashop_user', res.username);//block顯示,none隱藏  根據返回的201  200 跳轉頁面       $('.query').css({display:"block"})// 請稍后$(".success").css({display:"none"})//登錄成功//none 隱藏了success  $('.form_box').css({display:"none"})// 輸入登錄名、手機號信息綁定setTimeout(()=>{window.location.href="index.html"//轉到主頁},3000)  // 3秒等待}else if(res.code == 201){$('.query').css({display:"none"})$(".success").css({display:"none"})$('.form_box').css({display:"block"})// access_token = res.access_tokenuid = res.uid}else{alert(res.error)}}})
#user/views.py
from .models import Address, WeiboProfile
#....        # 2.post請求try:weibo_api = OAuthWeiboAPI(**settings.WEIBO_CONFIG)access_html = weibo_api.get_access_token(code)except Exception as e:print(e)return JsonResponse({"code": 10113, "error": "weibo server is busy"})# 成功獲取到access_tokenprint('---- get access token success ----')print(access_html)# 獲取wuid和access_tokenwuid = access_html.get('uid')access_token = access_html.get('access_token')"""微博表中查看該wuid是否存在情況1:用戶第一次微博登錄[201]情況2:用戶之前掃碼登錄過2.1 已經和正式用戶綁定過[200]2.2 在綁定注冊頁不填寫用戶名手機號信息,關閉頁面[201]200響應:{"code":200, "username":xxx, "token": token}201響應:{"code"201,"uid": wuid}"""try:weibo_user = WeiboProfile.objects.get(wuid=wuid)except Exception as e:# 用戶第一次掃碼登錄WeiboProfile.objects.create(wuid=wuid, access_token=access_token)# 返回201,到綁定注冊頁return JsonResponse({"code": 201, "uid": wuid})else:# 情況1:已和正式用戶綁定# 情況2:掃過碼,但是并未綁定user = weibo_user.user_profileif user:token = make_token(user.username)result = {"code": 200,"username": user.username,"token": token}return JsonResponse(result)else:result = {"code": 201,"uid": wuid}return JsonResponse(result)

驗證

#登錄頁注冊再次提交,授權登錄驗證  因第一次,返回201  進入綁定手機號郵箱頁面
http://localhost:7000/dadashop/templates/callback.html?code=3743ffa4c057f33c26d1e85fc36c23e3#補充信息提交,
Request URL: http://127.0.0.1:8000/v1/users/weibo/users  405 Method Not AllowedPayload: {"uid": "736547972","username": "user03","password": "123456","phone": "17723452345","email": "65733058@qq.com"}設計提交試圖,獲取數據,完成綁定

設計提交功能

#user/views.py
class OAuthWeiboView(View):
#...def post(self, request):"""綁定注冊視圖邏輯1.獲取請求體數據2.存入用戶表[UserProfile]3.兩個用戶綁定[更新外鍵-user_profile]4.組織數據返回"""data = json.loads(request.body)username = data.get("username")password = data.get("password")email = data.get("email")phone = data.get("phone")uid = data.get("uid")# 處理密碼m = md5()m.update(password.encode())pwd_md5 = m.hexdigest()# 創建正式用戶[create]并和微博用戶綁定[update]# 事務with transaction.atomic():sid = transaction.savepoint()try:# 創建正式用戶[UserProfile]user = UserProfile.objects.create(username=username, password=pwd_md5, email=email, phone=phone)# 更新外鍵[WeiboProfile]weibo_user = WeiboProfile.objects.get(wuid=uid)weibo_user.user_profile = userweibo_user.save()except Exception as e:print("bind user error", e)# 回滾transaction.savepoint_rollback(sid)return JsonResponse({"code": 10114, "error": "database error"})# 提交事務transaction.savepoint_commit(sid)# 1.發送激活郵件verify_url = get_verify_url(username) #下面重構功能函數async_send_active_email.delay(email, verify_url)# 2.簽發tokentoken = make_token(username)# 3.組織數據返回result = {"code": 200,"username": username,"token": token}return JsonResponse(result)

功能函數:生成郵件激活鏈接

#user/views.pydef get_verify_url(uname):"""功能函數:生成郵件激活鏈接"""# http://127.0.0.1:7000/dadashop/templates/active.html?code=xxx# code: base64(1016_username)code_num = "%d" % random.randint(1000, 9999)code_str = "%s_%s" % (code_num, uname)code = base64.urlsafe_b64encode(code_str.encode()).decode()# 存入redis[key-value] email_active_usernamekey = "email_active_%s" % unameCODE_MSG.set(key, code_num, 3600 * 24 * 3)# 生成激活鏈接verify_url = "http://127.0.0.1:7000/dadashop/templates/active.html?code=%s" % codereturn verify_url

再次注冊驗證

#登錄,注冊,授權,綁定郵箱信息  ,收件箱

二、微博登錄流程梳理

  • 微博開放平臺

    • 注冊微博開放平臺用戶,并進行實名認證

    • 創建應用

      • 控制臺-應用基本信息:App Key 、App Secret
      • 控制臺-應用高級信息:設置回調地址
    • 關于回調地址

      回調地址不能出現127.0.0.1,必須為域名[localhost]

  • 第三方微博登錄功能梳理

    • 用戶:登錄頁點擊微博登錄,xhr請求到后端索要微博授權登錄頁地址

    • 后端:視圖函數中生成微博授權登錄頁地址【微博接口文檔】,返給前端

    • 前端:重定向到微博授權登錄頁地址【login.html】

      window.location.href=response.oauth_url

    • 用戶:輸入微博賬號和密碼 或者 掃碼,確認授權并登錄

    • 微博:校驗微博賬號和密碼信息,如果正確則跳轉到回調地址【微博開放平臺設置】,在回調地址中添加授權碼的查詢參數

    • 前端:移花接木,把授權碼code從回調地址【7000端口】取出來,放到后端路由【8000端口】發送xhr請求

      var querystring = location.search
      $.ajax({url:baseUrl+'v1/users/weibo/users' + querystring
      })
      
    • 后端:獲取授權碼[request.GET.get()],向微博發請求【微博開發文檔】獲取授權令牌【access_token】

      {“uid”:“xxx”,“access_token”:“xxx”,…}

    • 后端:獲取到授權令牌后,創建微博表并存儲數據,并執行綁定注冊流程

      后端和前端協商狀態碼:

      200: 說明用戶之前已經使用微博登錄過并和正式用戶做了綁定,直接簽發token并跳轉到主頁【index.html】

      201:說明用戶之前并沒有和正式用戶綁定過,跳轉到綁定注冊頁面

    • 前端:根據狀態碼決定頁面跳轉

      200:跳轉到index.html

      201:跳轉到綁定注冊頁面【讓用戶填寫注冊相關信息】

    • 用戶:填寫注冊信息,點擊提交,發送xhr請求到后端

    • 后端:把該用戶存入正式用戶表并和當前微博用戶做好關聯

access_token使用:服務器端獲取到該用戶的access_token后,可以在微博開放平臺-我的應用-接口管理,獲取該用戶的相關資源【微博開放出來的資源】

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-qV8dt0GN-1688875149467)(project-pictures/09_第三方微博登錄流程圖.png)]

pip切換源

sudo pip3 install 模塊名 -i https://pypi.tuna.tsinghua.edu.cn/simple/1.阿里云 http://mirrors.aliyun.com/pypi/simple/
2.豆瓣http://pypi.douban.com/simple/
3.清華大學 https://pypi.tuna.tsinghua.edu.cn/simple/
4.中國科學技術大學 http://pypi.mirrors.ustc.edu.cn/simple/
5.華中科技大學http://pypi.hustunique.com/   pip3 freeze | grep -i  'redis'    
> pip3  install django_redis -i https://pypi.tuna.tsinghua.edu.cn/simple/
> 離線安裝- 下載安裝包[官網].tar.gz- 解壓:tar -zxvf  xxx.tar.gz- 到解壓目錄尋找:setup.py   [README文件中有安裝說明]- 安裝:sudo python3 setup.py  install     > python manage.py shell
>>> from django.core.cache import cache
>>> cache.set("zhaoliying",1016)
True  #  redis  里1號庫查看驗證,默認過期的事件是300s

:說明用戶之前并沒有和正式用戶綁定過,跳轉到綁定注冊頁面

  • 前端:根據狀態碼決定頁面跳轉

    200:跳轉到index.html

    201:跳轉到綁定注冊頁面【讓用戶填寫注冊相關信息】

  • 用戶:填寫注冊信息,點擊提交,發送xhr請求到后端

  • 后端:把該用戶存入正式用戶表并和當前微博用戶做好關聯

access_token使用:服務器端獲取到該用戶的access_token后,可以在微博開放平臺-我的應用-接口管理,獲取該用戶的相關資源【微博開放出來的資源】

[外鏈圖片轉存中…(img-qV8dt0GN-1688875149467)]

pip切換源

sudo pip3 install 模塊名 -i https://pypi.tuna.tsinghua.edu.cn/simple/1.阿里云 http://mirrors.aliyun.com/pypi/simple/
2.豆瓣http://pypi.douban.com/simple/
3.清華大學 https://pypi.tuna.tsinghua.edu.cn/simple/
4.中國科學技術大學 http://pypi.mirrors.ustc.edu.cn/simple/
5.華中科技大學http://pypi.hustunique.com/   pip3 freeze | grep -i  'redis'    
> pip3  install django_redis -i https://pypi.tuna.tsinghua.edu.cn/simple/
> 離線安裝- 下載安裝包[官網].tar.gz- 解壓:tar -zxvf  xxx.tar.gz- 到解壓目錄尋找:setup.py   [README文件中有安裝說明]- 安裝:sudo python3 setup.py  install     > python manage.py shell
>>> from django.core.cache import cache
>>> cache.set("zhaoliying",1016)
True  #  redis  里1號庫查看驗證,默認過期的事件是300s

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/215410.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/215410.shtml
英文地址,請注明出處:http://en.pswp.cn/news/215410.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Docker安裝與使用

Docker 1.初識Docker Docker如何解決大型項目依賴關系復雜&#xff0c;不同組件依賴的兼容性問題&#xff1f; Docker允許開發中將應用、依賴、函數庫、配置一起打包&#xff0c;形成可移植鏡像Docker應用運行在容器中&#xff0c;使用沙箱機制&#xff0c;相互隔離 Docker…

phpstorm中使用 phpunit 時的配置和代碼覆蓋率測試注意點

初始化一個composer項目&#xff0c;composer.json配置文件如下 {"name": "zingfront/questions-php","type": "project","require": {"php": "^7.4"},"require-dev": {"phpunit/phpun…

geemap學習筆記024:從Earth Engine中獲取遙感圖像的縮略圖

前言 遙感圖像的縮略圖通常是以較小的數據量對整景影像有一個全面的展示&#xff0c;便于分享和觀察&#xff0c;本節就介紹一下如何獲取遙感圖像的縮略圖。 1 導入庫并顯示地圖 import ee import geemap import osee.Initialize() Map geemap.Map() Map2 加載數據 roi e…

多維時序 | MATLAB實現RIME-CNN-BiLSTM-Multihead-Attention多頭注意力機制多變量時間序列預測

多維時序 | MATLAB實現RIME-CNN-BiLSTM-Multihead-Attention多頭注意力機制多變量時間序列預測 目錄 多維時序 | MATLAB實現RIME-CNN-BiLSTM-Multihead-Attention多頭注意力機制多變量時間序列預測預測效果基本介紹模型描述程序設計參考資料 預測效果 基本介紹 MATLAB實現RIME-…

項目管理工具:選品開發管理的最佳實踐

Zoho Projects是一個功能強大的項目管理工具&#xff0c;可以幫助電商企業實現選品開發過程的有序管理&#xff0c;提升選品開發效率。 以下是使用Zoho Projects進行選品開發管理的步驟&#xff1a; 1.創建項目&#xff1a; 登錄Zoho Projects&#xff0c;在主頁上點擊"新…

NSSCTF Crypto靶場練習,21-30wp

文章目錄 [AFCTF 2018]你能看出這是什么加密么[LitCTF 2023]你是我的關鍵詞(Keyworld)[NSSCTF 2022 Spring Recruit]classic[SWPUCTF 2021 新生賽]crypto4[LitCTF 2023]家人們&#xff01;誰懂啊&#xff0c;RSA簽到都不會 (初級)[SWPUCTF 2021 新生賽]crypto5[LitCTF 2023]Is …

亞信科技AntDB攜手藍凌軟件,助推企業數字化辦公轉型升級

隨著企業數字化轉型的深入&#xff0c;企業對于協同辦公、移動門戶、數字運營、智能客服等方面的需求越來越高&#xff0c;數智化正成為催生新動能和新優勢的關鍵力量。數字化的辦公平臺可以幫助企業實現各類信息、流程的集中化、數字化和智能化管理&#xff0c;為企業管理者提…

面試 JVM 八股文五問五答第一期

面試 JVM 八股文五問五答第一期 作者&#xff1a;程序員小白條&#xff0c;個人博客 相信看了本文后&#xff0c;對你的面試是有一定幫助的&#xff01; ?點贊?收藏?不迷路&#xff01;? 1.JVM內存布局 Heap (堆區&#xff09; 堆是 OOM 故障最主要的發生區域。它是內存…

大數據畢業設計之前端03:logo、menu的折疊展開實現

關鍵字&#xff1a;BuildAdmin、pinia、logo、aside、menu、菜單折疊、Vue、ElementUI 前言 上一篇文章中&#xff0c;借助aside的實現講了一些開發的小技巧&#xff0c;以及css的解讀。本篇文章主要寫一下如何填充aside的內容。 aside主要是由兩個部分組成的&#xff1a;log…

數據結構與算法-Rust 版讀書筆記-2線性數據結構-棧

數據結構與算法-Rust 版讀書筆記-2線性數據結構-棧 一、線性數據結構概念 數組、棧、隊列、雙端隊列、鏈表這類數據結構都是保存數據的容器&#xff0c;數據項之間的順序由添加或刪除時的順序決定&#xff0c;數據項一旦被添加&#xff0c;其相對于前后元素就會一直保持位置不…

電腦入門基礎知識

1.電腦鍵盤個數一般都是有多少個&#xff1f; 答&#xff1a;一般情況下&#xff0c;電腦鍵盤只有一個。但是&#xff0c;也有一些特殊的情況&#xff0c;例如游戲玩家可能會使用額外的游戲鍵盤&#xff0c;或者一些專業人士可能會使用多個鍵盤來提高工作效率。但是在大多數情…

[Spring~源碼] ControllerAdvice揭秘

在Spring MVC中&#xff0c;我們經常使用ControllerAdvice注解&#xff0c;可以實現全局統一異常處理、全局數據綁定等功能。但是&#xff0c;它的實現原理是什么呢&#xff1f;在本文中&#xff0c;我們將深入探究ControllerAdvice的實現原理。 文章目錄 什么是ControllerAdvi…

docker-compose.yml文件配置詳解

簡介 Compose 是用于定義和運行多容器 Docker 應用程序的工具。通過 Compose&#xff0c;您可以使用 YML 文件來配置應用程序需要的所有服務。然后&#xff0c;使用一個命令&#xff0c;就可以從 YML 文件配置中創建并啟動所有服務。 docker compose文件是一個yaml格式的文件&a…

【Hadoop_04】HDFS的API操作與讀寫流程

1、HDFS的API操作1.1 客戶端環境準備1.2 API創建文件夾1.3 API上傳1.4 API參數的優先級1.5 API文件夾下載1.6 API文件刪除1.7 API文件更名和移動1.8 API文件詳情和查看1.9 API文件和文件夾判斷 2、HDFS的讀寫流程&#xff08;面試重點&#xff09;2.1 HDFS寫數據流程2.2 網絡拓…

學會面向對象經典練習題21道

1.面向對象練習&#xff1a;設計小狗類 需求&#xff1a; 抽象形成一個小狗類Dog 屬性&#xff1a;名字name 年齡age 品種kind 主人host 價格price 功能&#xff1a; 跑run&#xff1a;無參&#xff0c;打印&#xff1a;小狗Dog跑的老快了~ 吃eat&#xff1a;參數int n&#x…

當MongoDB主鍵為String時,mongoTemplate無法根據id查詢的問題

MongoDB推薦使用ObjectId作為主鍵&#xff0c;但國內的開發都知道&#xff0c;事情往往不如人所愿&#xff0c;當我們真的出現了“_id”主鍵的類型為String時&#xff0c;且還必須想用mongoTemplate.findOne或findList時&#xff0c;直接使用該方法會導致查詢結果為空。 因為m…

https 協議

目錄 加密方式 對稱加密 非對稱加密 非對稱加密 非對稱加密 非對稱加密 對稱加密 AC證書 AC證書內容 數據摘要 數據簽名 在我們前面學習的http協議里面&#xff0c;我們發送的內容都是明文傳輸的&#xff0c;所以在安全上并不安全&#xff0c;但是在現在信息發達的時…

Java高級技術:優化性能與擴展性的最佳實踐

標題&#xff1a;Java高級技術&#xff1a;優化性能與擴展性的最佳實踐 摘要&#xff1a;本文將介紹Java中一些高級技術&#xff0c;以提高性能和代碼的擴展性。本文不包括反射和并發編程&#xff0c;旨在幫助開發者進一步提升Java應用程序的質量和可維護性。 優化性能的最佳實…

面試題目總結(三)

1. Spring、Springboot、springMVC、Spring Cloud 的區別&#xff1a; Spring&#xff1a;Spring 是一個開源的、輕量級的Java框架&#xff0c;提供了豐富的功能和組件&#xff0c;用于構建企業級應用程序。Spring框架包含了很多模塊&#xff0c;包括核心容器、數據訪問、事物…

MATLAB算法實戰應用案例精講-【數模應用】漫談機器學習(七)

目錄 幾個高頻面試題目 機器學習算法工程師需要掌握哪些編程語言? 1.Python 2. C# 3.JavaScript 4. R 5.Java