0
|
1 import os
|
|
2 from urlparse import urlparse
|
|
3 from webob import Response, exc
|
|
4
|
|
5 class Handler(object):
|
|
6 def __init__(self, app, request):
|
|
7 self.app = app
|
|
8 self.request = request
|
|
9 self.application_path = urlparse(request.application_url)[2]
|
|
10
|
|
11 def link(self, path=(), permanant=False):
|
|
12 if isinstance(path, basestring):
|
|
13 path = [ path ]
|
|
14 path = [ i.strip('/') for i in path ]
|
|
15 if permanant:
|
|
16 application_url = [ self.request.application_url ]
|
|
17 else:
|
|
18 application_url = [ self.application_path ]
|
|
19 path = application_url + path
|
|
20 return '/'.join(path)
|
|
21
|
|
22 def redirect(self, location):
|
|
23 raise exc.HTTPSeeOther(location=location)
|
|
24
|
|
25 class Get(Handler):
|
|
26
|
2
|
27 form = """<html><body><form name="upload_form" method="post" enctype="multipart/form-data">
|
|
28 <input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>"""
|
|
29
|
0
|
30 @classmethod
|
2
|
31 def match(cls, app, request):
|
0
|
32 return request.method == 'GET'
|
|
33
|
|
34 def __call__(self):
|
2
|
35 return Response(content_type='text/html', body=self.form)
|
0
|
36
|
|
37 class Post(Handler):
|
|
38
|
|
39 @classmethod
|
2
|
40 def match(cls, app, request):
|
0
|
41 return request.method == 'POST'
|
|
42
|
2
|
43 def write(self, fin, path):
|
|
44 assert os.sep not in fin.filename
|
|
45 assert '..' not in fin.filename
|
|
46 fout = file(path, 'w')
|
|
47 fout.write(fin.file.read())
|
|
48 fout.close()
|
|
49
|
0
|
50 def __call__(self):
|
|
51 fin = self.request.POST['file']
|
2
|
52 _path = os.path.join(self.app.directory, fin.filename)
|
|
53 self.write(self, fin, _path)
|
0
|
54 self.redirect(self.link('/'))
|
2
|
55
|
|
56 def path(directory, request):
|
|
57 if os.sep == '/':
|
|
58 return os.path.join(directory, request.path_info.strip('/'))
|
|
59 return os.path.join(directory, *request.path_info.strip('/').split('/'))
|
|
60
|
|
61 class SubpathGet(Get):
|
|
62
|
|
63 @classmethod
|
|
64 def match(cls, app, request):
|
6
|
65 if request.method != 'GET':
|
2
|
66 return False
|
6
|
67 if app.query_string and (app.query_string not in request.GET):
|
2
|
68 return False
|
|
69 _path = path(app.directory, request)
|
|
70 if os.path.exists(_path) and os.path.isdir(_path):
|
|
71 return True
|
0
|
72
|
2
|
73 class SubpathPost(Post):
|
|
74
|
|
75 @classmethod
|
|
76 def match(cls, app, request):
|
|
77 if request.method != 'POST':
|
|
78 return False
|
|
79 _path = path(app.directory, request)
|
|
80 if os.path.exists(_path) and os.path.isdir(_path):
|
|
81 return True
|
|
82
|
|
83 def __call__(self):
|
|
84 fin = self.request.POST['file']
|
|
85 _path = path(self.app.directory, request)
|
|
86 _path = os.path.join(path, fin.filename)
|
|
87 self.write(self, fin, _path)
|
|
88 self.redirect(self.link(request.path_info))
|
|
89
|