Python - 如何在应用模块中引用主应用的变量
Python - how to refer main app's variable in app's modules
我有以下 Flask 应用程序的文件结构(/env 是虚拟环境):
/env
/env/bin/...
/env/include/...
/env/lib/...
/env/lib64/...
/env/myapp.py
/mymodules/__init__.py
/mymodules/users/__init__.py
/mymodules/users/controller.py
myapp.py 包含以下内容:
# -*- coding: utf-8 -*-
from flask import Flask
from flask import request, current_app
from flask.ext.sqlalchemy import SQLAlchemy
import mymodules.users.controller as MyMods
app = Flask(__name__)
db = SQLAlchemy(app)
# [...]
@app.route(u"/test", methods=['GET'])
def test():
return MyMods.mytest()
if __name__ == u"__main__":
app.run()
controller.py
的内容
# -*- coding: utf-8 -*-
def mytest():
return "ok"
问题:如何在 controller.py 中使用 app
和 db
?
我可以将它作为参数传递:
MyMods.mytest(app, db)
def mytest(app_ref, db_ref):
但这是正确的做法吗?
您可以像以前那样传递参数,也可以设置模块级变量:
# controller.py
some_var = None
def mytest():
print(some_var)
# myapp.py
MyMods.some_var = db
...rest of your code...
只要在调用 mytest()
之前设置 some_var
。
我有以下 Flask 应用程序的文件结构(/env 是虚拟环境):
/env
/env/bin/...
/env/include/...
/env/lib/...
/env/lib64/...
/env/myapp.py
/mymodules/__init__.py
/mymodules/users/__init__.py
/mymodules/users/controller.py
myapp.py 包含以下内容:
# -*- coding: utf-8 -*-
from flask import Flask
from flask import request, current_app
from flask.ext.sqlalchemy import SQLAlchemy
import mymodules.users.controller as MyMods
app = Flask(__name__)
db = SQLAlchemy(app)
# [...]
@app.route(u"/test", methods=['GET'])
def test():
return MyMods.mytest()
if __name__ == u"__main__":
app.run()
controller.py
的内容# -*- coding: utf-8 -*-
def mytest():
return "ok"
问题:如何在 controller.py 中使用 app
和 db
?
我可以将它作为参数传递:
MyMods.mytest(app, db)
def mytest(app_ref, db_ref):
但这是正确的做法吗?
您可以像以前那样传递参数,也可以设置模块级变量:
# controller.py
some_var = None
def mytest():
print(some_var)
# myapp.py
MyMods.some_var = db
...rest of your code...
只要在调用 mytest()
之前设置 some_var
。