Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f7e4614

Browse files
authored
Run coroutines thread-safely (#26)
1 parent 305c89d commit f7e4614

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

fdk/runner.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ def handle_callable(ctx, handle_func, data=None,
3232
if isinstance(r, types.CoroutineType):
3333
print("function appeared to be a coroutine, awaiting...",
3434
file=sys.stderr, flush=True)
35-
return loop.run_until_complete(r)
35+
while not loop.is_running():
36+
return loop.run_until_complete(r)
3637

3738
return r
3839

@@ -107,3 +108,4 @@ def data_received(self, data):
107108
def connection_lost(self, exc):
108109
print('pipe closed', file=sys.stderr, flush=True)
109110
super(JSONProtocol, self).connection_lost(exc)
111+
sys.exit(0)

fdk/tests/test_json.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,3 +84,15 @@ def test_corotuine_func(self):
8484
self.assertIsNotNone(r)
8585
self.assertEqual(200, r.status())
8686
self.assertIn("OK", r.body())
87+
88+
def test_corotuine_func_multiple(self):
89+
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
90+
loop = asyncio.get_event_loop()
91+
in_bytes = data.raw_request_without_body.encode('utf8')
92+
# simulates two requests handled by the coroutines
93+
r1 = runner.handle_request(coroutine_func, in_bytes, loop=loop)
94+
r2 = runner.handle_request(coroutine_func, in_bytes, loop=loop)
95+
for r in [r1, r2]:
96+
self.assertIsNotNone(r)
97+
self.assertEqual(200, r.status())
98+
self.assertIn("OK", r.body())

0 commit comments

Comments
 (0)