如何初始化不安分作为烧瓶蓝图

Posted

技术标签:

【中文标题】如何初始化不安分作为烧瓶蓝图【英文标题】:How to init restless as flask blueprint 【发布时间】:2017-03-02 20:16:54 【问题描述】:

我不知道该怎么做。

蓝图接口:

# coding: utf-8
from flask import Blueprint, render_template
from ..models import User
from flask_restless import APIManager

manager = APIManager()

manager.create_api(User, url_prefix='/api', methods=['GET', 'POST', 'DELETE', 'PUT', 'PATCH'])

bp = Blueprint('api', __name__)

__init__.py:

def register_db(app):
    from .models import db

    db.init_app(app)

def register_api(app):
    from .controllers.api import manager

    manager.init_app(app, flask_sqlalchemy_db=db)

注册蓝图的:

def register_routes(app):
    from . import controllers
    from flask.blueprints import Blueprint
for module in _import_submodules_from_package(controllers):
    bp = getattr(module, 'bp')
    if bp and isinstance(bp, Blueprint):
        app.register_blueprint(bp)

我在尝试启动时收到此错误:

RuntimeError:应用程序未在数据库实例上注册并且没有应用程序绑定到当前上下文

如果我排除 methods=['GET', 'POST', 'DELETE', 'PUT', 'PATCH'],应用程序已启动,但如果我尝试发送请求 http http://0.0.0.0:5000/api/user,显然,我得到答案:

HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Length: 291
Content-Type: text/html
Date: Thu, 20 Oct 2016 15:33:52 GMT
Server: Werkzeug/0.11.11 Python/3.5.2

Docs没有给出解决问题的例子

你能告诉我在哪里可以找到答案

【问题讨论】:

【参考方案1】:

这行得通:

蓝图:

# coding: utf-8
from flask import Blueprint, render_template
from flask_restless import APIManager
from ..models import db


bp = Blueprint('api', __name__)

manager = APIManager(flask_sqlalchemy_db=db)

init.py:

def register_api(app):
    """Register api."""
    from .controllers.api import manager
    from .models import User

    manager.init_app(app)
    manager.create_api(User, app=app)

请求:http http://0.0.0.0:5000/api/user

回复:

HTTP/1.0 200 OK
Content-Length: 72
Content-Type: application/json
Content-Type: application/json
Date: Thu, 20 Oct 2016 18:50:04 GMT
Link: <http://0.0.0.0:5000/api/user?page=0&results_per_page=10>; rel="last"
Link: <http://0.0.0.0:5000/api/user?page=0&results_per_page=10>; rel="last"
Server: Werkzeug/0.11.11 Python/3.5.2
Vary: Accept


  "num_results": 0,
  "objects": [],
  "page": 1,
  "total_pages": 0

【讨论】:

以上是关于如何初始化不安分作为烧瓶蓝图的主要内容,如果未能解决你的问题,请参考以下文章

烧瓶 - 不安分使用分页或得到完整的回应

如何在具有多个蓝图的烧瓶中处理登录?

如何将装饰器应用于烧瓶中的所有蓝图 url

使用烧瓶+蓝图发送邮件

烧瓶蓝图导入错误:没有模块命名

注册 Flask 蓝图的顺序