Created
February 22, 2015 15:48
-
-
Save etataurov/f1faf910be3534315e83 to your computer and use it in GitHub Desktop.
arequests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from arequests.api import * |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import aiohttp | |
class CustomResponse(aiohttp.client.ClientResponse): | |
@asyncio.coroutine | |
def _get_text(self, encoding=None): | |
""" | |
from original ClientResponse.text | |
Read response payload and decode. | |
""" | |
if self._content is None: | |
yield from self.read() | |
return self._content.decode(self._get_encoding(encoding)) | |
@property | |
def text(self): | |
return (yield from self._get_text()) | |
@asyncio.coroutine | |
def get(url, params=None): | |
return (yield from aiohttp.request('get', url, params=params, response_class=CustomResponse)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import arequests | |
import requests | |
# суть в том, чтобы отличие асинхронного и синхронного было только в наличии yield from! | |
@asyncio.coroutine | |
def test_async_get(): | |
r = yield from arequests.get('https://api.github.com/events') | |
print((yield from r.text)) | |
@asyncio.coroutine | |
def test_async_url(): | |
payload = {'key1': 'value1', 'key2': 'value2'} | |
r = yield from arequests.get("http://httpbin.org/get", params=payload) | |
print(r) | |
print(r.url) | |
@asyncio.coroutine | |
def test_async_json(): | |
r = yield from arequests.get('https://api.github.com/events') | |
print((yield from r.json())) | |
def test_get(): | |
r = requests.get('https://api.github.com/events') | |
print(r.text) | |
def test_url(): | |
payload = {'key1': 'value1', 'key2': 'value2'} | |
r = requests.get("http://httpbin.org/get", params=payload) | |
# FIXME: url is broken https://github.com/KeepSafe/aiohttp/commit/baf9e81178bffd1569f8951d10ea1625a1b0f608 | |
print(r.url) | |
def run_async(): | |
yield from test_async_get() | |
yield from test_async_url() | |
yield from test_async_json() | |
def run(): | |
test_get() | |
test_url() | |
if __name__ == '__main__': | |
asyncio.get_event_loop().run_until_complete(run_async()) | |
print('async done') | |
run() | |
print('done') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment