我有一个Flask应用程序,这是我的 main.py
from king_slayer.database import init_db, manager
from king_slayer.views import fetch_production
if __name__ == '__main__':
init_db()
manager.run()
在执行manger.run()
之前,我想打电话
fetch_production()
所以我这样做了。
from king_slayer.database import init_db, manager
from king_slayer.views import fetch_production
if __name__ == '__main__':
init_db()
with manager.app.test_request_context():
fetch_production()
manager.run()
有效。
问题是当我杀死Flask
应用程序然后重新启动它时,它不会启动60-120秒。没有错误,没什么。浏览器不会加载任何东西。简单的问题加载页面'出现并在一段时间后工作正常,除非我再次重新启动Flask
应用程序。
如果我删除
with manager.app.test_request_context():
fetch_production()
延迟没有发生。
P.S
如果我不使用with manager.app.test_request_context():
Flask会抛出此错误。
Traceback (most recent call last):
File "main.py", line 8, in <module>
fetch_production()
File "/home/jarvis/Development/kingslayer/king_slayer/king_slayer/views.py", line 156, in fetch_production
results={"msg": "Database Updated", }
File "/home/jarvis/Development/kingslayer/local/lib/python2.7/site-packages/flask/json.py", line 235, in jsonify
and not request.is_xhr:
File "/home/jarvis/Development/kingslayer/local/lib/python2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/home/jarvis/Development/kingslayer/local/lib/python2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/home/jarvis/Development/kingslayer/local/lib/python2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
发生了什么事?
P.P.S fetch_production()
做了类似的事情
requests.get(config.SERVER, auth=HTTPBasicAuth(config.AUTH_USER, config.AUTH_PASSWORD))
进行一些函数调用,在views.py
中定义的函数,然后在文件系统中创建一个.ini
文件。然后最后返回return jsonify
。
requests.get(config.SERVER, auth=HTTPBasicAuth(config.AUTH_USER, config.AUTH_PASSWORD))
实际上非常快,如果手动调用fetch_production()
,它不会花费超过几毫秒。