Mercurial > hg > uploader
view uploader/handlers.py @ 7:a8c60480fce0
make query_string argument more universal
author | k0s <k0scist@gmail.com> |
---|---|
date | Sun, 27 Dec 2009 18:45:28 -0500 |
parents | d2990750e5d6 |
children | 619516d8c9ff |
line wrap: on
line source
import os from urlparse import urlparse from webob import Response, exc class Handler(object): def __init__(self, app, request): self.app = app self.request = request self.application_path = urlparse(request.application_url)[2] def link(self, path=(), permanant=False): if isinstance(path, basestring): path = [ path ] path = [ i.strip('/') for i in path ] if permanant: application_url = [ self.request.application_url ] else: application_url = [ self.application_path ] path = application_url + path return '/'.join(path) def redirect(self, location): raise exc.HTTPSeeOther(location=location) class Get(Handler): form = """<html><body><form name="upload_form" method="post" enctype="multipart/form-data"> <input type="file" name="file"/><input type="submit" value="upload"/></form></body></html>""" @classmethod def match(cls, app, request): if app.query_string and (app.query_string not in request.GET): return False return request.method == 'GET' def __call__(self): return Response(content_type='text/html', body=self.form) class Post(Handler): @classmethod def match(cls, app, request): return request.method == 'POST' def write(self, fin, path): assert os.sep not in fin.filename assert '..' not in fin.filename fout = file(path, 'w') fout.write(fin.file.read()) fout.close() def __call__(self): fin = self.request.POST['file'] _path = os.path.join(self.app.directory, fin.filename) self.write(self, fin, _path) self.redirect(self.link('/')) def path(directory, request): if os.sep == '/': return os.path.join(directory, request.path_info.strip('/')) return os.path.join(directory, *request.path_info.strip('/').split('/')) class SubpathGet(Get): @classmethod def match(cls, app, request): if not Get.match(cls, app, request): return False _path = path(app.directory, request) if os.path.exists(_path) and os.path.isdir(_path): return True class SubpathPost(Post): @classmethod def match(cls, app, request): if request.method != 'POST': return False _path = path(app.directory, request) if os.path.exists(_path) and os.path.isdir(_path): return True def __call__(self): fin = self.request.POST['file'] _path = path(self.app.directory, request) _path = os.path.join(path, fin.filename) self.write(self, fin, _path) self.redirect(self.link(request.path_info))