Sunday, July 20, 2008

zodb + cherrypy python

Here's a small example of how to use cherrypy and zodb together. It just adds what ever you pass into the /put url as arguments into the db.


easy_install ZODB3
easy_install cherrypy


You can see the website here, once you run the script: http://localhost:8080/



import cherrypy
import cgi

from ZODB import FileStorage, DB
import transaction

class MyZODB(object):
def __init__(self, path):
self.storage = FileStorage.FileStorage(path)
self.db = DB(self.storage)
self.connection = self.db.open()
self.dbroot = self.connection.root()

def close(self):
self.connection.close()
self.db.close()
self.storage.close()



def ehtml(s):
return cgi.escape(s)

class HelloWorld(object):
def index(self):
# list everything passed, and allow adding more.
r = ""
for k,v in dbroot.items():
r += "k:%s: v:%s:<br>" % (ehtml(k), ehtml(v))

r += "<form action='put' method='post'>"
r += "<textarea name='stuff'></textarea>"
r += "<input type='submit' name='submit' value='submit'>"
r += "</form>"
return r


def put(self, **kwargs):
# store all the args passed into the zodb.
dbroot.update(kwargs)
transaction.commit()

put.exposed = True
index.exposed = True

if __name__ == "__main__":
db = MyZODB('./Data.fs')
dbroot = db.dbroot

cherrypy.quickstart(HelloWorld())
db.close()

No comments: