我应该选择使用哪个Flask扩展来使用API​​?

问题描述

我曾经尝试过使用Flask-Restless,但是我不确定,我认为它无法使用工厂模式和蓝图。

我想找到类似于Restless(简单生成/ JSON格式)但与工厂模式和蓝图兼容的东西,那么,您建议我在我的那些要求下支持FP&BP的扩展来构建API?

解决方法

您可以非常简单地使用蓝图构建REST API,而无需依赖任何Flask扩展。

这是一个不起作用的示例,但应该可以帮助您入门。设置一个基本的蓝图文件(假设它名为user.py):

import json
from flask import Blueprint,jsonify,request
   
bp = Blueprint('user',__name__,url_prefix='/user')

@bp.route('/',methods=['GET','POST'])
def user_details():
    if request.method=='GET':
         # Access elements in the JSON passed in to the call using request.json
         # Return a JSON result by passing a dictionary to jsonify
         return jsonify({'result': 'ok','var1': 'val1'})

    if request.method == 'POST':
         # Access elements in the JSON passed in to the call using request.json
         # Return a JSON result by passing a dictionary to jsonify
        return jsonify({'result': 'ok')

,然后将蓝图正常添加到Flask服务器中,例如您的__init__.py将具有以下内容:

from flask import Flask
import user
app = Flask(__name__)
app.register_blueprint(user.bp)