Skip to content

Instantly share code, notes, and snippets.

@zwass
Created September 15, 2011 03:06
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 zwass/1218425 to your computer and use it in GitHub Desktop.
Save zwass/1218425 to your computer and use it in GitHub Desktop.
Code from PennApps CherryPy Talk
import cherrypy
import sqlite3
import json
def wrap_html(function):
def new_function(*args, **kwargs):
return """\
<html><body>
""" + function(*args, **kwargs) + """
</body></html>
"""
return new_function
def get_db():
conn = sqlite3.connect("pytalk.sqlite")
#Turn on autocommit
conn.isolation_level = None
c = conn.cursor()
return c
class Location():
@cherrypy.expose
def index(self, format="text"):
db = get_db()
db.execute("select * from locations")
values = db.fetchall()
result = { 'count': len(values), 'values': values }
return json.dumps(result)
@cherrypy.expose
def zip(self, zip=None):
db = get_db()
db.execute("select * from locations where zip=?", (zip,))
values = db.fetchall()
result = { 'count': len(values), 'values': values }
return json.dumps(result)
@cherrypy.expose
@wrap_html
def pretty(self):
db = get_db()
db.execute("select * from locations")
values = db.fetchall()
html = "<table>"
for value in values:
html += "<tr>"
for val in value:
html += "<td>" + str(val) + "</td>"
html += "</tr>"
html += "</table>"
return html
class HelloWorld():
location = Location()
@cherrypy.expose
@wrap_html
def index(self):
return "Hello World!"
@cherrypy.expose
@wrap_html
def hello(self, thing="World"):
return "Hello " + thing + "!"
@cherrypy.expose
def testmethod(self):
return cherrypy.request.method
@cherrypy.expose
def identify(self, name=None):
if 'POST' == cherrypy.request.method:
return "You identified as " + name + "."
else:
return """
<form action='identify' method='post'>
<p>Identify yourself:</p>
<input type='text' name='name' value=''/>
<input type='submit' value='Submit'/>
</form>
"""
cherrypy.quickstart(HelloWorld())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment