flask_restful 结合 blueprint使用

在flask bulueprint 中使用flask_restful费了好大劲,参考https://stackoverflow.com/questions/39792872/getting-flask-restful-routes-from-within-a-blueprint,整理如下,以备参考。

程序:
- /run.py
# /run.py
from myapp import create_app
app= create_app()
app.run(host='0.0.0.0')
-/myapp/init.py
# /myapp/__init__.py
from flask import Flask
from werkzeug.utils import import_string

blueprints = ['myapp.api:api_bp']

def create_app():
    app = Flask(__name__)
    for bp_name in blueprints:
        bp = import_string(bp_name)
        app.register_blueprint(bp)
    return app
-/myapp/api/init.py
# /myapp/api/__init__py
from flask import Blueprint
from flask_restful import Resource, Api

api_bp = Blueprint('api', __name__,
                url_prefix='/api')
api = Api(api_bp)
from . import views
-/myapp/api/views.py
# /myapp/api/views.py
from flask_restful import Resource
from myapp.api import api

@api.resource('/')
class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}
运行:

python run.py
浏览器: localhost:5000/api/hello
输出:
{
“hello”: “world”
}

你可能感兴趣的:(flask,restful,blueprint,python)