Skip to content

Instantly share code, notes, and snippets.

@pcuzner
Created August 9, 2021 22:22
Show Gist options
  • Save pcuzner/429135463a88c118ac43b971c84daceb to your computer and use it in GitHub Desktop.
Save pcuzner/429135463a88c118ac43b971c84daceb to your computer and use it in GitHub Desktop.
cherrypy example
#!/usr/bin/env python3
import cherrypy
# Test:
# curl -H "Content-Type: application/json" http://localhost:8000/data --data '{"data":30}' -X POST
class Root:
def __init__(self):
# yields /data endpoint
self.data = HostData()
class HostData:
# expose the methods here to the parent endpoint
exposed = True
@cherrypy.tools.json_in()
def POST(self):
# Only POST is accepted, and the header must be in json format
data = cherrypy.request.json
print(data)
class WebServer:
def __init__(self):
self.conf = {
'/': {
'request.show_tracebacks': False,
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.response_headers.on': True,
}
}
def start(self):
cherrypy.server.socket_port = 8000
cherrypy.server.socket_host = '0.0.0.0'
cherrypy.tree.mount(Root(), '/', self.conf)
cherrypy.engine.start()
cherrypy.engine.block()
if __name__ == "__main__":
w = WebServer()
w.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment