0

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.

3 Answers 3

1

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()
Sign up to request clarification or add additional context in comments.

6 Comments

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.
If you control both servers, why do you even need to use cURL?
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 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
I tried running your code on linux command line and it gives me this : NameError: name 'urllib2' is not defined
|
0

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

Comments

0

You can use Requests library

Sample Get Call

import requests

def consumeGETRequestSync():
 params = {'test1':'param1','test2':'param2'}
 url = 'http://httpbin.org/get'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 response = requests.get(url, headers = headers,data = params)
 print "code:"+ str(response.status_code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "content:"+ str(response.text)

consumeGETRequestSync()

You can check this blog post http://stackandqueue.com/?p=75

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.