Run code after flask application has started

后端 未结 6 931
渐次进展
渐次进展 2020-12-09 14:54

My goal is to get arbitrary code to run after my Flask application is started. Here is what I\'ve got:

def run():
    from webapp import app
    app.run(debu         


        
6条回答
  •  感动是毒
    2020-12-09 15:19

    I don't really like any of the methods mentioned above, for the fact that you don't need Flask-Script to do this, and not all projects are going to use Flask-Script already.

    The easiest method, would be to build your own Flask sub-class. Where you construct your app with Flask(__name__), you would simply add your own class and use it instead.

    def do_something():
      print('MyFlaskApp is starting up!')
    
    
    class MyFlaskApp(Flask):
      def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):
        if not self.debug or os.getenv('WERKZEUG_RUN_MAIN') == 'true':
          with self.app_context():
            do_something()
        super(MyFlaskApp, self).run(host=host, port=port, debug=debug, load_dotenv=load_dotenv, **options)
    
    
    app = MyFlaskApp(__name__)
    app.run()
    

    Of course, this doesn't run after it starts, but right before run() is finally called. With app context, you should be able to do anything you may need to do with the database or anything else requiring app context. This should work with any server (uwsgi, gunicorn, etc.) as well.

    If you need the do_something() to be non-blocking, you can simply thread it with threading.Thread(target=do_something).start() instead.

    The conditional statement is to prevent the double call when using debug mode/reloader.

提交回复
热议问题