Skip to content

Commit cfebfff

Browse files
committed
started to update everything for Python 3.5 and new async/await
1 parent 839b742 commit cfebfff

File tree

7 files changed

+248
-187
lines changed

7 files changed

+248
-187
lines changed

aiochat/server.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,9 @@ def get_static_client_page(_):
3535
with open('client.html', 'rb') as fh:
3636
return web.Response(body=fh.read())
3737

38-
@asyncio.coroutine
39-
def post_chat_message(self, request):
38+
async def post_chat_message(self, request):
4039
"""POST request handler for submitting new chat message."""
41-
json_data = yield from request.json()
40+
json_data = await request.json()
4241
try:
4342
username = json_data['username']
4443
text = json_data['text']
@@ -57,19 +56,18 @@ def post_chat_message(self, request):
5756
# https://bugzilla.mozilla.org/show_bug.cgi?id=521301
5857
return web.Response(status=NO_CONTENT, content_type='text/html')
5958

60-
@asyncio.coroutine
61-
def get_chat_messages(self, request):
59+
async def get_chat_messages(self, request):
6260
"""GET SSE request handler, streaming the incoming chat messages."""
6361
# inspired by https://github.com/brutasse/asyncio-sse
6462
response = web.StreamResponse()
6563
response.headers.add('Content-Type', 'text/event-stream')
6664
response.headers.add('Cache-Control', 'no-cache')
6765
response.headers.add('Connection', 'keep-alive')
68-
response.start(request)
66+
await response.prepare(request)
6967
response.write(b'retry: 1000\n') # set retry interval to 1s
7068

7169
while True:
72-
json_data = yield from asyncio.shield(self._next_message)
70+
json_data = await self._next_message
7371
self._send_event(json_data, response)
7472

7573
@staticmethod
@@ -84,11 +82,10 @@ def _send_event(json_data, response):
8482
def run_server(host, port):
8583
loop = asyncio.get_event_loop()
8684

87-
@asyncio.coroutine
88-
def _start_app():
85+
async def _start_app():
8986
app = ChatApp(loop)
90-
return (yield from loop.create_server(app.make_handler(),
91-
host=host, port=port))
87+
return (await loop.create_server(app.make_handler(),
88+
host=host, port=port))
9289

9390
loop.run_until_complete(_start_app())
9491
try:
@@ -105,4 +102,3 @@ def _start_app():
105102
print('Chat is served at:\n{}:{}/chat'.format(potential_ip, port))
106103
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
107104
run_server('0.0.0.0', port)
108-

calculator/stream_server.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,13 @@
1919
RESULT = 'result: {}\n'
2020

2121

22-
@asyncio.coroutine
23-
def client_handler(reader, writer):
22+
async def client_handler(reader, writer):
2423
interpreter = expression_gen()
2524
response = next(interpreter)
2625
writer.write(PROMPT.format(response).encode())
2726

