擅长:python、mysql、java
<p>如果您需要在flask应用程序启动后但严格地在第一个请求之前执行一些代码,甚至不会被执行第一个请求as@app触发。在第一个请求可以处理之前,您应该使用flask脚本,如CESCO所说,但是您可以将类服务器子类化并覆盖调用方法,而不是使用@manager.command覆盖runserver命令:</p>
<pre><code>from flask import Flask
from flask_script import Manager, Server
def custom_call():
#Your code
pass
class CustomServer(Server):
def __call__(self, app, *args, **kwargs):
custom_call()
#Hint: Here you could manipulate app
return Server.__call__(self, app, *args, **kwargs)
app = Flask(__name__)
manager = Manager(app)
# Remeber to add the command to your Manager instance
manager.add_command('runserver', CustomServer())
if __name__ == "__main__":
manager.run()
</code></pre>
<p>这样就不会覆盖runserver命令的默认选项。</p>