Python:HTTP請求模組(httplib/urllib,GET/POST,php),Web伺服器模組
阿新 • • 發佈:2019-02-01
一、HTTP請求模組
1.1 模組及區別
模組:
httplib、 httplib2
urllib、urllib2
區別:
2是1的加強版,http比url更底層。
可以理解為urllib是httplib的抽象。
1.2 httplib傳送GET請求例項程式碼
#!/usr/bin/env python import httplib #connect conn = httplib.HTTPConnection("192.168.175.130") #request conn.request("GET", "/get.php?id=100") #response r = conn.getresponse() #output print r.status, r.reason print r.read() #close conn.close()
httplib實現CDN中的預快取:
相當於執行:curl -x 127.0.0.1:80 http://tcp.qihooyun.cn/tcp.txt -v
#!/usr/bin/env python import httplib import urllib #connect conn = httplib.HTTPConnection("127.0.0.1", 80, timeout=60) #request method = "GET" url = "/tcp.txt" body = {} headers = {"Host": "tcp.qihooyun.cn"} conn.request(method, url, urllib.urlencode(body), headers) #response r = conn.getresponse() #output print r.status, r.reason print r.read() print r.getheaders() #close conn.close()
1.3 urllib、urllib2傳送GET請求例項程式碼
#!/usr/bin/env python
#import urllib
import urllib2
#r = urllib.urlopen("http://192.168.175.130/get.php?id=100")
r = urllib2.urlopen("http://192.168.175.130/get.php?id=100")
print r.read()
1.4 urllib、urllib2傳送POST請求例項程式碼
#!/usr/bin/env python #import urllib import urllib2 import json post_data = {} post_data['status'] = 1 post_data['info'] = "success" post_data_json = json.dumps(post_data) #r = urllib.urlopen("http://192.168.175.131/post.php", post_data_json) r = urllib2.urlopen("http://192.168.175.131/post.php", post_data_json) print(r.read())
1.5 上述get.php、post.php的程式碼
get.php:
<?php
if (!empty($_GET))
{
extract($_GET);
}
if (!empty($_POST))
{
extract($_POST);
}
$id=$_GET["id"];
print "php get response: ".$id;
?>
post.php:
<?php
if (!empty($_GET))
{
extract($_GET);
}
if (!empty($_POST))
{
extract($_POST);
}
$content = file_get_contents("php://input");
print "content:" . $content;
?>
二、Web伺服器模組
2.1 模組及區別
SimpleHTTPServer:包含執行GET和HEAD請求的SimpleHTTPRequestHandler類。
BaseHTTPServer:提供基本的Web服務和處理器類,分別是HTTPServer和BaseHTTPRequestHandler。
CGIHTTPServer:包含處理POST請求和執行CGIHTTPRequestHandler類。2.2 例項程式碼
建立最簡單的Web伺服器:
python -m SimpleHTTPServer
python -m CGIHTTPServer 8080
預設埠8000
參考資料: