Python Falcon反向代理POST请求被忽略,返回404问题求助
问题原因及解决方法
核心原因
Falcon 默认会自动解析 Content-Type: application/json 的请求体,若未正确处理解析逻辑,请求可能无法匹配到on_post方法,直接返回404。另外,当前路由配置的拆分方式,也可能导致带请求体的POST请求无法正确匹配资源类。
具体修复步骤
1. 禁用自动解析请求体
作为反向代理,无需Falcon解析请求体,直接透传即可。在API实例中关闭JSON和表单编码的自动解析:
proxy_api.req_options.auto_parse_json = False proxy_api.req_options.auto_parse_form_urlencoded = False
2. 合并路由配置
将两个路由合并为一个,利用Falcon的可选路由参数特性,避免重复注册资源,同时匹配所有路径:
proxy_api.add_route('/{text:.*}', ReverseProxyResource())
{text:.*}表示text为可选参数,可匹配任意字符(包括路径中的/),根路径和子路径请求都能统一处理。
3. 完善POST请求透传逻辑
透传原请求的Content-Type头部,确保目标服务能正确识别请求格式:
def on_post(self, req, resp, text=None): print("POST") destination = "[destination_url]/" + text if text else "[destination_url]" # 透传原请求的Content-Type头部 headers = { 'Content-Type': req.get_header('Content-Type', default='application/octet-stream') } result = requests.post( destination, data=req.bounded_stream.read(), headers=headers ) resp.body = result.text resp.status = result.status_code
完整修复代码
import falcon import requests class ReverseProxyResource: def on_get(self, req, resp, text=None): print("GET") destination = "[destination_url]/" + text if text else "[destination_url]" result = requests.get(destination) resp.body = result.text resp.status = result.status_code def on_post(self, req, resp, text=None): print("POST") destination = "[destination_url]/" + text if text else "[destination_url]" headers = { 'Content-Type': req.get_header('Content-Type', default='application/octet-stream') } result = requests.post( destination, data=req.bounded_stream.read(), headers=headers ) resp.body = result.text resp.status = result.status_code proxy_api = application = falcon.API() proxy_api.req_options.auto_parse_json = False proxy_api.req_options.auto_parse_form_urlencoded = False proxy_api.add_route('/{text:.*}', ReverseProxyResource())
内容的提问来源于stack exchange,提问作者DevBot
相关产品推荐
相关产品推荐

