Understanding the Magic

Flask-Dance might initially seem like magic (“it just works!”), but it’s just code. It’s complicated, but understandable. This page will teach you how Flask-Dance works.

Making the Blueprint

The first thing you do with Flask-Dance is make a blueprint. This is an instance of OAuth1ConsumerBlueprint or OAuth2ConsumerBlueprint, depending on if you’re using OAuth 1 or OAuth 2. (Most providers use OAuth 2.)

When you make your blueprint, you can either pass your client ID and client secret to the blueprint directly, or teach your blueprint where to find those values on its own using the from_config dictionary. Using this dictionary is usually a good idea, since it allows you to specify these values in your application configuration instead of in your code.

After you’ve made the blueprint, you need to register it on your Flask application, just like you would with any other blueprint.

Using the Requests Session

The Flask-Dance blueprints have a session attribute. When you access this attribute, the blueprint will create and return a requests.Session object, properly configured for OAuth authentication. You can use this object in exactly the same way as you would normally use the Requests library for making HTTP requests.

The pre-set configurations also allow you to import special objects that refer to these Requests session objects. For example, if you run this code:

.. code-block:: python
from flask_dance.contrib.github import github

You can then call github.get() just like you do with Requests. However, this github object is not actually a Requests session – it’s something called a LocalProxy. This allows you to access the session within the context of an incoming HTTP request, but it will not allow you access it outside that context.