Skip to content

Commit

Permalink
added closing context manager to http response
Browse files Browse the repository at this point in the history
  • Loading branch information
ramalho committed Jul 14, 2015
1 parent 3dbd22a commit 333615d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 27 deletions.
22 changes: 12 additions & 10 deletions 17-futures/countries/flags2_asyncio.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Download flags of countries (with error handling).
asyncio version
asyncio yield-from version
Sample run::
Expand All @@ -18,6 +18,7 @@
# BEGIN FLAGS2_ASYNCIO_TOP
import asyncio
import collections
from contextlib import closing

import aiohttp
from aiohttp import web
Expand All @@ -40,15 +41,16 @@ def __init__(self, country_code):
def get_flag(base_url, cc): # <2>
url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
resp = yield from aiohttp.request('GET', url)
if resp.status == 200:
image = yield from resp.read()
return image
elif resp.status == 404:
raise web.HTTPNotFound()
else:
raise aiohttp.HttpProcessingError(
code=resp.status, message=resp.reason,
headers=resp.headers)
with closing(resp):
if resp.status == 200:
image = yield from resp.read()
return image
elif resp.status == 404:
raise web.HTTPNotFound()
else:
raise aiohttp.HttpProcessingError(
code=resp.status, message=resp.reason,
headers=resp.headers)


@asyncio.coroutine
Expand Down
4 changes: 0 additions & 4 deletions 17-futures/countries/flags2_asyncio_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@
asyncio version using thread pool to save files
Sample run::
$
"""

import asyncio
Expand Down
14 changes: 1 addition & 13 deletions 17-futures/countries/flags2_await.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
"""Download flags of countries (with error handling).
asyncio version
Sample run::
$ python3 flags2_asyncio.py -s ERROR -e -m 200
ERROR site: http://localhost:8003/flags
Searching for 676 flags: from AA to ZZ
200 concurrent connections will be used.
--------------------
146 flags downloaded.
363 not found.
167 errors.
Elapsed time: 2.59s
asyncio async/await version
"""
# BEGIN FLAGS2_ASYNCIO_TOP
Expand Down

0 comments on commit 333615d

Please sign in to comment.