view simpypi/wsgi.py @ 40:bb69b82ddd17

misspelling
author Jeff Hammel <jhammel@mozilla.com>
date Thu, 01 Mar 2012 10:16:12 -0800
parents ee29001674af
children c934505fa098
line wrap: on
line source

"""
request dispatcher:
data persisting across requests should go here
"""

import os
import pkginfo
import shutil
import tempfile
from webob import Request, Response, exc

here = os.path.dirname(os.path.abspath(__file__))

class SimPyPI(object):

    def __init__(self, directory, index=None):

        self.directory = directory
        assert os.path.exists(directory)

        # request handlers
        self.handlers = dict([(method, getattr(self, method))
                              for method in ('GET', 'POST')])
        # TODO: HEAD, OPTIONS, maybe more

        # cache index HTML
        self.index = index or os.path.join(here, 'templates', 'index.html')
        assert os.path.exists(self.index)
        self.index = file(self.index).read()

    def __call__(self, environ, start_response):

        # get a request object
        request = Request(environ)

        # match the request to a handler
        handler = self.handlers.get(request.method)
        if handler:
            res = handler(request)
        else:
            res = exc.HTTPNotFound()

        return res(environ, start_response)

    def GET(self, request):
        return Response(body=self.index, content_type='text/html')

    def POST(self, request):
        """handle posting a package"""

        # get the package
        try:
            package = request.POST['package']
        except KeyError:
            # sanity check: does the field exist?
            return exc.HTTPBadRequest()

        # sanity check: is it a file? (TODO)
        if not hasattr(package, 'file') or not hasattr(package, 'filename'):
            return exc.HTTPBadRequest()

        # successful response
        response = exc.HTTPSeeOther(add_slash=True)

        # make a temporary copy for pkginfo
        # (or PaInt?)
        tmpdir = tempfile.mkdtemp()
        try:
            path = os.path.join(tmpdir, filename)
            f = file(path, 'w')
            import pdb; pdb.set_trace()
            f.close()
        # put the package in the right place
        finally:
            # cleanup
            shutil.rmtree(tmpdir)

        # redirect to the main page
        return response