By admin at 2013-12-04 15:06:06 • 895次点击


import leveldb
import inspect

class LeveldbPlugin(object):
    name = 'leveldb'

    def __init__(self, dbfile='./db', keyword='db'):
         self.dbfile = dbfile
         self.keyword = keyword

    def setup(self, app):
        for other in app.plugins:
            if not isinstance(other, LeveldbPlugin): continue
            if other.keyword == self.keyword:
                raise PluginError("Found another db plugin with "
                "conflicting settings (non-unique keyword).")

    def apply(self, callback, context):
        # Override global configuration with route-specific values.
        conf = context['config'].get('leveldb') or {}
        dbfile = conf.get('dbfile', self.dbfile)
        keyword = conf.get('keyword', self.keyword)

        # Test if the original callback accepts a 'db' keyword.
        # Ignore it if it does not need a database handle.
        args = inspect.getargspec(context['callback'])[0]
        if keyword not in args:
            return callback

        def wrapper(*args, **kwargs):
            # Connect to the database
            db = leveldb.LevelDB(dbfile)
            # Add the connection handle as a keyword argument.
            kwargs[keyword] = db

                rv = callback(*args, **kwargs)
            return rv

        # Replace the route callback with the wrapped one.
        return wrapper

Plugin = LeveldbPlugin

但对于leveldb 这样简单的key-value 操作,还是直接用py-leveldb 较好,简单的测试,前者用0.002~0.003秒,后者用0.0002~0.0003秒。

import leveldb

db = leveldb.LevelDB('./db')

# single put
db.Put('hello', 'world')
print db.Get('hello')

# single delete
print db.Get('hello')

# multiple put/delete applied atomically, and committed to disk
batch = leveldb.WriteBatch()
batch.Put('hello', 'world')
batch.Put('hello again', 'world')

db.Write(batch, sync = True)

bottle, leveldb, py, plugin

登录 后发表评论