python - 使用 Flask Classy 设置 Flask

标签 python python-2.7 flask

我的文件夹根 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__.pyQuotesView.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/

相关文章:

python - 处理棉花糖模式的多个变体

python - 带有 Python 3.6 的 MYSQLdb

Python - Pymediainfo模块[错误126]找不到指定的模块

python - 如何获取以前版本的 Python Selenium Webdriver

适合初学者的 Python 追溯模块

python - 在 AWS Beanstalk 上部署 Flask App 出错?内部服务器错误

python - 使用 alembic 对 flask_sqlalchemy 中新添加的不可空列进行迁移时出现 "ALTER"语法错误

python - 如何在文件中从字符 "xxx"到字符 "yyy"读写

Python 堆栈内容在传递给函数时会被覆盖

python - 在 python 中使用正则表达式解析 IP