简体   繁体   中英

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.

I want to pass on any data that's posted, so I use json=get_json() in requests.post . 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)".

I tried json=request.data instead, but I get "TypeError: Object of type 'bytes' is not JSON serializable".

How can I get the data without assuming it's JSON? How can I pass the data to Requests without assuming it's 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() .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM