我正在尝试从 Instant Flask Web Development 一书中逐步学习Flask,但我得到了下面的错误。 (这似乎是循环导入的问题。) 问题是:
有人可以解释循环导入的修复和细节吗?
目录结构:
├── manage.py
├── requirements.txt
└── sched
├── __init__.py
├── __init__.pyc
├── app.py
├── app.pyc
├── static
└── templates
manager.py:
from flask.ext.script import Manager
from sched import app
manager = Manager(app)
app.config['DEBUG'] = True
if __name__ == '__main__':
manager.run()
app.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
__init__.py
是安培。
命令行生成错误:
$ python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 8, in <module>
app.config['DEBUG'] = True
AttributeError: 'module' object has no attribute 'config'
答案 0 :(得分:2)
当你这样做时
from sched import app
您正在导入app
模块。 app
对象位于模块内。您要使用的导入是
from sched.app import app
答案 1 :(得分:1)
替代架构:
# app.py:
from flask import Flask
app = Flask(__name__)
app.debug = True
from flask.ext.script import Manager
manager = Manager(app)
# __init__.py:
from .sched import app, manager
import sched.views # for your views
import sched.commands # for additional commands
# manager.py:
from sched import manager
if __name__ == '__main__':
manager.run()
#views.py:
from .app import app
@app.route('/')
def hello_world():
return 'Hello World!'
答案 2 :(得分:1)
我建议您为自己的应用关注an app factory pattern。
manage.py
sched/
__init__.py
在__init__.py
中,您可以执行以下操作:
from flask import Flask
def create_app():
app = Flask(__name__)
app.config['DEBUG'] = True
return app
manage.py
中的
from app import create_app
from flask.ext.script import Manager
app = create_app()
manager = Manager(app)
if __name__ == '__main__':
manager.run()
这往往是大型应用程序结构的可扩展解决方案。