[Flask] reading yaml only at start up

Gergely Polonkai gergely at polonkai.eu
Fri Jul 12 01:12:38 EDT 2019


Depends on how you initialise your app.

If you use a plain Flask object, you may want to override the Flask class
with something like a custom FlaskYamlReader and do the reading in
__init__(). One advantage of this is that you can store the dict in
self.yamldict so you can easily access it with current_app.yamldict.

If you use an application factory, you can read it in the factory function
and either set it as an attribute of the app object (with setattr) or add
it to the g object like

from flask import g

def factory():
    app = Flask(…)
    g.yamldict = yaml.safe_read(yourfile)
    return app

Then access the object using g.yamldict in your code.

However, keep in mind that in a production environment your app can be
recreated for each request. If this is the case, you might want to create a
proxy object instead, which you can automatically propagate during the
first request and use as a cache afterwards.

Happy coding!

Gergely

On Thu, 11 Jul 2019, 23:50 Geert Stappers, <stappers at stappers.nl> wrote:

>
> Hi,
>
> Flask documentation does cover database connection.
>
>
> Thing I'm looking for is how read (only at startup)
> a YAML file into a dictionary.
> And how to reference that dict in various routes.
>
> Where may I find source code that does that?
>
>
> Groeten
> Geert Stappers
> --
> Leven en laten leven
> _______________________________________________
> Flask mailing list
> Flask at python.org
> https://mail.python.org/mailman/listinfo/flask
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20190712/e4add5bd/attachment.html>


More information about the Flask mailing list