This repository provides an example of how to use Flask-Dance with a SQLAlchemy storage. This particular repository uses Twitter as an OAuth provider, and it wires together the following Flask extensions:
You can run this code locally, or deploy it to Heroku to test it out.
Visit https://developer.twitter.com/en/apps to register an
app on Twitter. You must set the application's authorization
callback URL to http://127.0.0.1:5000/login/twitter/authorized
.
Once you've registered your application on Twitter, Twitter will give you an app ID and app secret, which we'll use in step 4.
Run the following commands on your computer:
git clone https://github.com/singingwolfboy/flask-dance-twitter-sqla.git cd flask-dance-twitter-sqla python3 -m venv venv source venv/bin/activate pip install -r requirements.txt
These commands will clone this git repository onto your computer,
create a virtual environment for this project, activate it, and install
the dependencies listed in requirements.txt
.
Also note that if you have trouble installing psycopg2
, it's OK to
skip it. That dependency is only needed if you are using PostgreSQL
for your database, and if you're running locally, then you can use
SQLite instead, which is simpler. SQLite is also the default option,
so you don't need to reconfigure anything.
Since we're storing OAuth data in the SQLAlchemy storage, we need to create the database to hold that data. Fortunately, this project includes basic command line support, so doing so is pretty straightforward. Run this code:
flask createdb
If it worked, you should see the message "Database tables created".
Many applications use environment variables for configuration, and Flask-Dance is no exception. You'll need to set the following environment variables:
TWITTER_OAUTH_APP_ID
: set this to the app ID you got from Twitter.TWITTER_OAUTH_APP_SECRET
: set this to the app secret you got from Twitter.OAUTHLIB_INSECURE_TRANSPORT
: set this totrue
. This indicates that you're doing local testing, and it's OK to use HTTP instead of HTTPS for OAuth. You should only do this for local testing. Do not set this in production! [oauthlib docs]
How you set these variables depends on your operating system. For Mac/Linux, you
can use the export command. For Windows, you can use the SET command. If
you don't want to worry about this, you can create a .env
file with
your environment variables, and use foreman to run your app. This repository
has a .env.example
file that you can copy.
If you're setting environment variables manually, run your app using the
flask
command:
flask run
If you're using a .env
file for your environment variables, install foreman
and use that to run your app:
foreman start
Then, go to http://localhost:5000/ to visit your app and log in with Twitter!