注册蓝图时,'function'对象没有属性'name'

时间:2016-07-04 07:10:16

标签: python flask

这是我的项目布局:

baseflask/
   baseflask/
      __init__.py
      views.py
      resources/
          health.py/
   wsgi.py/

这是我的打印

from flask import Blueprint
from flask import Response
health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def health():
    jd = {'status': 'OK'}
    data = json.dumps(jd)
    resp = Response(data, status=200, mimetype='application/json')
    return resp

我如何在__init__.py注册:

import os
basedir = os.path.abspath(os.path.dirname(__file__))
from flask import Blueprint
from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
app.debug = True

CORS(app)

from baseflask.health import health
app.register_blueprint(health)

这是错误:

Traceback (most recent call last):
  File "/home/ubuntu/workspace/baseflask/wsgi.py", line 10, in <module>
    from baseflask import app
  File "/home/ubuntu/workspace/baseflask/baseflask/__init__.py", line 18, in <module>
    app.register_blueprint(health)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 62, in wrapper_func
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 880, in register_blueprint
    if blueprint.name in self.blueprints:
AttributeError: 'function' object has no attribute 'name'

2 个答案:

答案 0 :(得分:23)

屏蔽引用health实例的Blueprint全局名称,方法是重复使用视图函数的名称:

health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def health():

您不能同时拥有路径视图功能和蓝图使用相同的名称;您替换了引用蓝图的全局名称health,并尝试为相同的全局名称注册路由功能。

为蓝图使用其他名称:

health_blueprint = Blueprint('health', __name__)

并注册:

from baseflask.health import health_blueprint
app.register_blueprint(health_blueprint)

或为视图函数使用不同的名称(除非您在endpoint='health'装饰器中明确使用@health.route(...),否则端点名称也会更改。)

答案 1 :(得分:0)

health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def health():

您的蓝图名称与您的函数名称相同,请尝试重命名函数名称。

health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def check_health():