views:

35

answers:

2

This PHP code below fetches html from server A to server B. I did this to circumvent the same-domain policy of browsers. (jQuery's JSONP can also be used to achieve this but I prefer this method)

<?php
 /* 
   This code goes inside the body tag of server-B.com.
   Server-A.com then returns a set of form tags to be echoed in the body tag of Server-B 
 */
 $ch = curl_init();
 $url = "http://server-A.com/form.php";
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_HEADER,FALSE);
 curl_exec($ch);     //   grab URL and pass it to the browser
 curl_close($ch);    //   close cURL resource, and free up system resources
?>

How can I achieve this in Python? Im sure there is Curl implementation in Python too but I dont quite know how to do it yet.

+1  A: 

There are cURL wrappers for Python, but the preferred way of doing this is using urllib2

Note that your code in PHP retrieves the whole page and prints it. The equivalent Python code is:

import urllib2

url = 'http://server-A.com/form.php'
res = urllib2.urlopen(url)
print res.read()
NullUserException
Yes, but I made the form.php to just output the form tags without the rest of usual content like header, foote... just the form.
r2b2
If you control both servers, why do you even need to use cURL?
NullUserException
I only have control on Server-A.com. Server-B.com is hosted somewhere else and built on Django. I can only request (and suggest) to the guy at the other end how he can fetch data from Server-A.com in proxy kind of way .
r2b2
@r2b2 You should ask him for an API. It'll be easier on you both. But if he won't cooperate, `urllib` will work just as well as cURL
NullUserException
I tried running your code on linux command line and it gives me this : NameError: name 'urllib2' is not defined
r2b2
@r2b2 You need to import the `urllib2` module (see my updated answer)
NullUserException
Ace! Thanks a lot !
r2b2
A: 

I'm pretty sure this is what you're looking for: http://pycurl.sourceforge.net/ Good luck!

Ruel