开发者

How can I implement my PHP curl request to Python

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://serv开发者_开发百科er-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.


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()


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