So far we acquired the user authentication token in the command line. This works at development time, but our users need a more friendly way to hand over their tokens. Let’s look what we need to do to use Tweepy in a Flask application and how we can get the user token from Twitter.
This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.
Don’t use Flask-Tweepy
There is a package called Flask-Tweepy on PyPi.org, but it got its last commit in 2012. Do not try to use it and instead use Tweepy directly in Flask.
Match the port to the configured redirect URL
In the App configuration on the Twitter developer portal, you can specify a redirect URL. You can set it to localhost and choose a port that works for you. Make sure that you set this port in your Flask app at the end of your file (for my application I need to set it to port 6006):
1 2 |
if(__name__ == "__main__"): app.run(port=6006) |
Prepare Tweepy
As with the command line applications, we need a bit of preparation to get the configuration in place. I use once more the .env files to protect my Twitter keys:
1 2 3 4 5 6 7 8 9 10 11 12 |
import flask from flask import redirect, request import tweepy import random import os from dotenv import load_dotenv load_dotenv() api_key = os.getenv('api-key') api_secret = os.getenv('api-key-secret') app = flask.Flask(__name__) |
Ask Twitter for the user tokens
Tweepy creates the authorisation URL with the Twitter endpoints for us. But instead of letting the user click on the link, we can redirect the user in our Flask application:
1 2 3 4 |
@app.route('/') def index(): auth = tweepy.OAuthHandler(api_key, api_secret) return redirect(auth.get_authorization_url()) |
Extract the user tokens
The interesting part of the authentication process happens when the user is redirected back from Twitter to your application. The user accepted the permissions for your application and now we need to turn the token we get back in the redirect URL into a user token and a secret:
1 2 3 4 5 6 7 8 9 10 11 |
@app.route('/callback', methods=['GET', 'POST']) def callback(): args = request.args oauth_token = args['oauth_token'] oauth_verifier = args['oauth_verifier'] auth = tweepy.OAuthHandler(api_key, api_secret) auth.request_token = {'oauth_token': oauth_token, 'oauth_token_secret': oauth_verifier} auth.get_access_token(oauth_verifier) user_tokens = f"access-token={auth.access_token}<br>access-token-secret={auth.access_token_secret}" return user_tokens |
Most tutorials skip this important step, and if you try to figure this code out on yourself you will understand why. It is a pain and looks ugly, but it works.
Work with the user tokens
In this post I put the user tokens in the .env file. In a real web application, you would put them to the user object or into the session. How to use sessions in Flask will be part of a different post.
We need to initialise Tweepy with the user tokens as we did in the command line application before we can access Twitter on behalf of the user:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@app.route('/tweet') def tweet(): # You would read these values from the session user_token = os.getenv('access-token') user_token_secret = os.getenv('access-token-secret') auth = tweepy.OAuthHandler(api_key, api_secret) auth.set_access_token(user_token,user_token_secret) api = tweepy.API(auth) # Create a tweet - random() to not write same tweet twice api.update_status(f"A Tweet from Flask - {random.random()}") return "Tweet send with Flask" |
If you go to /tweet in your application, Tweepy will post a tweet:
Next
We now can fetch the user tokens in a user-friendly way. Next week we start to explore the Twitter API and iterate through our friends and followers.
1 thought on “Python Friday #112: How to Use Tweepy in Flask”