Skip to content

Instantly share code, notes, and snippets.

@arthurk
Created April 26, 2010 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthurk/379597 to your computer and use it in GitHub Desktop.
Save arthurk/379597 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# Example of using Tokyo Cabinet with the
# pytc (http://pypi.python.org/pypi/pytc/) Python language bindings.
# For an overview of pytc's methods, download the pytc source,
# open the pytc.c file and go to line 889
from tc import HDB, HDBOREADER, HDBOWRITER, HDBOCREAT, HDBONOLCK, Error
# open (or create) the 'test.hdb' database with write permissions
db = HDB('test.hdb', HDBOCREAT | HDBOWRITER)
# add a few records
db.put('v1', '111')
db.put('v2', '222')
db.put('v3', '222')
db.put('foo', '111')
print db.get('foo')
# adding another record with the same key overwrites the value
db.put('foo', '222')
print db.get('foo')
# if you don't like this behaviour, you can use the `putkeep` method
# which will throw a tc.Error exception
try:
db.putkeep('foo', '333')
except Error as e:
print e
# you can also add int and double values. However, pytc's get() method
# will always return a string. So these methods are useless :-)
db.addint('v1', 123)
print type(db.get('v1'))
# remove a record
db.out('foo')
try:
db.get('foo')
except KeyError as e:
print e
# open database as read-only + non-locking
db.close()
db = HDB('test.hdb', HDBOREADER | HDBONOLCK)
# iterate over all existing records
for key in db:
print "%s: %s" % (key, db.get(key))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment