Home > OS >  Convert response.request.body to dict
Convert response.request.body to dict

Time:10-17

Using the python requests library I can issue a POST:

response = requests.post("https://httpbin.org", data = {"x": 100, "y": 200})
<Response [405]>

The returned requests.Response object still holds a reference to the original request.

response.request
<PreparedRequest [POST]>

This enables me to access the parameters of the request later on, e.g.:

response.request.body
'x=100&y=200'

However, the data which was originally passed as a dict has already been processed into a string which the server understands. My goal is to back-convert the body into the original dict form. Is it possible to do that without parsing the string explicitely, e.g. some library function?

I see that this thread URL query parameters to dict python answers a considerable part of this question, but there is a small difference. In the cited question the urllib is used to split the url into a path and a query string and convert the result in a dict. However, this question is about parsing a body of a POST request. So the split does not apply here.

CodePudding user response:

You can use this to Convert Query string to dict

string_query = 'x=100&y=200'
dict_query  = {item.split('=')[0]:int(item.split('=')[1]) for item in string_query.split("&")}


print(dict_query)

You can use this Simple Function:

def query_to_dict (query : str) -> dict:

    return {item.split('=')[0]:int(item.split('=')[1]) for item in query.split("&")}


body_response = 'x=100&y=200'

dict_query = query_to_dict(body_response)

print(dict_query)

find more information on : python: how to convert a query string to json string?

CodePudding user response:

The cited thread URL query parameters to dict python ( Martijn Pieters's answer) indeed shows how-to convert the query string to a dict. However, one needs to pass the body instead of the splitted query, then it works:

dict(urllib.parse.parse_qsl(response.request.body))

So, now I can answer the question myself.

  • Related