Search code examples
pythoncurlpycurl

curl example to pycurl


Here is my command

curl -i -H 'X-Storage-User:12345:12345' -H 'X-Storage-Pass:new1234' https://ssproxy.ucloudbiz.olleh.com/auth/v1.0

Result

HTTP/1.1 200 OK
Date: Fri, 08 Jan 2016 05:49:06 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 126
Connection: close
X-Auth-Token-Expires: 51114
X-Auth-Token: AUTH_tkdfefef8dfsfsefsf
X-Storage-Token: AUTH_tkdfefef8dfsfsefsf
X-Storage-Url: https://ssproxy.ucloudbiz.olleh.com/v1/AUTH_3xxsdff_sdfwef_sdfwf
X-Trans-Id: tx76sdsefwfwwt

How do I convert it to pycurl?

Thank you in advance.


Solution

  • Here is the corrisponding command in pycurl written in Python 3:

    import pycurl
    import sys
    
    def bodycb(buf):
        import sys
        sys.stdout.buffer.write(buf)
    
    def headercb(buf):
        import sys
        sys.stdout.buffer.write(buf)
    
    headers = ['X-Storage-User:12345:12345', 'X-Storage-Pass:new1234']
    
    pycurl_connect = pycurl.Curl()
    pycurl_connect.setopt(pycurl.URL, 'https://ssproxy.ucloudbiz.olleh.com/auth/v1.0')
    pycurl_connect.setopt(pycurl.HTTPHEADER, headers)
    pycurl_connect.setopt(pycurl.WRITEFUNCTION, bodycb)
    pycurl_connect.setopt(pycurl.HEADERFUNCTION, headercb)
    pycurl_connect.perform() 
    

    You need to pass in your headers in a list using pycurl.HTTPHEADER. The headercb and bodycb functions are just callbacks to print the responses headers and body to the console.