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?
Use serving-lifecycle hooks
@app.before_serving
– runs once per worker, right before the first request is accepted.
@app.after_serving
– runs once on a clean shutdown
Create the requests.Session
in the first hook, stash it on the application object and close it in the second.