2827
while True:
29-
message = (yield from reader.readline()).decode().strip()
28+
message = (await reader.readline()).decode().strip()
3029
try:
3130
response = interpreter.send(message)
3231
except StopIteration as e:
Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@
1717
{
1818
"cell_type": "code",
1919
"execution_count": 1,
20-
"metadata": {
21-
"collapsed": false
22-
},
20+
"metadata": {},
2321
"outputs": [],
2422
"source": [
2523
"import asyncio\n",
@@ -36,9 +34,7 @@
3634
{
3735
"cell_type": "code",
3836
"execution_count": 2,
39-
"metadata": {
40-
"collapsed": false
41-
},
37+
"metadata": {},
4238
"outputs": [
4339
{
4440
"name": "stdout",
@@ -71,9 +67,7 @@
7167
{
7268
"cell_type": "code",
7369
"execution_count": 3,
74-
"metadata": {
75-
"collapsed": false
76-
},
70+
"metadata": {},
7771
"outputs": [
7872
{
7973
"name": "stdout",
@@ -102,9 +96,7 @@
10296
{
10397
"cell_type": "code",
10498
"execution_count": 4,
105-
"metadata": {
106-
"collapsed": false
107-
},
99+
"metadata": {},
108100
"outputs": [
109101
{
110102
"name": "stdout",
@@ -145,9 +137,7 @@
145137
{
146138
"cell_type": "code",
147139
"execution_count": 5,
148-
"metadata": {
149-
"collapsed": false
150-
},
140+
"metadata": {},
151141
"outputs": [
152142
{
153143
"name": "stdout",
@@ -179,7 +169,7 @@
179169
"language_info": {
180170
"codemirror_mode": {
181171
"name": "ipython",
182-
"version": 3
172+
"version": 3.0
183173
},
184174
"file_extension": ".py",
185175
"mimetype": "text/x-python",
@@ -191,4 +181,4 @@
191181
},
192182
"nbformat": 4,
193183
"nbformat_minor": 0
194-
}
184+
}

notebook/aioloop35.ipynb

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Simple I/O Loop Examples"
8+
]
9+
},
10+
{
11+
"cell_type": "markdown",
12+
"metadata": {},
13+
"source": [
14+
"Create an event loop (which automatically becomes the default event loop in the context)."
15+
]
16+
},
17+
{
18+
"cell_type": "code",
19+
"execution_count": 7,
20+
"metadata": {},
21+
"outputs": [],
22+
"source": [
23+
"import asyncio\n",
24+
"loop = asyncio.get_event_loop()"
25+
]
26+
},
27+
{
28+
"cell_type": "markdown",
29+
"metadata": {},
30+
"source": [
31+
"Run a simple callback as soon as possible:"
32+
]
33+
},
34+
{
35+
"cell_type": "code",
36+
"execution_count": 8,
37+
"metadata": {},
38+
"outputs": [
39+
{
40+
"name": "stdout",
41+
"output_type": "stream",
42+
"text": [
43+
"Hello World!\n"
44+
]
45+
}
46+
],
47+
"source": [
48+
"def hello_world():\n",
49+
" print('Hello World!')\n",
50+
" loop.stop()\n",
51+
"\n",
52+
"loop.call_soon(hello_world)\n",
53+
"loop.run_forever()"
54+
]
55+
},
56+
{
57+
"cell_type": "markdown",
58+
"metadata": {},
59+
"source": [
60+
"Async functions can be directly scheduled in the eventloop."
61+
]
62+
},
63+
{
64+
"cell_type": "code",
65+
"execution_count": 9,
66+
"metadata": {},
67+
"outputs": [
68+
{
69+
"name": "stdout",
70+
"output_type": "stream",
71+
"text": [
72+
"Hello World!\n"
73+
]
74+
}
75+
],
76+
"source": [
77+
"async def hello_world():\n",
78+
" await asyncio.sleep(1.0)\n",
79+
" print('Hello World!')\n",
80+
"\n",
81+
"loop.run_until_complete(hello_world())"
82+
]
83+
},
84+
{
85+
"cell_type": "markdown",
86+
"metadata": {},
87+
"source": [
88+
"Multiple "
89+
]
90+
},
91+
{
92+
"cell_type": "code",
93+
"execution_count": 10,
94+
"metadata": {},
95+
"outputs": [
96+
{
97+
"data": {
98+
"text/plain": [
99+
"<Task pending coro=<hello_world() running at <ipython-input-9-c98f2874b726>:1>>"
100+
]
101+
},
102+
"execution_count": 10,
103+
"output_type": "execute_result",
104+
"metadata": {}
105+
}
106+
],
107+
"source": [
108+
"asyncio.ensure_future(hello_world())"
109+
]
110+
},
111+
{
112+
"cell_type": "markdown",
113+
"metadata": {},
114+
"source": [
115+
"Futures implement the coroutine interface, so they can be awaited (`await` actually calls `__await__` before the iteration)."
116+
]
117+
},
118+
{
119+
"cell_type": "code",
120+
"execution_count": 13,
121+
"metadata": {},
122+
"outputs": [
123+
{
124+
"name": "stdout",
125+
"output_type": "stream",
126+
"text": [
127+
"True\n"
128+
]
129+
}
130+
],
131+
"source": [
132+
"future = asyncio.Future()\n",
133+
"print(hasattr(future, '__await__'))"
134+
]
135+
},
136+
{
137+
"cell_type": "markdown",
138+
"metadata": {},
139+
"source": [
140+
""
141+
]
142+
}
143+
],
144+
"metadata": {
145+
"kernelspec": {
146+
"display_name": "Python 3",
147+
"language": "python",
148+
"name": "python3"
149+
},
150+
"language_info": {
151+
"codemirror_mode": {
152+
"name": "ipython",
153+
"version": 3.0
154+
},
155+
"file_extension": ".py",
156+
"mimetype": "text/x-python",
157+
"name": "python",
158+
"nbconvert_exporter": "python",
159+
"pygments_lexer": "ipython3",
160+
"version": "3.4.3"
161+
}
162+
},
163+
"nbformat": 4,
164+
"nbformat_minor": 0
165+
}

0 commit comments

Comments
 (0)