我的文件夹根 app.py 看起来像这样
import application
if __name__ == '__main__':
application.app.run()
我有一个名为 application 的文件夹,其中包含 __init__.py
和三个文件夹: Controller 、模型和 View 。
__init__.py
看起来像这样
__version__ = '0.1'
from application.controllers import QuotesView
from flask import Flask
app = Flask('application')
QuotesView.register(app)
我的controllers
文件夹有两个文件__init__.py
和QuotesView.py
,如下所示:
QuotesView.py
from flask.ext.classy import FlaskView, route
# we'll make a list to hold some quotes for our app
quotes = [
"A noble spirit embiggens the smallest man! ~ Jebediah Springfield",
"If there is a way to do it better... find it. ~ Thomas Edison",
"No one knows what he can do till he tries. ~ Publilius Syrus"
]
class QuotesView(FlaskView):
@route('/')
def index(self):
return "<br>".join(quotes)
def before_request(self, name):
print("something is happening to a widget")
def after_request(self, name, response):
print("something happened to a widget")
return response
并且 __init__.py
看起来像这样:
import os
import glob
__all__ = [os.path.basename(
f)[:-3] for f in glob.glob(os.path.dirname(__file__) + "/*.py")]
当我运行 python app.py
时,我收到属性丢失错误:
Traceback (most recent call last):
File "app.py", line 2, in <module>
import application
File "/home/ace/flask/application/__init__.py", line 5, in <module>
QuotesView.register(app)
AttributeError: 'module' object has no attribute 'register'
虽然我觉得是我的导入,但我似乎无法弄清楚错误在哪里。我对 python 还很陌生,所以这可能很简单。
最佳答案
问题是您没有导入 QuotesView
类。您将导入 QuotesView
模块。因此,为了使其正常工作,您可以执行以下两项操作之一:
1.从模块中导入类:
from application.controllers.QuotesView import QuotesView
2.从导入模块访问类
from application.controllers import QuotesView
QuotesView.QuotesView.register(app)
我认为方法 1 更简洁。
关于python - 使用 Flask Classy 设置 Flask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428282/