flask之flask-restful

时间:2024-06-13 19:06:02
0、需要的库
flask_restful from flask import Flask
from flask_cors import CORS
1、参数的获取
self.parser.add_argument('pageIndex', type=int, location=['args','form'], required=True) # get location的值列表中最后一个优先出现在结果集中
self.parser.add_argument('pageSize', type=int, location=['form'], required=True) # post
self.parser.add_argument('X-custom-cookie', location=['cookies'], required=True) # cookies
self.parser.add_argument('X-custom-token', location='headers', required=True) # 注意location不能使用['headers'],自定义header 2、允许跨域资源共享(CORS)
app_obj = Flask(__name__)
CORS(app_obj, allow_headers=['Content-Type', 'Access-Control-Allow-Headers', 'X-custom-token'])
3、返回的headers中添加header
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
@api.representation('application/json')
def output_json(data, code, headers=None):
"""Makes a Flask response with a JSON encoded body"""
resp = make_response(json.dumps(data), code)
resp.headers.extend({"Access-Control-Allow-Credentials":"true"})
return resp