Forum Discussion

fillmore's avatar
fillmore
New Contributor
3 years ago

Swagger codegen for Flask (Python). Access to shared Python object from models and controllers

Hello, I have an existing (and fully functioning) REST API built with Flask that I am re-implementing using the OpenAPI 3.0 for the heck of it.

I am using the Swagger codegen to jumpstart the server part. First a general question: is there a document/tutorial/blogpost that explains how the different bits hang together?

Looking at the files in the swagger_server folder it sort of makes sense, but I could still use an overview of some kind (apologies if it's somewhere in plain sight, I couldn't find it).

 

Here is my specific question. In my existing server, I have a pretty heavy initialization part that generates some large "in-memory" data structures. As my current implementation is a monolithic file, that's not an issue. But as controllers and models will need to access this data structure (and re-initializing it each time is out of question), how do you recommend that I access this shared object from within controllers and model? Is there a way for me to set a reference in __main__.py that I can access from all the other classes? Or should I create some kind of singleton?  Or am I missing something?

 

Hopefully what I wrote made sense. 

 

Thank you

  • Hi,

     

    I realize this is an old question but as for a singleton one can create a module such as `config.py` and import and use it wherever you need it. The rest I am busy figuring out myself still.

     

    Regards,

    Hans

  • fillmore's avatar
    fillmore
    New Contributor

    So, here is my solution, in case it's useful to others. I added the heavy duty part to the __main__.py file and then made it accessible to models and controllers through the app context:

     

    heavy = ... real heavy, gets computed once a t startup
    
    def main():
        :
        with app.app.app_context():
            current_app.heavy = heavy

     

    Controller methods can access the heavy stuff with:

     

        with current_app.app_context():
            heavy = current_app.heavy

     

    If there is a better way to do it, please let me know. This cuts it for me. 

    PS: thank you Hans for your suggestion. Didn't work for me.