how to construct the curl command from python requests module?
This method existed in requests once upon a time but it is far from being remotely relevant to the module. You could create a function that takes a response and inspects its request
attribute.
The request
attribute is a PreparedRequest
object so it has headers
, and body
attributes. The body is what you pass to curl with -d
and the headers can be generated as you did above. Finally you'll want to pluck off the url
attribute from the request
object and send that. The hooks don't matter to you unless you're doing something with a custom authentication handler.
req = response.request
command = "curl -X {method} -H {headers} -d '{data}' '{uri}'"
method = req.method
uri = req.url
data = req.body
headers = ['"{0}: {1}"'.format(k, v) for k, v in req.headers.items()]
headers = " -H ".join(headers)
return command.format(method=method, headers=headers, data=data, uri=uri)
That should work. Your data will be properly formatted whether it is as multipart/form-data
or anything else.
You can also use curlify to do this.
$ pip install curlify
...
import curlify
print(curlify.to_curl(r.request)) # r is the response object from the requests library.