本文整理汇总了Python中aiohttp.ClientSession.request方法的典型用法代码示例。如果您正苦于以下问题:Python ClientSession.request方法的具体用法?Python ClientSession.request怎么用?Python ClientSession.request使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp.ClientSession
的用法示例。
在下文中一共展示了ClientSession.request方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: go
# 需要导入模块: from aiohttp import ClientSession [as 别名]
# 或者: from aiohttp.ClientSession import request [as 别名]
def go(dirname, filename):
ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_ctx.load_cert_chain(
os.path.join(dirname, 'sample.crt'),
os.path.join(dirname, 'sample.key')
)
app, _, url = yield from self.create_server(
'GET', '/static/' + filename, ssl_ctx=ssl_ctx
)
app.router.add_static('/static', dirname)
conn = TCPConnector(verify_ssl=False, loop=self.loop)
session = ClientSession(connector=conn)
resp = yield from session.request('GET', url)
self.assertEqual(200, resp.status)
txt = yield from resp.text()
self.assertEqual('file content', txt.rstrip())
ct = resp.headers['CONTENT-TYPE']
self.assertEqual('application/octet-stream', ct)
self.assertEqual(resp.headers.get('CONTENT-ENCODING'), None)
resp.close()
resp = yield from session.request('GET', url + 'fake')
self.assertEqual(404, resp.status)
resp.close()
resp = yield from session.request('GET', url + '/../../')
self.assertEqual(404, resp.status)
resp.close()
示例2: base_url
# 需要导入模块: from aiohttp import ClientSession [as 别名]
# 或者: from aiohttp.ClientSession import request [as 别名]
class FirebaseHTTP:
"""
HTTP Client for Firebase.
Args:
base_url (str): URL to your data.
auth (string): Auth key.
loop (class:`asyncio.BaseEventLoop`): Loop.
"""
def __init__(self, base_url, auth=None, loop=None):
"""Initialise the class."""
self._loop = loop or asyncio.get_event_loop()
self._base_url = base_url
self._auth = auth
self._session = ClientSession(loop=self._loop)
async def close(self):
"""Gracefully close the session."""
await self._session.close()
async def get(self, *, path=None, params=None):
"""Perform a GET request."""
return await self._request(method='GET', path=path, params=params)
async def put(self, *, value, path=None, params=None):
"""Perform a put request."""
return await self._request(method='PUT', value=value, path=path, params=params)
async def post(self, *, value, path=None, params=None):
"""Perform a POST request."""
return await self._request(method='POST', value=value, path=path, params=params)
async def patch(self, *, value, path=None, params=None):
"""Perform a PATCH request."""
return await self._request(method='PATCH', value=value, path=path, params=params)
async def delete(self, *, path=None, params=None):
"""Perform a DELETE request."""
return await self._request(method='DELETE', path=path, params=params)
async def stream(self, *, callback, path=None):
"""Hook up to the EventSource stream."""
url = posixpath.join(self._base_url, path) if path else self._base_url
headers = {'accept': 'text/event-stream'}
async with self._session.get(url, headers=headers) as resp:
while True:
await FirebaseHTTP._iterate_over_stream(resp.content.read(), callback)
@staticmethod
async def _iterate_over_stream(iterable, callback):
"""Iterate over the EventSource stream and pass the event and data to the callback as and when we receive it."""
async for msg in iterable:
msg_str = msg.decode('utf-8').strip()
if not msg_str:
continue
key, value = msg_str.split(':', 1)
if key == 'event' and value == 'cancel':
raise StreamCancelled('The requested location is no longer allowed due to security/rules changes.')
elif key == 'event' and value == 'auth_revoked':
raise StreamAuthRevoked('The auth credentials has expired.')
elif key == 'event':
event = value
elif key == 'data':
await callback(event=event, data=json.loads(value))
async def _request(self, *, method, value=None, path=None, params=None):
"""Perform a request to Firebase."""
url = posixpath.join(self._base_url, path.strip('/')) if path else self._base_url
url += '.json'
data = json.dumps(value) if value else None
params = params or {}
headers = {}
if self._auth:
params.update({'auth': self._auth})
headers.update({'typ': 'JWT', 'alg': 'HS256'})
async with self._session.request(method, url, data=data, params=params, headers=headers) as resp:
assert resp.status == 200
return await resp.json()
示例3: __init__
# 需要导入模块: from aiohttp import ClientSession [as 别名]
# 或者: from aiohttp.ClientSession import request [as 别名]
class TestClient:
"""
A test client implementation, for a aiohttp.web.Application.
:param app: the aiohttp.web application passed
to create_test_server
:type app: aiohttp.web.Application
:param protocol: the aiohttp.web application passed
to create_test_server
:type app: aiohttp.web.Application
"""
def __init__(self, app, protocol="http"):
self._app = app
self._loop = loop = app.loop
self.port = unused_port()
self._handler = handler = app.make_handler()
self._server = loop.run_until_complete(loop.create_server(
handler, '127.0.0.1', self.port
))
self._session = ClientSession(loop=self._loop)
self._root = "{}://127.0.0.1:{}".format(
protocol, self.port
)
self._closed = False
def request(self, method, url, *args, **kwargs):
return _RequestContextManager(self._request(
method, url, *args, **kwargs
))
@asyncio.coroutine
def _request(self, method, url, *args, **kwargs):
""" routes a request to the http server.
the interface is identical to asyncio.request,
except the loop kwarg is overriden
by the instance used by the application.
"""
return (yield from self._session.request(
method, self._root + url, *args, **kwargs
))
def close(self):
if not self._closed:
loop = self._loop
loop.run_until_complete(self._session.close())
loop.run_until_complete(self._handler.finish_connections())
loop.run_until_complete(self._app.finish())
self._server.close()
loop.run_until_complete(self._server.wait_closed())
self._closed = True
def __del__(self):
self.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()