我不知道该怎么做。

蓝图API:

# 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没有给出解决问题的示例

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

最佳答案

这有效:

蓝图:

# 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
}

关于flask - 如何初始化躁动不安的 flask 蓝图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40161060/

10-15 17:36