您现在的位置是:首页 >技术教程 >flask-restful 和 blueprint网站首页技术教程
flask-restful 和 blueprint
flask-restful 使用 flask-restful第三方库 from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class HelloWorldResource(Resource):
def get(self):
return {'hello':'world'}
def post(self):
return {'msg':‘post hello wolrd’}
api.add_resource(HelloworldResource,'/') 方式完成restful请求,flask_restful可以直接返回字典
flask-rest 采用
from flask import Buleprint
api=Blueprint('api',__name__)
@api.route('/posts/',methods=['get','post']) 方式注册路由@permission_required(Permission.WRITE)
def new_post():
post = Post.from_json(request.json)
post.author = g.current_user
db.session.add(post)
db.session.commit()
return jsonify(post.to_json()), 201, {'Location': url_for('api.get_post', id=post.id)}
原生flask 使用 jsonify返回json格式数据
蓝图注册到app实例上
from .api import api as api_blueprint
app.register_blueprint(api_blueprint, url_prefix='/api/v1')