0

During the app initialization (create_app()) I'd like to download some data (a list of objects) and store it somewhere within the app and be able to retrieve (just read) it in the views, something like this:

def get_users():
    return current_app.users

How should I approach this in flask? Thanks in advance

maslak
  • 1,115
  • 3
  • 8
  • 22
  • Does this answer your question? [What is the g object in this Flask code?](https://stackoverflow.com/questions/30514749/what-is-the-g-object-in-this-flask-code) – meshkati Feb 19 '21 at 09:54
  • @meshkati unfortunately not: `An app context lasts for one request / response cycle, g is not appropriate for storing data across requests` I'd like to be able to share data between requests, just for read, and get this data only once - during app initialization – maslak Feb 19 '21 at 09:56
  • Yeah I shared this question because of the last part of the answer that says: "Use a database, redis, the session, or another external data source for persisting data." – meshkati Feb 19 '21 at 10:02

1 Answers1

0

As @meshkati pointed out, there are different solutions to this.

What works for me is the following:

in my __init__.py file that contains the create_app() I also load the data that I need below the header, e.g.:

site_data = {}
site_data['categories'] = json.load(open(os.path.join('app', 'sitedata', 'science_categories.json')))

Then, whenever I need this data in the app, I include a from app import site_data in that file, e.g. the views file(s). This way, the data is loaded when I start the app and is accessible in the backend independent of any request.

But this means that the data is not updated while the app is running. So when you really need something like the current users stored in your database, you should query them regularly (+ maybe cache them if you do not want to query them too often)

straeter
  • 111
  • 7
  • ok but what if I want to download some data and save it to the db during app init? – maslak Feb 19 '21 at 12:12
  • you have the option to work on your database (i.d. insert or read out) after you created the database by `db.create_all()` and before you do the `app.run()`. Make sure this happens inside the app context, so for example you can do something like: `from app import site_data; if __name__ == "__main__": with app.app_context(): db.create_all(); site_data["test"] = User.query.first(); app.run();` – straeter Feb 19 '21 at 16:13