简体   繁体   中英

Running a single .py file once before main app.py in Flask

Is it possible to run a .py file or segment of python just once

to make the necessary -heavily data involved- computations, save to a tmp file,

then have the primary app.py file use that tmp file as a datasource without having to redo computations every time someone makes a request in Flask?

You may try this one: before_first_request


I'll show you a simple example:

from flask import Flask                                                     

app = Flask(__name__)                                                       


@app.before_first_request                                                   
def do_heavy_work():                                                        
    print("work, work!")                                                    


@app.route('/')                                                             
def index():                                                                
    return 'Hello, world.'                                                  


@app.route('/next')                                                         
def next():                                                                 
    return 'yoo'                                                            


if __name__ == '__main__':                                                  
    app.run(debug=True)

And you should find that the do_heavy_work only called once.

Depending on the type of computations and volume of traffic you might want to use a background worker/job queue like Celery. The idea with the HTTP requests is you want to keep them as fast and light as possible for the request/response lifecycle. If you are doing heavy data computations for every request as part of this cycle, you're slowing down users and not making good use of the HTTP processes.

Check this article from Heroku on Celery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM