[英]Issues performing URL Rewrite using Python's Requests library
I'm trying to use Requests to proxy requests sent to a Flask endpoint to another URL.我正在尝试使用请求将发送到 Flask 端点的请求代理到另一个 URL。
I want to pass on any data that's posted, so I use json=get_json()
in requests.post
.我想传递任何发布的数据,所以我在
requests.post
使用json=get_json()
。 However, when the initial request is GET, it doesn't have any JSON, so I get a 400 error with "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)".但是,当初始请求是 GET 时,它没有任何 JSON,因此我收到 400 错误“无法解码 JSON 对象:期望值:第 1 行第 1 列(字符 0)”。
I tried json=request.data
instead, but I get "TypeError: Object of type 'bytes' is not JSON serializable".我尝试使用
json=request.data
,但我得到“TypeError: Object of type 'bytes' is not JSON serializable”。
How can I get the data without assuming it's JSON?如何在不假设它是 JSON 的情况下获取数据? How can I pass the data to Requests without assuming it's JSON?
如何在不假设它是 JSON 的情况下将数据传递给请求?
from flask import request
import requests
@app.route("/pas/<path:arg>", methods=("GET", "POST", "PUT", "DELETE"))
def proxy(arg):
url = f"http://{config.pasUrl}:{config.pasPort}/{arg}?{request.query_string.decode('utf-8')}"
out_request = requests.request(
method=request.method,
url=url,
headers=request.headers,
json=request.get_json(),
)
return out_request.text
Replace json=request.get_json()
with data=request.get_data()
.将
json=request.get_json()
替换为data=request.get_data()
。
The data
parameter of requests.request()
takes a dictionary, list of tuples, bytes, or file-like object , and Flask's request.get_data()
returns the raw bytes of the body of the request. requests.request()
的data
参数采用字典、元组列表、字节或类文件对象,而 Flask 的request.get_data()
返回请求正文的原始字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.