bottle_leveldb.py plugin
写了个bottle_leveldb.py
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
try:
rv = callback(*args, **kwargs)
except:
raise
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
db.Delete('hello')
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')
batch.Delete('hello')
db.Write(batch, sync = True)
0
See Also
- Bottle.py Session
- leveldb+bottle+gevent 是个不错的组合
- Golang leveldb 热备份方法
- bottle authentication 插件
- 再次比较go实现的两个嵌入式数据库boltdb与leveldb
Nearby
- 上一篇 › Go Web 框架
- 下一篇 › 站长请进,程序在新浪商店还支持不,想装个试试