added closing context manager to http response

This commit is contained in:
Luciano Ramalho 2015-07-14 00:06:25 -03:00
parent 3dbd22af09
commit 333615d051
3 changed files with 13 additions and 27 deletions

View File

@ -1,6 +1,6 @@
"""Download flags of countries (with error handling). """Download flags of countries (with error handling).
asyncio version asyncio yield-from version
Sample run:: Sample run::
@ -18,6 +18,7 @@ Sample run::
# BEGIN FLAGS2_ASYNCIO_TOP # BEGIN FLAGS2_ASYNCIO_TOP
import asyncio import asyncio
import collections import collections
from contextlib import closing
import aiohttp import aiohttp
from aiohttp import web from aiohttp import web
@ -40,15 +41,16 @@ class FetchError(Exception): # <1>
def get_flag(base_url, cc): # <2> def get_flag(base_url, cc): # <2>
url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower()) url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
resp = yield from aiohttp.request('GET', url) resp = yield from aiohttp.request('GET', url)
if resp.status == 200: with closing(resp):
image = yield from resp.read() if resp.status == 200:
return image image = yield from resp.read()
elif resp.status == 404: return image
raise web.HTTPNotFound() elif resp.status == 404:
else: raise web.HTTPNotFound()
raise aiohttp.HttpProcessingError( else:
code=resp.status, message=resp.reason, raise aiohttp.HttpProcessingError(
headers=resp.headers) code=resp.status, message=resp.reason,
headers=resp.headers)
@asyncio.coroutine @asyncio.coroutine

View File

@ -2,10 +2,6 @@
asyncio version using thread pool to save files asyncio version using thread pool to save files
Sample run::
$
""" """
import asyncio import asyncio

View File

@ -1,18 +1,6 @@
"""Download flags of countries (with error handling). """Download flags of countries (with error handling).
asyncio version asyncio async/await 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
""" """
# BEGIN FLAGS2_ASYNCIO_TOP # BEGIN FLAGS2_ASYNCIO_TOP