Created
April 23, 2020 17:59
-
-
Save M4cs/0ea99c84f181876bfc81caecbe39e7f4 to your computer and use it in GitHub Desktop.
Twitter OAuth Tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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