我有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):
但这是正确的做法吗?
答案 0 :(得分:0)
你可以像你一样传递它param或者可以设置模块级变量:
# controller.py
some_var = None
def mytest():
print(some_var)
# myapp.py
MyMods.some_var = db
...rest of your code...
只要在调用some_var
之前设置mytest()
。