Skip to content

Commit 333615d

Browse files
committed
added closing context manager to http response
1 parent 3dbd22a commit 333615d

File tree

3 files changed

+13
-27
lines changed

3 files changed

+13
-27
lines changed

17-futures/countries/flags2_asyncio.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Download flags of countries (with error handling).
22
3-
asyncio version
3+
asyncio yield-from version
44
55
Sample run::
66
@@ -18,6 +18,7 @@
1818
# BEGIN FLAGS2_ASYNCIO_TOP
1919
import asyncio
2020
import collections
21+
from contextlib import closing
2122

2223
import aiohttp
2324
from aiohttp import web
@@ -40,15 +41,16 @@ def __init__(self, country_code):
4041
def get_flag(base_url, cc): # <2>
4142
url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
4243
resp = yield from aiohttp.request('GET', url)
43-
if resp.status == 200:
44-
image = yield from resp.read()
45-
return image
46-
elif resp.status == 404:
47-
raise web.HTTPNotFound()
48-
else:
49-
raise aiohttp.HttpProcessingError(
50-
code=resp.status, message=resp.reason,
51-
headers=resp.headers)
44+
with closing(resp):
45+
if resp.status == 200:
46+
image = yield from resp.read()
47+
return image
48+
elif resp.status == 404:
49+
raise web.HTTPNotFound()
50+
else:
51+
raise aiohttp.HttpProcessingError(
52+
code=resp.status, message=resp.reason,
53+
headers=resp.headers)
5254

5355

5456
@asyncio.coroutine

17-futures/countries/flags2_asyncio_executor.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,6 @@
22
33
asyncio version using thread pool to save files
44
5-
Sample run::
6-
7-
$
8-
95
"""
106

117
import asyncio

17-futures/countries/flags2_await.py

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,6 @@
11
"""Download flags of countries (with error handling).
22
3-
asyncio version
4-
5-
Sample run::
6-
7-
$ python3 flags2_asyncio.py -s ERROR -e -m 200
8-
ERROR site: http://localhost:8003/flags
9-
Searching for 676 flags: from AA to ZZ
10-
200 concurrent connections will be used.
11-
--------------------
12-
146 flags downloaded.
13-
363 not found.
14-
167 errors.
15-
Elapsed time: 2.59s
3+
asyncio async/await version
164
175
"""
186
# BEGIN FLAGS2_ASYNCIO_TOP

0 commit comments

Comments
 (0)