curl-and-python

Re: help to Converting Curl to PyCurl code

From: Michael Wood <esiotrot_at_gmail.com>
Date: Sun, 19 Dec 2010 21:34:21 +0200

Hi

On 19 December 2010 18:50, Mohan L <l.mohanphy_at_gmail.com> wrote:
>
> Dear All,
>
> I am new to Pycurl. I am unable to find good doc in the internet to start it
> myself. I need some one help to getting start Pycurl.

It's pretty similar to using it in C. Just check the documentation on
the pycurl web site and also use the curl documentation. In
particular
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html

Where you might do curl_easy_setopt(curl, CURLOPT_URL, "..."); in C,
you would instead do curl.setopt(pycurl.URL, "...") in Python.

> I have user name and password for my site. I need to login the site using
> username and password using Pycurl. Then I need to send the request to
> server and the server will send the xml file as response. I am doing this
> like this in Curl. I am sending the username and password in in one curl
> call, it return "JSESSIONID" id.  I am using the session id in the below
> command to fetch the xml data from server.
>
> curl -d "command=listCapacity&zoneId=1&podId=1" -X POST -b
> "JSESSIONID=webD~C"  https://manage.com:443/client/api -k > out.xml
>
> running the above command in command line gives the xml file as output. I
> want to convert this using Pycurl code so that it will be easy to parse the
> xml from Python.

Do as Daniel suggests to get the C code, and work from there. I have
pasted some Python code which should do the same as your curl command
as a place to start.

> I need some code clue to achieve the above. Any help will be really
> appreciated. I could be very nice some code and explanation of the code, so
> that I will try to learn myself further.

The code is so simple it should not need any explanation.

> Thanks For Your Time.

#!/usr/bin/env python

import pycurl

def main():
    curl = pycurl.Curl()
    if not curl:
        print "Could not create Curl handle"
        return

    curl.setopt(pycurl.URL, "https://manage.com/client/api")
    curl.setopt(pycurl.NOPROGRESS, True)
    curl.setopt(pycurl.POSTFIELDS, "command=listCapacity&zoneId=1&podId=1")
    curl.setopt(pycurl.USERAGENT, "...")
    curl.setopt(pycurl.COOKIE, "JSESSIONID=webD~C")
    curl.setopt(pycurl.SSL_VERIFYPEER, False)

    curl.perform()

if __name__ == "__main__":
    main()
==================================

But, the above is not ideal, because how do you generate the POSTFIELDS string?

It's better to do this:

    postfields = [("command", "listCapacity"), ("zoneId", "1"), ("podId", "1")]
    curl.setopt(pycurl.HTTPPOST, postfields)

Or something like that anyway...

-- 
Michael Wood <esiotrot_at_gmail.com>
_______________________________________________
http://cool.haxx.se/cgi-bin/mailman/listinfo/curl-and-python
Received on 2010-12-19