Skip to content

Instantly share code, notes, and snippets.

@M4cs
Created Apr 23, 2020
Embed
What would you like to do?
Twitter OAuth Tutorial
from flask import Flask
from flask_restful import Api
from requests_oauthlib.oauth1_auth import Client
config = {
'twitter_consumer_key': 'ENTER TWITTER CONSUMER KEY',
'twitter_consumer_secret': 'ENTER TWITTER CONSUMER SECRET'
}
app = Flask(__name__)
api = Api(app)
oauth = Client(config['twitter_consumer_key'], client_secret=config['twitter_consumer_secret'])
from app.twitter import TwitterAuthenticate, TwitterCallback
api.add_resource(TwitterAuthenticate, '/authenticate/twitter')
api.add_resource(TwitterCallback, '/callback/twitter')
from flask_restful import Resource, reqparse
from flask import redirect
from app import oauth
import requests
class TwitterAuthenticate(Resource):
def get(self):
uri, headers, body = oauth.sign('https://twitter.com/oauth/request_token')
res = requests.get(uri, headers=headers, data=body)
res_split = res.text.split('&') # Splitting between the two params sent back
oauth_token = res_split[0].split('=')[1] # Pulling our APPS OAuth token from the response.
return redirect('https://api.twitter.com/oauth/authenticate?oauth_token=' + oauth_token, 302)
def callback_parser():
parser = reqparse.RequestParser()
parser.add_argument('oauth_token')
parser.add_argument('oauth_verifier')
return parser
class TwitterCallback(Resource):
def get(self):
parser = callback_parser()
args = parser.parse_args() # Parse our args into a dict
res = requests.post('https://api.twitter.com/oauth/access_token?oauth_token=' + args['oauth_token'] + '&oauth_verifier=' + args['oauth_verfier']])
res_split = res.text.split('&')
oauth_token = res_split[0].split('=')[1]
oauth_secret = res_split[1].split('=')[1]
userid = res_split[2].split('=')[1]
username = res_split[3].split('=')[1]
# ... Do Code Here
return redirect('http://somwhere.com", 302)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment