Flask Blueprint AttributeError function 错误检查

Python 2016-07-16 01:34 暂无评论

Flask 算是新手上路,之前写过小玩意儿,但是基本没有用到 Bluprint 这个 API 基本不是很了解。

报错内容:

Traceback (most recent call last):
  File "/Users/home/PycharmProjects/Demo/Run.py", line 9, in <module>
    app = Create_apps()
  File "/Users/home/PycharmProjects/Demo/apps/__init__.py", line 14, in Create_apps
    register_blueprints(app)
  File "/Users/home/PycharmProjects/Demo/apps/__init__.py", line 19, in register_blueprints
    app.register_blueprint(Admin)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 65, in wrapper_func
    return f(self, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/flask/app.py", line 958, in register_blueprint
    if blueprint.name in self.blueprints:
AttributeError: 'function' object has no attribute 'name'

从报错种可以看到是 register_blueprints(app) 注册 Bluprint 的时候报错,然后走到下一步就是注册 Admin 这个视图的时候报错了。看到 apps\Admin\Views.py 代码中首先注册了这个视图路由命名为 Admin,写下一个测试 def Admin(): 的时候因为视图路由本身即是用 Admin 命名,因为定义了一个函数 Admin 产生冲突然后报错。

做一个小测试就知道了!

>>> from flask import Flask
>>> app = Flask(__name__)
>>> @app.route('/')
... def app():
...     return 'test page!'
...
>>> app.run()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'run'

这样报错的原因就是定义的路由 app 再自定义一个函数 app 导致冲突报错。

下面是正确的代码。

>>> from flask import Flask
>>> app = Flask(__name__)
>>> @app.route('/')
... def apps():
...     return 'test page!'
...
>>> app.run()
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [16/Jul/2016 01:32:14] "GET / HTTP/1.1" 200 -

代码结构:
run.py

#!/usr/bin/env python
#coding: utf-8

from apps import Create_apps
app = Create_apps()

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

apps\__init__.py

#!/usr/bin/env python
#coding: utf-8

from flask import Flask
from Admin.Views import Admin

def Create_apps():
    app = Flask(__name__)
    register_blueprints(app)
    return app

def register_blueprints(app):
    app.register_blueprint(Admin)

apps\Admin\Views.py

#!/usr/bin/env python
#coding: utf-8

from flask import Blueprint, render_template, redirect, url_for

Admin = Blueprint('Admin', __name__, url_prefix='/Admin/', template_folder='templates/Admin', static_folder='static/Admin')

@Admin.route('/')
def Admin():
    return 'The is Admin pages'
暂无评论