Skip to content

Instantly share code, notes, and snippets.

@ploxiln
Created January 20, 2020 02:08
Show Gist options
  • Save ploxiln/a9dec7a47eabcbfbc503df7abe954275 to your computer and use it in GitHub Desktop.
Save ploxiln/a9dec7a47eabcbfbc503df7abe954275 to your computer and use it in GitHub Desktop.
import asyncio
import threading
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
def asyncrazy(func, *args):
"""run a stand-alone async function synchronously with a thread"""
result = None
def wrapper():
nonlocal result
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(func(*args))
thr = threading.Thread(target=wrapper)
thr.start()
thr.join()
return result
async def aio_func(msg):
print("started async...")
await asyncio.sleep(2)
print("still going", flush=True)
await asyncio.sleep(2)
print("async done", flush=True)
return "async %s!" % msg
class MainHandler(RequestHandler):
def get(self):
msg = self.get_argument("msg")
resp = asyncrazy(aio_func, msg)
self.set_header("Content-Type", "text/plain")
self.write(resp.encode() + b"\n")
if __name__ == "__main__":
app = Application([('/', MainHandler)])
app.listen(8080)
print("listening on port 8080", flush=True)
IOLoop.current().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment