forked from meizhitu/100programhomework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
100-46-network-14.py
136 lines (116 loc) · 4.98 KB
/
100-46-network-14.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
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
#coding=utf-8
import cgi
import time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os # os. path
CWD = os.path.abspath('.')
## print CWD
# PORT = 8080
UPLOAD_PAGE = 'upload.html' # must contain a valid link with address and port of the server
def make_index(relpath):
abspath = os.path.abspath(relpath) # ; print abspath
flist = os.listdir(abspath) # ; print flist
rellist = []
for fname in flist:
relname = os.path.join(relpath, fname)
rellist.append(relname)
# print rellist
inslist = []
for r in rellist:
inslist.append('<a href="%s">%s</a><br>' % (r, r))
# print inslist
page_tpl = "<html><head></head><body>%s</body></html>"
ret = page_tpl % ( '\n'.join(inslist), )
return ret
# -----------------------------------------------------------------------
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path == '/':
page = make_index('.')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(page)
return
if self.path.endswith(".html"):
## print curdir + sep + self.path
f = open(curdir + sep + self.path)
#note that this potentially makes every file on your computer readable by the internet
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
if self.path.endswith(".esp"): #our dynamic content
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write("hey, today is the" + str(time.localtime()[7]))
self.wfile.write(" day in the year " + str(time.localtime()[0]))
return
else: # default: just send the file
filepath = self.path[1:] # remove leading '/'
f = open(os.path.join(CWD, filepath), 'rb')
#note that this potentially makes every file on your computer readable by the internet
self.send_response(200)
self.send_header('Content-type', 'application/octet-stream')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError as e:
# debug
print e
self.send_error(404, 'File Not Found: %s' % self.path)
def do_POST(self):
# global rootnode ## something remained in the orig. code
try:
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
# using cgi.FieldStorage instead, see
# http://stackoverflow.com/questions/1417918/time-out-error-while-creating-cgi-fieldstorage-object
fs = cgi.FieldStorage(fp=self.rfile,
headers=self.headers, # headers_,
environ={'REQUEST_METHOD': 'POST'}
# all the rest will come from the 'headers' object,
# but as the FieldStorage object was designed for CGI, absense of 'POST' value in environ
# will prevent the object from using the 'fp' argument !
)
## print 'have fs'
else:
raise Exception("Unexpected POST request")
fs_up = fs['upfile']
filename = os.path.split(fs_up.filename)[1] # strip the path, if it presents
fullname = os.path.join(CWD, filename)
# check for copies :
if os.path.exists(fullname):
fullname_test = fullname + '.copy'
i = 0
while os.path.exists(fullname_test):
fullname_test = "%s.copy(%d)" % (fullname, i)
i += 1
fullname = fullname_test
if not os.path.exists(fullname):
with open(fullname, 'wb') as o:
# self.copyfile(fs['upfile'].file, o)
o.write(fs_up.file.read())
self.send_response(200)
self.end_headers()
self.wfile.write("<HTML><HEAD></HEAD><BODY>POST OK.<BR><BR>");
self.wfile.write("File uploaded under name: " + os.path.split(fullname)[1]);
self.wfile.write('<BR><A HREF=%s>back</A>' % ( UPLOAD_PAGE, ))
self.wfile.write("</BODY></HTML>");
except Exception as e:
print e
self.send_error(404, 'POST to "%s" failed: %s' % (self.path, str(e)))
if __name__ == '__main__':
try:
server = HTTPServer(('', 8080), MyHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()