python flask-restful blueprint和factory pattern一起工作?

jef*_*rey 9 python rest blueprint flask flask-restful

我正在使用flask-restful进行一项宁静的服务,我想在我的项目中利用工厂模式和蓝图.在app/__init__.py我有一个create_app函数来创建一个烧瓶应用程序,并返回给外线来电,所以调用者可以启动应用程序.

def create_app():
    app = Flask(__name__)
    app.config.from_object('app.appconfig.DevelopmentConfig')
    from app.resource import resource
    app.register_blueprint(v1, url_prefix='/api')
    print app.url_map
    return app
Run Code Online (Sandbox Code Playgroud)

在该函数内部,我打算使用前缀url注册指向实现包的蓝图.

app/resource/__init__.py下面是代码

from flask import current_app, Blueprint, render_template
from flask.ext import restful
resource = Blueprint('resource', __name__, url_prefix='/api')

@resource.route('/')
def index():    
    api = restful.Api(current_app)
    from resource.HelloWorld import HelloWorld
    api.add_resource(HelloWorld, '/hello')
Run Code Online (Sandbox Code Playgroud)

我的目标是我可以在url访问HelloWorld休息服务/api/hello,但我知道上面的代码有些错误@resource.route('/') ....我得到了一些错误,如AssertionError: A setup function was called after the first request was handled. This usually indicates a bug in the app ...api.add_resource(HelloWorld, '/hello').你能不能给我一些关于正确方法的提示?谢谢!

Sea*_*ira 20

像所有正确实现的Flask扩展一样,Flask-Restful支持两种注册方法:

  1. 使用应用程序进行实例化(正如您尝试的那样Api(current_app))
  2. 稍后使用 api.init_app(app)

处理循环导入问题的规范方法是使用第二个模式并在create_app函数中导入实例化的扩展并使用以下init_app方法注册扩展:

# app/resource/__init__.py
from resource.hello_world import HelloWorld

api = restful.Api(prefix='/api/v1')  # Note, no app
api.add_resource(HelloWorld, '/hello')

# We could actually register our API on a blueprint
# and then import and register the blueprint as normal
# but that's an alternate we will leave for another day
# bp = Blueprint('resource', __name__, url_prefix='/api')
# api.init_app(bp)
Run Code Online (Sandbox Code Playgroud)

然后在你的create_app通话中你只需加载并注册api:

def create_app():
    # ... snip ...
    # We import our extension
    # and register it with our application
    # without any circular references
    # Our handlers can use `current_app`, as you already know
    from app.resource import api
    api.init_app(app)
Run Code Online (Sandbox Code Playgroud)

  • 我得到异常**属性错误:'nonetype'对象在一个资源中调用`abort(404)`时,在来自flask_restful包的`self.app.config.get("ERROR_404_HELP",True)`中没有属性'config'**.所以我根据您的上述评论切换到蓝图,这完全解决了问题,谢谢! (2认同)
  • 对于经验丰富的烧瓶/网络开发人员来说,这可能是显而易见的,但是我花了好几天才终于遇到这个问题.谢谢你有用的模式. (2认同)