Skip to content

Instantly share code, notes, and snippets.

@rexlow
Last active January 14, 2019 08:08
Show Gist options
  • Save rexlow/3436a920b575a10b64f541dbcba1368c to your computer and use it in GitHub Desktop.
Save rexlow/3436a920b575a10b64f541dbcba1368c to your computer and use it in GitHub Desktop.
Tornado threaded async non-blocking server example
#!/usr/bin/python3
import time
import json
import urllib
from tornado.ioloop import IOLoop
from tornado.gen import coroutine
from tornado.httpserver import HTTPServer
from tornado.concurrent import run_on_executor
from tornado.web import Application, RequestHandler
from concurrent.futures.thread import ThreadPoolExecutor
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 8080
SERVER_MAX_WORKERS = 1000
class DotDict(dict):
def __getattr__(self, name):
return self[name]
class ServiceHandler(RequestHandler):
executor = ThreadPoolExecutor(max_workers=SERVER_MAX_WORKERS)
def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "*")
self.set_header("Access-Control-Expose-Headers", "*")
self.set_header("Access-Control-Allow-Credentials", "false")
self.set_header("Access-Control-Allow-Headers", "x-requested-with")
self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
def parseEncodedString(self, encodedString):
return urllib.parse.unquote(urllib.parse.unquote(encodedString))
def formatRequestBody(self, data) -> dict:
dataDict = { self.parseEncodedString(k):self.parseEncodedString(v) for k,v in (x.split('=') for x in data) }
dataDict = DotDict(dataDict)
return dataDict
@coroutine
def get(self):
print("Get Request")
result = yield self.asyncDemo()
self.write(json.dumps(result))
self.finish()
@run_on_executor
def handleGet(self):
reqBody = self.request.body.decode('utf8').split("&")
reqBody = self.formatRequestBody(reqBody)
response = {
"status_code": 200
}
return response
@run_on_executor
def asyncDemo(self):
reqBody = self.request.body.decode('utf8').split("&")
reqBody = self.formatRequestBody(reqBody)
print("Sleeping...")
time.sleep(5)
print("Done!")
return reqBody
if __name__ == "__main__":
print("Server running at {}:{}".format(SERVER_HOST, SERVER_PORT))
app = Application([
(r"/", ServiceHandler)
], debug=True)
server = HTTPServer(app)
server.listen(port=SERVER_PORT)
IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment