[英]Load and keep variables / objects accessible between files in python Flask server
When I start my flask app, I want it to immediately load an object, and I want this object to be available to functions defined in other files. 当我启动flask应用程序时,我希望它立即加载一个对象,并且希望该对象可用于其他文件中定义的功能。
The way things are set up now is as follows: 现在设置的方式如下:
object = someObjectToLoadAtServerStartAndAlwaysKeepInMemoryAndAccessFromAnyPyFile
In run.py, located in folder Project: 在run.py中,位于文件夹Project中:
from app import app
app.run(debug = True)
In __init__.py, located in Project/app: 在位于项目/应用程序中的__init__.py中:
from flask import Flask
app = Flask(__name__)
from app import views
In views.py, located in Project/app: 在位于Project / app中的views.py中:
from app import app
@app.route('/page')
def func():
#access preloaded variable here#
Note that I want the object (which is saved to a file) to be loaded immediately after the app is started, and maintained forever as long as the app is running. 请注意,我希望该对象(保存到文件中)在应用启动后立即加载,并在应用运行时一直保持下去。 I have tried any number of things, defining the object everywhere I can, and using global, but it is never accessible to func()
我已经尝试了很多方法,可以在任何地方定义对象,并使用global,但是func()永远无法访问它。
If I define it on top of views.py, will it load even no one has used one of the @app.routes? 如果我在views.py上定义它,即使没有人使用@ app.routes之一,它也会加载吗?
All right, after I change __init.py__
to __init__.py
, this will work: 好吧,在将
__init.py__
更改为__init__.py
,这将起作用:
File tree : 文件树 :
Project
├── app
│ ├── __init__.py
│ └── views.py
└── run.py
run.py : run.py :
from app import app
app.run(debug = True)
app/__init__.py : app / __ init__.py :
from flask import Flask
app = Flask(__name__)
from app import views
app/views.py : app / views.py :
from app import app
@app.route('/page')
def func():
return 'Hello'
Here is a demo: 这是一个演示:
If you have a look at how the LoginManager manager instance 'lm' is handled in part 6 of the Flask Mega-Tutorial, that gives you a great example to work from. 如果您查看Flask Mega-Tutorial的第6部分中如何处理LoginManager管理器实例“ lm”,那么将为您提供一个很好的示例。
Any object declared in the init .py for the app module is then accessed by a direct import in the relevant file (eg. 'from app import lm') 然后,通过直接导入相关文件(例如,“来自应用程序导入lm”),可以在应用程序模块的init .py中声明的任何对象被访问
See if this makes things clearer: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins 看看这是否使事情更清楚: http : //blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.