Login With Twitter using Python and Flask. - Softtalks

Featured Post

Should you use React Native to build your startup’s mobile app?

Should you use React Native to build your startup’s mobile app? Flexible application improvement is a jumbled system. It requires ...

Saturday, April 25, 2020

Login With Twitter using Python and Flask.

Login With Twitter using Python and Flask.


As of late while chipping away at a task I ran over an issue with attempting to execute Twitter Integrations into my Flask application. The entirety of the aides on Google was breaking or simply didn't fit in with my application. I needed a basic method to interface with Twitter's OAuth1 API yet everything was giving me mistakes.

Flask is the library I'm utilizing so as to make my principle webserver and perceptible courses. We don't utilize a lot of separated from the divert work from it in this. flask_restful is the REST library I'm utilizing so as to handily make a JSON based API. The endpoints we make in this are RESTful API Endpoints that acquire the Resource class from flask_restful. requests_oauthlib is the OAuth library I use so as to create the OAuth headers to verify with Twitter's API. We will likewise be utilizing the solicitations library so as to make demands server-side to Twitter.

First, you have to arrange a flagon application. Lets make an envelope called application first:



mkdir ./application

compact disc ./application

Presently from inside the application/index we will make a record called init.py :

# Let's import the Flask class from the cup library

from cup import Flask

# Let's import the Api class from the flask_restful library

from flask_restful import Api

# Let's import our OAuth library to arrangement

from requests_oauthlib.oauth1_auth import Client

# Create A Config To Store Values

config = {

'twitter_consumer_key': 'ENTER TWITTER CONSUMER KEY',

'twitter_consumer_secret': 'ENTER TWITTER CONSUMER SECRET'

}

# Initialize Our Flask App

application = Flask(__name__)

# Initialize Our RESTful API

programming interface = Api(app)

# Initialize Our OAuth Client

oauth = Client(config['twitter_consumer_key'], client_secret=config['twitter_consumer_secret'])

This is all we have to accomplish for the time being in the init.py record. Next, we will begin to make our endpoints for Twitter. This expects you to have arrangement a Twitter Application and you have your customer keys.

Next, we make our endpoint. For this, we can simply make a document called twitter.py or actually whatever you'd like. Next, we include:

# Import our capacities and Resource class from flask_restful

from flask_restful import Resource, reqparse

# Import our capacities from Flask

from flagon import divert

# Import our oauth object from our application

from application import oauth

# Import demands so as to make server sided demands

import demands

# We need to make our underlying endpoint to login with twitter

class TwitterAuthenticate(Resource):

# Here we are making it so this endpoint acknowledges GET demands

def get(self):

# We should produce our marked OAuth Headers

uri, headers, body = oauth.sign('https://twitter.com/oauth/request_token')

# We have to make a solicitation to twitter with the OAuth parameters we just made

res = requests.get(uri, headers=headers, data=body)

# This profits a string with OAuth factors we have to parse

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 reaction.

# Now we need to divert to the login URL utilizing our OAuth Token

return redirect('https://api.twitter.com/oauth/authenticate?oauth_token=' + oauth_token, 302)

This is our verification endpoint when someone endeavors to hit this it will divert them to the Twitter log in page which will at that point send them to our Callback URL which you ought to have an arrangement in your Twitter App's dashboard.

Next, we have to include the rationale for dealing with our callback URL. We can add this to a similar record as the TwitterAuthenticate class.

# We have to make a parser for that callback URL

def callback_parser():

parser = reqparse.RequestParser()

parser.add_argument('oauth_token')

parser.add_argument('oauth_verifier')

bring parser back

# Now we arrangement the Resource for the callback

class TwitterCallback(Resource):

def get(self):

parser = callback_parser()

args = parser.parse_args() # Parse our args into a dict

# We have to make a solicitation to twitter with this callback OAuth token

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('&')

# Now we have to parse our oauth token and mystery from the reaction

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]

# We currently approach the oauth token, oauth mystery, userID, and username of the individual who signed in.

# .... Accomplish more code here

# ....

return redirect('http://somwhere.com", 302)

This TwitterCallback class will parse and deal with the OAuth tokens so as to get to the client's record data. You can do anything you desire with this data whether that be putting away it into a DB User Model or making demands with Tweepy!

The last advance is adding these endpoints to your init.py document we made toward the start! At the base of the record include this:

from app.twitter import TwitterAuthenticate, TwitterCallback

api.add_resource(TwitterAuthenticate, '/validate/twitter')

api.add_resource(TwitterCallback, '/callback/twitter') # This MUST match your Callback URL you set in the Twitter App Dashboard!!!

Our last twitter.py should resemble this:

from flask_restful import Resource, reqparse

from cup import divert

from application import oauth

import demands

class TwitterAuthenticate(Resource):

def get(self):

uri, headers, body = oauth.sign('[https://twitter.com/oauth/request_token'](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 reaction.

return redirect('[https://api.twitter.com/oauth/authenticate?oauth_token='](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')

bring parser back

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='](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](http://somwhere.com)", 302)

Our last init.py should look something like:

from flagon 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'

}

application = Flask(__name__)

programming interface = Api(app)

oauth = Client(config['twitter_consumer_key'], client_secret=config['twitter_consumer_secret'])

from app.twitter import TwitterAuthenticate, TwitterCallback

api.add_resource(TwitterAuthenticate, '/verify/twitter')

api.add_resource(TwitterCallback, '/callback/twitter')

I trust you discover this guide accommodating and have a great time coordinating with Twitter's User API!

No comments:

Post a Comment