我对flask
应用进行了结构设计,使得应用工厂将所有__init__.py
文件统一为一个app
对象,如下所示:
app.py
tasks.py
/project/
__init__.py
routes/
__init__.py
auth_bp.py
register_bp.py
models/
__init__.py
user.py
base.py
app.py
from project import create_app
app = create_app()
项目/ __ init __。py
from flask import Flask
def create_app():
from . import routes, models
app = Flask(__name__)
models.init_app(app)
routes.init_app(app)
return app
项目/模型/ __ init __,py
from base import db
def init_app(app):
db.init_app(app)
项目/路线/ __ init __。py
from auth import auth_bp
from register import register_bp
def init_app(app):
app.register_blueprint(auth_bp)
app.register_blueprint(register_bp)
我想包扎的是如何构造一些依赖于app.context()
的后台进程,例如:
project / tasks.py
import sys
sys.path.append('/path/to/root')
from app import app
def load_cache(track_and_features):
while True:
with app.app_context():
Upload_Track(track_and_features)
@app.route('/cache')
def cache(track_and_features):
executor.submit(load_cache, track_and_features)
return 'Ok'
在我调用cache()
的模块中,该问题(我想)是在该模块中依次导入app
对象的。
project / routes / auth_bp.py
from tasks import cache
@auth_bp.route("/callback/q")
def callback():
(...)
cache()
return redirect(url_for('register.homepage'))
我遇到了错误:
File "app.py", line 6, in <module>
app = create_app()
File "/Users/me/Documents/Code/Apps/Production/project/__init__.py", line 20, in create_app
from . import routes
File "/Users/me/Documents/Code/Apps/Production/project/routes/__init__.py", line 1, in <module>
from auth import auth_bp
File "/Users/me/Documents/Code/Apps/Production/project/routes/auth.py", line 18, in <module>
from tasks import cache
File "/Users/me/Documents/Code/Apps/Production/tasks.py", line 4, in <module>
from app import app
File "/Users/me/Documents/Code/Apps/Production/app.py", line 6, in <module>
app = create_app()
File "/Users/me/Documents/Code/Apps/Production/project/__init__.py", line 20, in create_app
from . import models, routes, services
ImportError: cannot import name routes
我该如何解决?
答案 0 :(得分:0)
请勿在{{1}}中导入app
。对于应用程序工厂,您在工厂外部没有routes
来注册路线。。取而代之的是,将蓝图用于所有视图,然后将蓝图导入工厂。您could still register your views with the app
object inside the factory,但这远不及使用蓝图向其注册视图那样干净。
您已经使用专用的app
功能执行此操作,但是您的init_app()
模块未遵循此模式。它也应该使用蓝图。如果可以简化应用程序,则可以在模块之间共享蓝图。
您真正创建一个project/routes/tasks.py
名称的唯一点就是运行整个应用程序,因此对于WSGI服务器,测试或命令行工具。