Created
August 9, 2021 22:22
-
-
Save pcuzner/429135463a88c118ac43b971c84daceb to your computer and use it in GitHub Desktop.
cherrypy example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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