-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTTPServerDemo.py
73 lines (60 loc) · 2.23 KB
/
HTTPServerDemo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#encoding=utf-8
'''
Created on 2012-11-7
@author: Steven
http://www.lifeba.org
基于BaseHTTPServer的http server实现,包括get,post方法,get参数接收,post参数接收。
'''
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import io,shutil
import urllib,time
import getopt,string
class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.process(2)
def do_POST(self):
self.process(1)
def process(self,type):
content =""
if type==1:#post方法,接收post参数
datas = self.rfile.read(int(self.headers['content-length']))
datas = urllib.unquote(datas).decode("utf-8", 'ignore')#指定编码方式
datas = transDicts(datas)#将参数转换为字典
if datas.has_key('data'):
content = "data:"+datas['data']+"\r\n"
if '?' in self.path:
query = urllib.splitquery(self.path)
action = query[0]
if query[1]:#接收get参数
queryParams = {}
for qp in query[1].split('&'):
kv = qp.split('=')
queryParams[kv[0]] = urllib.unquote(kv[1]).decode("utf-8", 'ignore')
content+= kv[0]+':'+queryParams[kv[0]]+"\r\n"
#指定返回编码
enc="UTF-8"
content = content.encode(enc)
f = io.BytesIO()
f.write(content)
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html; charset=%s" % enc)
self.send_header("Content-Length", str(len(content)))
self.end_headers()
shutil.copyfileobj(f,self.wfile)
def transDicts(params):
dicts={}
if len(params)==0:
return
params = params.split('&')
for param in params:
dicts[param.split('=')[0]]=param.split('=')[1]
return dicts
if __name__=='__main__':
try:
server = HTTPServer(('', 8000), MyRequestHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
pass