I try to build a middleware for my app.
I need a way to create some object in my middleware function and i want to have access to that object in a next endpoint method . Please see my code example .
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
myObject = MyClass(request)
response = await call_next(request)
return response
@app.get("/")
def read_root(arg:str):
data = myObject.build_data(arg)
return {"Hello": "World", "data": data}
Is it possible to do? How to do this correctly?
Also, if it is not possible to create new object and pass it to an endpoint code. Maybe i can create kinda "global variable" for object? But how will it work in terms of multithreading?
app = FastAPI()
myObject = MyClass()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
myObject.use_request(request)
response = await call_next(request)
return response
@app.get("/")
def read_root(arg:str):
data = myObject.build_data(arg)
return {"Hello": "World", "data": data}
Will this work fine or there will be some specifics of multithreading etc?
The answer posted by MatsLindh in a comment works fine. Also i have got the full answer here https://github.com/fastapi/fastapi/discussions/12250
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
myObject = MyClass(request)
response = await call_next(request)
return response
@app.get("/")
def read_root(arg:str):
data = myObject.build_data(arg)
return {"Hello": "World", "data": data}