欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python的Flask框架應(yīng)用程序?qū)崿F(xiàn)使用QQ賬號登錄的方法

 更新時間:2016年06月07日 18:26:36   作者:digwtx  
利用QQ開放平臺的API使用QQ賬號登錄是現(xiàn)在很多網(wǎng)站都具備的功能,而對于Flask框架來說則有Flask-OAuthlib這個現(xiàn)成的輪子,這里我們就來看一下Python的Flask框架應(yīng)用程序?qū)崿F(xiàn)使用QQ賬號登錄的方法

Flask-OAuthlib是OAuthlib的Flask擴展實現(xiàn),
項目地址:
https://github.com/lepture/flask-oauthlib
主要特性:

  • 支持OAuth 1.0a, 1.0, 1.1, OAuth2客戶端
  • 友好的API(和Flask-OAuth一樣)
  • 與Flask直接整合
  • 等等……

Flask-OAuthlib提供了多個開放平臺的示例代碼,比如Google, Facebook, Twiter, Github, Dropbox, 豆瓣, 微博等,只是暫時沒有QQ登錄的示例代碼。

QQ OAuth登錄示例
下面是QQ登錄的代碼:

import os
import json
from flask import Flask, redirect, url_for, session, request, jsonify, Markup
from flask_oauthlib.client import OAuth

QQ_APP_ID = os.getenv('QQ_APP_ID', '101187283')
QQ_APP_KEY = os.getenv('QQ_APP_KEY', '993983549da49e384d03adfead8b2489')

app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
oauth = OAuth(app)

qq = oauth.remote_app(
  'qq',
  consumer_key=QQ_APP_ID,
  consumer_secret=QQ_APP_KEY,
  base_url='https://graph.qq.com',
  request_token_url=None,
  request_token_params={'scope': 'get_user_info'},
  access_token_url='/oauth2.0/token',
  authorize_url='/oauth2.0/authorize',
)


def json_to_dict(x):
  '''OAuthResponse class can't not parse the JSON data with content-type
  text/html, so we need reload the JSON data manually'''
  if x.find('callback') > -1:
    pos_lb = x.find('{')
    pos_rb = x.find('}')
    x = x[pos_lb:pos_rb + 1]
  try:
    return json.loads(x, encoding='utf-8')
  except:
    return x


def update_qq_api_request_data(data={}):
  '''Update some required parameters for OAuth2.0 API calls'''
  defaults = {
    'openid': session.get('qq_openid'),
    'access_token': session.get('qq_token')[0],
    'oauth_consumer_key': QQ_APP_ID,
  }
  defaults.update(data)
  return defaults


@app.route('/')
def index():
  '''just for verify website owner here.'''
  return Markup('''<meta property="qc:admins" '''
         '''content="226526754150631611006375" />''')


@app.route('/user_info')
def get_user_info():
  if 'qq_token' in session:
    data = update_qq_api_request_data()
    resp = qq.get('/user/get_user_info', data=data)
    return jsonify(status=resp.status, data=resp.data)
  return redirect(url_for('login'))


@app.route('/login')
def login():
  return qq.authorize(callback=url_for('authorized', _external=True))


@app.route('/logout')
def logout():
  session.pop('qq_token', None)
  return redirect(url_for('get_user_info'))


@app.route('/login/authorized')
def authorized():
  resp = qq.authorized_response()
  if resp is None:
    return 'Access denied: reason=%s error=%s' % (
      request.args['error_reason'],
      request.args['error_description']
    )
  session['qq_token'] = (resp['access_token'], '')

  # Get openid via access_token, openid and access_token are needed for API calls
  resp = qq.get('/oauth2.0/me', {'access_token': session['qq_token'][0]})
  resp = json_to_dict(resp.data)
  if isinstance(resp, dict):
    session['qq_openid'] = resp.get('openid')

  return redirect(url_for('get_user_info'))


@qq.tokengetter
def get_qq_oauth_token():
  return session.get('qq_token')


if __name__ == '__main__':
  app.run()

主要流程:

  • 訪問QQ互聯(lián)網(wǎng)站 http://connect.qq.com/ 注冊成為開發(fā)者,并申請應(yīng)用,申請應(yīng)用時需要驗證網(wǎng)站所有權(quán);
  • 應(yīng)用申請好之后,把QQ_APP_ID和QQ_APP_KEY替換為你的應(yīng)用的;
  • 訪問/login,然后會跳轉(zhuǎn)到QQ的授權(quán)驗證網(wǎng)頁;
  • QQ驗證通過之后,會跳轉(zhuǎn)回到/login/authorized,并獲取access_token;
  • 得到access_token之后,通過access_token獲取openid,access_token和openid是后期調(diào)用其它API的必要參數(shù);
  • 跳轉(zhuǎn)到/user_info,獲取并顯示登錄用戶的基本信息。

