Brian Jenkins
Brian Jenkins

Reputation: 368

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

Upvotes: 2

Views: 2349

Answers (1)

dln385
dln385

Reputation: 12100

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.

Upvotes: 2

Related Questions