Skip to content

Instantly share code, notes, and snippets.

@abargnesi
Created October 1, 2012 13:08
Show Gist options
  • Select an option

  • Save abargnesi/3811705 to your computer and use it in GitHub Desktop.

Select an option

Save abargnesi/3811705 to your computer and use it in GitHub Desktop.
Custom response bodies for HTTP errors
#!/usr/bin/env python
import cherrypy
import simplejson
def not_found():
resp = cherrypy.response
resp.headers['Content-Type'] = 'application/json'
resp.status = 404
body = {'success': False, 'code': 404}
resp.body = simplejson.dumps(body)
return resp.body
class Resource(object):
exposed = True
def GET(self, item=None):
if item:
return not_found()
resp = cherrypy.response
resp.headers['Content-Type'] = 'text/html'
resp.status = 200
return "<html><body>looks good</body></html>"
class Root(object):
pass
root = Root()
root.test = Resource()
conf = {
'global': {
'server.socket_host': '0.0.0.0',
'server.socket_port': 8000,
},
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
}
}
cherrypy.quickstart(root, '/', conf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment