r/FastAPI • • 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!

1 Upvotes

6 comments sorted by

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.

1

u/[deleted] Sep 18 '22

Thanks for taking the time to reply- that definitely makes sense. I was thinking about redis but it seems like overkill for what I'm trying to do.

My goal is to fetch a small amount of data from an external API once every n hours and use that data in the logic for one of my routes, rather than re-fetching the data each request.

I get the sense that FastAPI doesn't have a built in way to set and retrieve app variables from within request handlers, is that accurate? I'm not opposed to using redis, but I was hoping I'd be able to accomplish this in a single container.

1

u/[deleted] Sep 18 '22 edited Sep 18 '22

How about a cronjob script calling a python module? Store to disk using dbm module

1

u/extreme4all Oct 02 '22

Apscheduler library is what you are looking for, or manualky schedule the task every hour While True: await func() await asyncio.sleep(3600)

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.