gpt4 book ai didi

python - 使用蓝图的 Flask 循环导入

转载 作者:行者123 更新时间:2023-12-04 12:34:56 24 4
gpt4 key购买 nike

我试图在“蓝图”目录中获取应用程序实例,但不断收到循环导入错误。
根目录的文件树app

├── __init__.py
├── app.db
├── config.py
├── main
│   ├── __init__.py
│   └── routes.py
├── models.py
├── projects
│   ├── __init__.py
│   ├── forms.py
│   └── routes.py
└── users
├── __init__.py
├── forms.py
└── routes.py
我想要 app将在 projects/routes.py 中导入和使用文件:
app/projects/routes.py
import os
from flask import render_template, url_for, flash, redirect, Blueprint, request

from run import app # <- this is the line that triggers the error

# some other code

portfolio = Blueprint('portfolio', __name__)
应用程序/初始化 .py
def create_app(config_class=Config):

app = Flask(__name__)

# some other code

from app.projects.routes import portfolio
app.register_blueprint(portfolio)

# some other code

return app

run.py比后面提到的根目录高一级。
运行.py
from app import create_app

app = create_app()

if __name__ == '__main__':
app.run()

from app.models import User
from app import db
错误的追溯
flask.cli.NoAppException: While importing "run", an ImportError was raised:  Traceback (most recent call last): File "/Users/berry/Environments/Progresso Nel Edilzia/progresso/lib/python3.8/site-packages/flask/cli.py", line 240, in locate_app __import__(module_name) File "/Users/berry/Environments/Progresso Nel Edilzia/run.py", line 3, in <module> app = create_app() File "/Users/berry/Environments/Progresso Nel Edilzia/app/__init__.py", line 39, in create_app from app.projects.routes import portfolio File "/Users/berry/Environments/Progresso Nel Edilzia/app/projects/routes.py", line 10, in <module> from run import app ImportError: cannot import name 'app' from partially initialized module 'run' (most likely due to a circular import) (/Users/berry/Environments/Progresso Nel Edilzia/run.py)

最佳答案

如果您需要应用程序对象,您可以 from flask import current_app如果您需要在请求上下文之外使用应用程序,您可以在功能中导入应用程序

def foo_func():
from run import app
# ... use app to do something

关于python - 使用蓝图的 Flask 循环导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62539408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com