pythonflask

How can I share one requests.Session across all Flask routes and close it cleanly on shutdown?


I’m building a small Flask 3.0 / Python 3.12 micro-service that calls an external REST API on almost every request

Right now each route makes a new requests.Session which is slow and leaks sockets under load

from flask import Flask, jsonify
import requests

app = Flask(__name__)

@app.get("/info")
def info():
    with requests.Session() as s:                  
        r = s.get("https://api.example.com/info")
    return jsonify(r.json())

What I tried

session = requests.Session()  

I get a resource warning through the above.

How can I re-use one requests.Session for all incoming requests and close it exactly once when the application exits?


Solution

  • Use serving-lifecycle hooks

    Create the requests.Session in the first hook, stash it on the application object and close it in the second.