how to construct the curl command from python requests module?

后端 未结 2 340
面向向阳花
面向向阳花 2020-12-29 01:57

Python requests is a good module to ease my web REST API access programming, I usually do like below

import json
url =         


        
相关标签:
2条回答
  • 2020-12-29 02:15

    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 lib
    
    0 讨论(0)
  • 2020-12-29 02:18

    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.

    0 讨论(0)
提交回复
热议问题