Using Session in a Flask app

Flask's Application object has an extensions mapping that can be used to store utilities such as connectors. In our case, we want to store a Session object. We can create a function that will initialize a placeholder in the app.extensions mapping and add a Session object in it:

    from requests import Session      def setup_connector(app, name='default', **options):         if not hasattr(app, 'extensions'):             app.extensions = {}          if 'connectors' not in app.extensions:             app.extensions['connectors'] = {}         session = Session()          if 'auth' in options:             session.auth = options['auth']         headers = options.get('headers', {})         if 'Content-Type' not in headers:             headers['Content-Type'] = 'application/json'  session.headers.update(headers) ...

Get Python Microservices Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.