changeset 0:827f7577f940

initial commit of file upload widget
author k0s <k0scist@gmail.com>
date Sat, 21 Nov 2009 15:29:03 -0500
parents
children a02c4fcd7001
files setup.py uploader.ini uploader/__init__.py uploader/dispatcher.py uploader/factory.py uploader/handlers.py
diffstat 6 files changed, 146 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/setup.py	Sat Nov 21 15:29:03 2009 -0500
@@ -0,0 +1,31 @@
+from setuptools import setup, find_packages
+import sys, os
+
+version = "0.0"
+
+setup(name='uploader',
+      version=version,
+      description="a file uploader app",
+      long_description="""
+""",
+      classifiers=[], # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
+      author='Ethan Jucovy',
+      author_email='',
+      url='',
+      license="",
+      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
+      include_package_data=True,
+      zip_safe=False,
+      install_requires=[
+          # -*- Extra requirements: -*-
+         'WebOb',	
+         'Paste',
+         'PasteScript',
+      ],
+      entry_points="""
+      # -*- Entry points: -*-
+      [paste.app_factory]
+      main = uploader.factory:factory
+      """,
+      )
+      
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/uploader.ini	Sat Nov 21 15:29:03 2009 -0500
@@ -0,0 +1,22 @@
+#!/usr/bin/env paster
+
+[DEFAULT]
+debug = true
+email_to = 
+smtp_server = localhost
+error_email_from = paste@localhost
+
+[server:main]
+use = egg:Paste#http
+host = 0.0.0.0
+port = 56567
+
+[composite:main]
+use = egg:Paste#urlmap
+/ = uploader
+
+set debug = false
+
+[app:uploader]
+paste.app_factory = uploader.factory:factory
+uploader.directory = %(here)s/example
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/uploader/__init__.py	Sat Nov 21 15:29:03 2009 -0500
@@ -0,0 +1,1 @@
+#
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/uploader/dispatcher.py	Sat Nov 21 15:29:03 2009 -0500
@@ -0,0 +1,30 @@
+"""
+request dispatcher
+"""
+
+import os
+from handlers import Get, Post
+from webob import Request, exc
+
+class Dispatcher(object):
+
+    ### class level variables
+    defaults = { 'directory': None}
+
+    def __init__(self, **kw):
+        for key in self.defaults:
+            setattr(self, key, kw.get(key, self.defaults[key]))
+        self.handlers = [ Get, Post ]
+        assert os.path.exists(self.directory)
+
+    ### methods dealing with HTTP
+    def __call__(self, environ, start_response):
+        request = Request(environ)
+        for h in self.handlers:
+            if h.match(request):
+                handler = h(self, request)
+                break
+        else:
+            handler = exc.HTTPNotFound
+        res = handler()
+        return res(environ, start_response)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/uploader/factory.py	Sat Nov 21 15:29:03 2009 -0500
@@ -0,0 +1,12 @@
+from dispatcher import Dispatcher
+from paste.httpexceptions import HTTPExceptionHandler
+
+def factory(global_conf, **app_conf):
+    """create a webob view and wrap it in middleware"""
+    keystr = 'uploader.'
+    args = dict([(key.split(keystr, 1)[-1], value)
+                 for key, value in app_conf.items()
+                 if key.startswith(keystr) ])
+    app = Dispatcher(**args)
+    return HTTPExceptionHandler(app)
+    
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/uploader/handlers.py	Sat Nov 21 15:29:03 2009 -0500
@@ -0,0 +1,50 @@
+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):
+
+    @classmethod
+    def match(cls, request):
+        return request.method == 'GET'
+
+    def __call__(self):
+        retval = """<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>"""
+        return Response(content_type='text/html', body=retval)
+
+class Post(Handler):
+
+    @classmethod
+    def match(cls, request):
+        return request.method == 'POST'
+
+    def __call__(self):
+        fin = self.request.POST['file']
+        assert os.sep not in fin.filename
+        assert '..' not in fin.filename
+        fout = file(os.path.join(self.app.directory, fin.filename), 'w')
+        fout.write(fin.file.read())
+        fout.close()
+        self.redirect(self.link('/'))
+