0

我有一个烧瓶应用程序。

应用程序.py

app = Flask(__name__)

from views import *

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

视图.py

from app import app

@app.route('/')
def home():
    return "Homepage"

所以,这里app.py是导入所有表单views.py和视图需要app的,在app.py. 但它仍然没有引起循环导入。为什么?

我使用以下方法运行此应用程序:

python app.py
4

2 回答 2

4

This looks similar to the Larger Applications document which Flask allows you to do when creating apps.

From the docs:

Circular Imports

Every Python programmer hates them, and yet we just added some: circular imports (That’s when two modules depend on each other. In this case views.py depends on __init__.py). Be advised that this is a bad idea in general but here it is actually fine. The reason for this is that we are not actually using the views in __init__.py and just ensuring the module is imported and we are doing that at the bottom of the file.

于 2013-05-06T14:14:02.330 回答
0

If we try to follow what the program does, it is something like that:

app = Flask(__name__) # OK
from views import * # Goes into views.py

from app import app # Looks into app.py, finds it, import it

# Defines home
@app.route('/')
def home():
    return "Homepage"

# import home and app, overriding app in app.py
# But views.app is the same as app.app, so it is still
# the same object

# Run main
if __name__=="__main__":
    app.run()

I bet it computes something like that. Since app is defined before being imported, it's ok.

于 2013-05-06T14:14:45.847 回答