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支持两种注册方法:
Api(current_app))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)
| 归档时间: |
|
| 查看次数: |
6145 次 |
| 最近记录: |