The Python Flask framework application implements the login method using the QQ account, pythonflask

Source: Internet
Author: User
Tags oauth openid

The Python Flask framework application implements the login method using the QQ account, pythonflask

Flask-OAuthlib is the Flask extension Implementation of OAuthlib,
Project address:
Https://github.com/lepture/flask-oauthlib
Main features:

  • Supports OAuth 1.0a, 1.0, 1.1, and oau2client
  • Friendly API (same as Flask-OAuth)
  • Integrate directly with Flask
  • Wait ......

Flask-OAuthlib provides sample code for multiple open platforms, such as Google, Facebook, Twiter, Github, Dropbox, Douban, and weibo. It is only a sample code without QQ logon.

QQ OAuth logon example
The following is the QQ logon code:

import osimport jsonfrom flask import Flask, redirect, url_for, session, request, jsonify, Markupfrom flask_oauthlib.client import OAuthQQ_APP_ID = os.getenv('QQ_APP_ID', '101187283')QQ_APP_KEY = os.getenv('QQ_APP_KEY', '993983549da49e384d03adfead8b2489')app = Flask(__name__)app.debug = Trueapp.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 xdef 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.tokengetterdef get_qq_oauth_token():  return session.get('qq_token')if __name__ == '__main__':  app.run()

Main process:

  • Access QQ Internet site http://connect.qq.com/registered as a developer, and apply for applications, the application needs to verify the ownership of the site;
  • After the application is applied, replace QQ_APP_ID and QQ_APP_KEY with your application;
  • Access/login and go to the QQ authorization verification webpage;
  • After the QQ verification is passed, it will jump back to/login/authorized and get the access_token;
  • After obtaining access_token, obtain the openid through access_token. access_token and openid are necessary parameters for later calling other APIs;
  • Jump to/user_info to get and display the basic information of the logon user.

For more information, see Flask-OAuthlib and QQ interconnection documents:

Https://flask-oauthlib.readthedocs.org/
Http://wiki.connect.qq.com/
Special description on the SAE Platform
On the SAE platform, there is no problem with the authorization process. When the access_token is obtained and the API is called, a request header similar to the following will be appended to the request (such as get and put:

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

This request header will cause HTTPError: HTTP Error 400: Bad request, resulting in a request failure. The solution is to convert the key name to the str type. The Hack code is as follows:

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, bodyqq.pre_request = change_qq_header

When the project is deployed on the SAE platform, place the code before the if _ name _ = '_ main _' statement.

Summary
Oau2's logon verification is relatively easy, and most platforms support standard protocols. Using a common library can simplify the development process. In addition, the QQ login code has been submitted to the Flask-OAuthlib code base.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.