更多信息請參閱Flask-OAuthlib文檔和QQ互聯(lián)文檔:

https://flask-oauthlib.readthedocs.org/
http://wiki.connect.qq.com/
關(guān)于SAE平臺的特別說明
在SAE平臺上,授權(quán)過程沒有任何問題,當(dāng)獲取到access_token之后,調(diào)用API時,會在請求時(比如get, put)附加類似如下的請求頭:

headers = {u'Authorization': u'Bearer 83F40E96FB6882686F4DF1E17105D04E'}

這個請求頭會引發(fā)HTTPError: HTTP Error 400: Bad request,造成請求失敗。解決的辦法是把鍵名轉(zhuǎn)換成str類型,Hack代碼如下:

def convert_keys_to_string(dictionary):
  """Recursively converts dictionary keys to strings."""
  if not isinstance(dictionary, dict):
    return dictionary
  return dict((str(k), convert_keys_to_string(v))
    for k, v in dictionary.items())

def change_qq_header(uri, headers, body):
  headers = convert_keys_to_string(headers)
  return uri, headers, body

qq.pre_request = change_qq_header

當(dāng)項目部署在SAE平臺時,將這段代碼放在if __name__ == '__main__'語句之前即可。

小結(jié)
OAuth2登錄驗證還是比較容易的,絕大多數(shù)的平臺都支持標準的協(xié)議,使用通用的庫可以簡化開發(fā)流程。另外,QQ登錄的代碼已經(jīng)提交到Flask-OAuthlib代碼庫了。

相關(guān)文章

  • 詳解sklearn?Preprocessing?數(shù)據(jù)預(yù)處理功能

    詳解sklearn?Preprocessing?數(shù)據(jù)預(yù)處理功能

    這篇文章主要介紹了sklearn?Preprocessing?數(shù)據(jù)預(yù)處理功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-08-08
  • pygame時序模塊time的具體使用

    pygame時序模塊time的具體使用

    Pygame Time模塊能夠幫助你更好地控制幀率和時間,從而增強游戲的可玩性,本文主要介紹了pygame時序模塊time的具體使用,具有一定的參考價值,感興趣的可以了解一下
    2023-12-12
  • pycharm右鍵沒有run,run不了問題的解決

    pycharm右鍵沒有run,run不了問題的解決

    這篇文章主要介紹了pycharm右鍵沒有run,run不了問題的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 對python的輸出和輸出格式詳解

    對python的輸出和輸出格式詳解

    今天小編就為大家分享一篇對python的輸出和輸出格式詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • Python高階函數(shù)map()?簡介和使用詳解

    Python高階函數(shù)map()?簡介和使用詳解

    map()?函數(shù)是Python中的內(nèi)置函數(shù),這個函數(shù)又叫做映射函數(shù),其實里面具有一個迭代器的功能,會依次遍歷可迭代對象進行相關(guān)的操作,這篇文章主要介紹了Python高階函數(shù)map()?簡介和使用詳解,需要的朋友可以參考下
    2023-03-03
  • Python使用PyMuPDF實現(xiàn)添加PDF水印

    Python使用PyMuPDF實現(xiàn)添加PDF水印

    在日常工作中,我們經(jīng)常需要對PDF文件進行處理,其中一項常見的需求是向PDF文件添加水印,本文將介紹如何使用Python編程語言和PyMuPDF庫在PDF文件中添加水印,感興趣的可以了解一下
    2023-08-08
  • python數(shù)據(jù)庫操作指南之PyMysql使用詳解

    python數(shù)據(jù)庫操作指南之PyMysql使用詳解

    PyMySQL是在Python3.x版本中用于連接MySQL服務(wù)器的一個庫,Python2 中則使用mysqldb,下面這篇文章主要給大家介紹了關(guān)于python數(shù)據(jù)庫操作指南之PyMysql使用的相關(guān)資料,需要的朋友可以參考下
    2023-03-03
  • Linux上使用Python統(tǒng)計每天的鍵盤輸入次數(shù)

    Linux上使用Python統(tǒng)計每天的鍵盤輸入次數(shù)

    這篇文章主要介紹了Linux上使用Python統(tǒng)計每天的鍵盤輸入次數(shù),非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-04-04
  • python Zmail模塊簡介與使用示例

    python Zmail模塊簡介與使用示例

    這篇文章主要介紹了python Zmail模塊簡介與使用示例,幫助大家利用python收發(fā)郵件,感興趣的朋友可以了解下
    2020-12-12
  • Django獲取前端數(shù)據(jù)的實現(xiàn)方式

    Django獲取前端數(shù)據(jù)的實現(xiàn)方式

    這篇文章主要介紹了Django獲取前端數(shù)據(jù)的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02

最新評論