Source

Cubbard / cubbard.py

Full commit
from __future__ import with_statement

import pytyrant
import simplejson

from webob import Response, Request
from webob.exc import *
from selector import Selector
from UserDict import UserDict
from poodle import Pool

from pprint import pprint


class ViceTyrant(UserDict):
    def __init__(self, host, port, *args, **kw):
        self.data = pytyrant.PyTyrant.open(host, port)
        UserDict.__init__(self, *args, **kw)

class TyranicalIndexMiddleware(object):
    def __init__(self, host, port, app=None, prefix='/_tyrant'):
        self.app = app
        self.urls = [
            ('/_tyrant/{key:any}[/]', {'GET': self.get, 'PUT': self.put})
        ]
        self._s = Selector(self.urls)
        if self.app:
            self._s.status404 = self.app

        def factory():
            return ViceTyrant(host, port)
        self.pool = Pool(factory)

    def _sr(self, *args, **kw):
        self.args = args
        self.kw = kw
        
    def __call__(self, env, sr):
        with self.pool.get() as conn:
            env['tyranical.conn'] = conn
            result = self._s(env, self._sr)
        sr(*self.args, **self.kw)
        return result

    def get(self, env, sr):
        res = Response()
        req = Request(env)
        t = env['tyranical.conn']
        try:
            res.body = t[req.urlvars['key']]
        except KeyError:
            res = HTTPNotFound()
        return res(env, sr)

    def put(self, env, sr):
        req = Request(env)
        res = Response()
        t = env['tyranical.conn']
        t[req.urlvars['key']] = req.body
        res.body = simplejson.dumps({'message': 'success'})
        return res(env, sr)