Python Friday #112: How to Use Tweepy in Flask

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):

 

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:

 

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:

 

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:

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:

If you go to /tweet in your application, Tweepy will post a tweet:

A Tweet send from Flask with Tweepy to Twitter

 

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”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.