CloudBean項目中到PHP開發WEB管理端,用Python開發服務控制端,在項目中Python的服務控制端有時候需要主動連接PHP的WEB管理端下載或上傳配置參數或數據信息,這裡采用的原理是Python模擬Http客戶端,向PHP所在的Apache發起Get或Post請求。
這裡將實現的技術代碼進行公開。
一、Python以GET請求的方式,請求PHP頁面,並獲得返回值
1、Python代碼:
<span xmlns="http://www.w3.org/1999/xhtml" >[root@AY python]#cat httpclientget.py
#!/usr/bin/env python
#coding=utf8
import httplib
httpclient=None
print 'bb'
try:
httpclient=httplib.HTTPConnection('www.xxx.org',80)
httpclient.request('GET','/CloudBean/capture.php?name=liu&pass=wew')
res=httpclient.getresponse()
print res.status
print res.reason
print res.read()
except Exception,e:
print "heelowr"
</span>
2、php代碼:
<span xmlns="http://www.w3.org/1999/xhtml" >[root@AY python]#cat /CloudBean/capture.php
<?php
echo $_GET["name"];
echo $_GET["pass"];
echo "GET:";
?>
</span>
二、Python以Post請求的方式,請求PHP頁面,並獲得返回值
1、Python代碼:
<span xmlns="http://www.w3.org/1999/xhtml" >[root@AY python]#cat httpclientpost.py
#!/usr/bin/env python
#coding=utf8
import httplib,urllib
httpclient=None
try:
params = urllib.urlencode({'name': 'tom', 'pass': 22})
print 'aaa'
headers = {"X-CPU": "arm/x86" , "X-USER": "234299044218541","X-RESOLUTION": "240x320","X-SYSTEM":"2.3","X-LANG":"en-us","X-SIGN":"a1ae6bee406a6b8aa0862969ba49cc1d", "X-IMSI":"3110012345678912","X-COUNTRY":"in","X-TIME":"1335339139"}
httpclient=httplib.HTTPConnection('www.xxx.org',80)
httpclient.request('POST','/CloudBean/cappost.php',params,headers)
res=httpclient.getresponse()
print res.status
print res.reason
print res.read()
print res.getheaders()
except Exception,e:
print "error"
</span>
2、PHP代碼:
<span xmlns="http://www.w3.org/1999/xhtml" >[root@AY python]#cat /CloudBean/cappost.php
<?php
echo $_POST["name"];
echo $_POST["pass"];
echo "post";
?>
</span>
《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