官术网_书友最值得收藏!

Creating the Flask application

Perfect, now let's add another file called twitter_auth.py in the twittervotes directory. We are going to create three functions in it but, first, let's add some imports:

from urllib.parse import parse_qsl

import yaml

from flask import Flask
from flask import render_template
from flask import request

import oauth2 as oauth

from core import read_config
from core.models import RequestToken

First, we import the parser_qls from the urllib.parse module to parse the returned query string, and the yaml module so we can read and write YAML configuration files. Then we import everything we need to build our Flask application. The last third-party module that we are going to import here is the oauth2 module, which will help us to perform the OAuth authentication.

Lastly, we import our function read_config and the RequestToken namedtuple that we just created.

Here, we create our Flask app and a few global variables that will hold values for the client, consumer, and the RequestToken instance:

app = Flask(__name__)

client = None
consumer = None
req_token = None

The first function that we are going to create is a function called get_req_token with the following content:

def get_oauth_token(config):

global consumer
global client
global req_token

consumer = oauth.Consumer(config.consumer_key,
config.consumer_secret)
client = oauth.Client(consumer)

resp, content = client.request(config.request_token_url, 'GET')

if resp['status'] != '200':
raise Exception("Invalid response
{}".format(resp['status']))

request_token = dict(parse_qsl(content.decode('utf-8')))

req_token = RequestToken(**request_token)

This function gets as argument an instance to the configuration and the global statements say to the interpreter that the consumer, client, and req_token used in the function will be referencing the global variables.

We create a consumer object using the consumer key and the consumer secret that we obtained when the Twitter app was created. When the consumer is created, we can pass it to the client function to create the client, then we call the function request, which, as the name suggests, will perform the request to Twitter, passing the request token URL.

When the request is complete, the response and the content will be stored in the variables resp and content. Right after that, we test whether the response status is not 200 or HTTP.OK; in that case, we raise an exception, otherwise we parse the query string to get the values that have been sent back to us and create a RequestToken instance.

主站蜘蛛池模板: 泰和县| 台安县| 皋兰县| 萍乡市| 德安县| 嘉祥县| 双辽市| 郑州市| 甘南县| 师宗县| 潍坊市| 河曲县| 金门县| 卢龙县| 漯河市| 平定县| 九龙县| 浦城县| 红安县| 正定县| 德庆县| 岑溪市| 安宁市| 盐亭县| 蒙自县| 方城县| 上饶县| 神木县| 隆德县| 洱源县| 城市| 墨竹工卡县| 闽侯县| 深泽县| 平武县| 诏安县| 汉源县| 大田县| 德令哈市| 桑植县| 南皮县|