如何根据烧瓶中的请求正文路由请求?我想我可以使用redirect
,但我不希望使用它,而应根据正文的内容立即路由请求。
这是我尝试但失败的内容:
# I am using Flask-restful extension
from flask import Flask, request
from flask_restful import Resource, Api
class RouteA:
def post(self):
return {'route': 'RouteA'}
class RouteB:
def post(self):
return {'route': 'RouteB'}
app = Flask(__name__)
api = Api(app) # This is just flask-restful app wrapper extension
# I am trying to use before_request
@app.before_request
def routing():
request_body = request.get_json(force=True)
type = request_body.get('type', None)
if type and type == 'RouteB':
# somehow direct to routeB
request.path = '/jobs/routeb'
# I can do this too but I prefer direct routing rather than redirecting
# return redirect(location='jobs/routeb', code=307)
# routing here
api.add_resource(RouteA, '/jobs')
api.add_resource(RouteB, '/jobs/routeb')
if __name__ == '__main__':
app.run(debug=True)
我将如何向该端点发出请求:
import requests
url = 'http://localhost:5000/jobs'
payload = {
'type': 'RouteB'
}
r = requests.post(url=url, json=payload)
response = r.json()
print(response)
# Expecting:
# {'route': 'RouteB'}