-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathasyncwsgi.py
67 lines (52 loc) · 1.6 KB
/
asyncwsgi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- coding: utf-8 -*-
"""
Async WSGI support for tornado and asyncio
"""
import threading
from functools import wraps
from greenlet import greenlet, getcurrent
local = threading.local()
def coroutine(f):
@wraps(f)
def wrapper(*args, **kwargs):
if not hasattr(local, 'main'):
raise RuntimeError(
'Event loop needs to be started with asyncwsgi.run')
def done(data):
try:
assert(data.done())
gr.switch(data.result())
except Exception as e:
gr.throw(e)
gr = getcurrent()
gen = local.make_coroutine(f)(*args, **kwargs)
local.schedule(gen).add_done_callback(done)
return local.main.switch()
return wrapper
def wrap(f):
def wrapper(*args, **kwargs):
return greenlet(f).switch(*args, **kwargs)
return wrapper
def run(loop):
try:
import tornado.ioloop
import tornado.gen
except ImportError:
pass
else:
if isinstance(loop, tornado.ioloop.IOLoop):
local.make_coroutine = tornado.gen.coroutine
local.schedule = lambda x: x
local.main = greenlet(loop.start)
return local.main.switch()
try:
import asyncio
except ImportError:
pass
else:
if isinstance(loop, asyncio.AbstractEventLoop):
local.make_coroutine = asyncio.coroutine
local.schedule = loop.create_task
local.main = greenlet(loop.run_forever)
return local.main.switch()
raise ValueError('Invalid event loop provided')