Skip to content

Commit ff64628

Browse files
author
meig
committed
enhance xhttp server
1 parent 7ba6e63 commit ff64628

File tree

4 files changed

+114
-19
lines changed

4 files changed

+114
-19
lines changed

pub/common/error.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ def pack_errinfo_json(error,detail=None):
4646
def match(code,error_tuple):
4747
return code == error_tuple[0]
4848

49+
def pack_ok_json():
50+
return '{"result":"ok"}'
51+
4952
if __name__ == "__main__":
5053
print pack_errinfo_json(ERROR_INTERNAL_SERVER_ERROR,"shit")
5154
raw_input()

pub/common/utils.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# -*- coding:utf-8 -*-
55
import sys
66
import os
7+
import os.path
78
import platform
89

910
def get_cur_info_within_exception():
@@ -100,9 +101,30 @@ def test_directory(test_dir):
100101
return False
101102
return True
102103

103-
104+
def rmdir_r(path,ignore_error=False):
105+
items = os.listdir(path)
106+
for item in items:
107+
try:
108+
fullpath = os.path.join(path,item)
109+
if os.path.isdir(fullpath):
110+
rmdir_r(fullpath,ignore_error)
111+
else:
112+
os.remove(fullpath)
113+
except Exception:
114+
if ignore_error:
115+
continue
116+
else:
117+
break
118+
os.rmdir(path)
104119

105120
if __name__ == '__main__':
106121
test()
107122
print get_local_addr()
108-
os.system("pause")
123+
os.system("pause")
124+
125+
try:
126+
rmdir_r(r"E:\git__\flashp2p\livems_refactor\live_master\pub\common\tp1")
127+
except Exception,e:
128+
print str(e)
129+
130+
raw_input("press")

pub/xhttp/xhttp_server.py

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,62 @@
11
#!/usr/bin/python
22
# -*- coding:utf-8 -*-
33

4+
import httplib
5+
import re
46
import tornado.httpserver
57
import tornado.ioloop
6-
from common import error
7-
import urls
8+
import xhttp_utils
9+
from pub.common import error
810

911
class XRequestHandler(object):
1012
''' Callback handler to dispatch and handle request'''
1113

12-
def __init__(self,url_map):
13-
self.__router = url_map
14+
def __init__(self,url_match_list):
15+
self.__router = url_match_list
1416

1517
def handle_request(self,request):
16-
if self.__router.has_key(request.path):
17-
handler = self.__router[request.path]
18+
#if self.__router.has_key(request.path):
19+
# handler = self.__router[request.path]
20+
#else:
21+
# handler = None
22+
request_handler = None
23+
for re_str,handler in self.__router:
24+
if re.match(re_str,request.path):
25+
request_handler = handler
26+
break
27+
if not request_handler:
28+
resp = xhttp_utils.render_to_response(None,404)
1829
else:
19-
handler = None
20-
if not handler:
21-
body = error.pack_errinfo_json(error.ERROR_HTTP_URL_NOT_SUPPORTED)
22-
else:
23-
body = handler(request)
24-
message = "HTTP/1.1 200 OK\r\nContent-Length:%d\r\n\r\n%s" % (len(body),body)
30+
try:
31+
resp = request_handler(request)
32+
except Exception,e:
33+
resp = xhttp_utils.render_to_response(None,500)
34+
message = resp.pack_http_response_buf()
2535
request.write(message)
2636
request.finish()
2737

28-
def start(port,url_map=None):
38+
def pack_response(code,headers={},body=""):
39+
status = httplib.responses.get(code)
40+
if not status:
41+
status = "Unknown"
42+
segs = []
43+
segs.append("HTTP/1.1 %u %s" % (code,status))
44+
for key,value in headers.iteritems():
45+
segs.append("%s:%s"%(key,value))
46+
body = str(body)
47+
segs.append("Content-Length:%d" % len(body))
48+
message = "%s\r\n\r\n%s" % ("\r\n".join(segs),body)
49+
return message
50+
51+
def start(ports,url_map=None,_no_keep_alive=True):
2952
request_handler = XRequestHandler(url_map)
30-
http_server = tornado.httpserver.HTTPServer(request_handler.handle_request,no_keep_alive=True)
31-
http_server.listen(int(port))
53+
if not isinstance(ports,tuple):
54+
ports = (ports,)
55+
for port in ports:
56+
http_server = tornado.httpserver.HTTPServer(request_handler.handle_request,no_keep_alive=_no_keep_alive)
57+
http_server.listen(int(port))
3258
tornado.ioloop.IOLoop.instance().start()
33-
print "thread to quit:Main Thread"
34-
return True
59+
return True
60+
61+
def stop():
62+
tornado.ioloop.IOLoop.instance().stop()

pub/xhttp/xhttp_utils.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/python
2+
# -*- coding:utf-8 -*-
3+
4+
import httplib
5+
6+
class ServerResponse(object):
7+
def __init__(self,code,headers,body):
8+
self.code = code
9+
self.headers = headers
10+
self.body = body
11+
12+
def pack_http_response_buf(self):
13+
status = httplib.responses.get(self.code)
14+
if not status:
15+
status = "Unknown"
16+
segs = []
17+
segs.append("HTTP/1.1 %u %s" % (self.code,status))
18+
for key,value in self.headers.iteritems():
19+
segs.append("%s:%s"%(key,value))
20+
if self.body == None:
21+
body = status
22+
else:
23+
body = str(self.body)
24+
segs.append("Content-Length:%d" % len(body))
25+
message = "%s\r\n\r\n%s" % ("\r\n".join(segs),body)
26+
return message
27+
28+
def render_to_response(body,code=200,headers={}):
29+
return ServerResponse(code,headers,body)
30+
31+
def pack_response(code):
32+
resp = render_to_response("",code)
33+
return resp.pack_http_response_buf()
34+
35+
def login_required(auth_func):
36+
def _deco(handler):
37+
def __deco(request):
38+
if auth_func(request):
39+
return handler(request)
40+
return render_to_response("",401,{"WWW-Authenticate":'Basic realm="insert realm"'})
41+
return __deco
42+
return _deco

0 commit comments

Comments
 (0)