開發過程當中常常須要測試接口,有些接口須要須要認證信息(token). 爲了不在每一個請求中重複加入token. 能夠簡單搭建一個代理服務統一攔截全部請求.python
Flask提供了完善的生命週期函數,咱們能夠在before_request中攔截請求,加上token後轉發出去,而後將Response返回.json
from flask import Flask, request, jsonify, Response import requests def create_app(): app = Flask(__name__) app.config['JSON_AS_ASCII'] = False return app app = create_app() @app.before_request def proxy(): headers = {h[0]: h[1] for h in request.headers} url = request.url headers['x-token'] = '***' # 一些本身的邏輯... return requests.request(request.method, url, data=request.json, headers=headers).content if __name__ == "__main__": app.run()