Issues performing URL Rewrite using Python's Requests library

  • A+
Category:Languages

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: