- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
Latest commit
160 lines (109 loc) · 4.54 KB
/
Copy pathserver.py
File metadata and controls
160 lines (109 loc) · 4.54 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# A light weight server in Django style powered by Python Standard Lib
# See views.py to learn how to write a view
fromhttp.serverimportBaseHTTPRequestHandler,HTTPServer
importurllib.parse, io, shutil
fromhttpimportHTTPStatus
fromviewsimport*
MIME_LIST={"css":"text/css","js":"application/x-javascript","jpg":"image/jpeg",
"jpeg":"image/jpeg","png":"image/png","gif":"image/gif","ico":"image/x-ico"}
classMyRequestHandler(BaseHTTPRequestHandler):
def__init__(self, request, client_address, server):
self.content=""
self.error_message_format=DEFAULT_ERROR_MESSAGE# You can define your error page here
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
defdo_GET(self):
self.do_response("GET")
defdo_POST(self):
self.do_response("POST")
defMIME_identify(self,path):
ctype="text/plain"
try:
fileType=path
while"."infileType:
_, _, fileType=fileType.partition(".")
ctype=MIME_LIST[fileType]
except:
pass
#print("Path:"+path+"\nType:"+ctype)
returnctype
# This function serve static files. You'd better serve
# HTML templates in views.py. You should define a MIME
# type in MIME_LIST before serve a new type of files
defserve_file(self, path):
ifos.path.isdir(path):
parts=urllib.parse.urlsplit(self.path)
ifnotparts.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(HTTPStatus.MOVED_PERMANENTLY)
new_parts= (parts[0], parts[1], parts[2] +'/',
parts[3], parts[4])
new_url=urllib.parse.urlunsplit(new_parts)
self.send_header("Location", new_url)
self.end_headers()
returnFalse
forindexin"index.html", "index.htm":
index=os.path.join(path, index)
ifos.path.exists(index):
path=index
break
else:
returnFalse
try:
f=open(os.path.dirname(__file__)+path, 'rb')
exceptOSError:
self.send_error(HTTPStatus.NOT_FOUND, "File not found")
returnFalse
ctype=self.MIME_identify(path)
try:
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", ctype)
fs=os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Cache-Control","no-store")
self.end_headers()
shutil.copyfileobj(f, self.wfile)
returnTrue
except:
f.close()
raise
defdo_response(self, method):
path_and_query=urllib.parse.splitquery(self.path) # Separate the query from the path
requestPath=path_and_query[0]
ifpath_and_query[1]: query=path_and_query[1]
else: query=""
dataDict= {}
ifmethod=="POST":
data=self.rfile.read(int(self.headers['content-length']))
data=urllib.parse.unquote(data.decode("utf-8", 'ignore'))
foriindata.split("&"):
key, _, value=i.partition("=")
dataDict[key] =value
responsefromView=command_selector(requestPath, "POST", dataDict)
else: #method=="GET"
if'?'inself.path:
ifquery:
foriinquery.split('&'):
k=i.split('=')
dataDict[k[0]] =urllib.parse.unquote(k[1])
else:
pass
responsefromView=command_selector(requestPath, "GET", dataDict)
ifnotresponsefromView :
self.serve_file(requestPath)
return
self.content=responsefromView.content
f=io.BytesIO()
f.write(self.content)
f.seek(0)
self.send_response(responsefromView.status)
foriinresponsefromView.head:
self.send_header(i, responsefromView.head[i])
self.end_headers()
shutil.copyfileobj(f, self.wfile)
classLPServer(HTTPServer):
def__init__(self,addr, port, bind_and_active=True):
HTTPServer.__init__(self,(addr,port),MyRequestHandler,bind_and_active)
deftest():
svr=LPServer("", 8080)
svr.serve_forever()