r/FastAPI • u/[deleted] • Sep 17 '22
Question FastAPI equivalent to Express' app.locals/local variables
Hi there,
Apologies in advance if this is a silly question. I'm developing an application using FastAPI for the first time (coming mostly from a Node background). There's something that I just can't figure out, but I must be overlooking it as it's a pretty common use case.
In Node's Express framework, there is an object called `locals` which is a property of the main `app` variable. This is used to store variables in memory. For example, I may run a scheduled job to fetch and parse some data and save the data in memory within `app.locals.jobData`. All request handlers are able to access this object, so you can easily use the cached data in your handler logic. For example, I could do something like:
app.get('/show_job_data', (req, res) => {
return res.json({data: req.app.locals.jobData})
})Is there such a tool available for FastAPI, or does it require the use of an additional package? I'm having a difficult time finding an answer in the documentation. Thanks!
3
u/motute Sep 18 '22
Use the ‘state’ variable of the fastapi instance. You can use it to store arbitrary data. Each incoming request can access it using request.app.state.
1
u/pytheous1988 Sep 18 '22
If you don't need this on disk you could just store it in memory.
You likely have a config object, you could set it in memory by running the API call during startup and assigning it to some element on the object. Then reset it with the newe API call task every n hours.
2
u/quantum1eeps Sep 17 '22
I think you are looking for a “worker” that can setup a queue or bus such as redis or celery.