1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
|
.. _aiohttp-client-reference:
HTTP Client Reference
=====================
.. highlight:: python
.. module:: aiohttp.client
Client Session
--------------
Client session is the recommended interface for making HTTP requests.
Session encapsulates *connection pool* (*connector* instance) and
supports keepalives by default.
Usage example::
>>> import aiohttp
>>> session = aiohttp.ClientSession()
>>> resp = yield from session.get('http://python.org')
>>> resp
<ClientResponse(python.org/) [200]>
>>> data = yield from resp.read()
>>> session.close()
.. versionadded:: 0.15.2
The client session supports context manager protocol for self closing::
>>> with aiohttp.ClientSession() as session:
>>> resp = yield from session.get('http://python.org')
>>> yield from resp.release()
>>> session.closed
True
.. versionadded:: 0.17
.. class:: ClientSession(*, connector=None, loop=None, cookies=None,\
headers=None, auth=None, request_class=ClientRequest,\
response_class=ClientResponse, \
ws_response_class=ClientWebSocketResponse)
The class for creating client sessions and making requests.
:param aiohttp.connector.BaseConnector connector: BaseConnector
sub-class instance to support connection pooling.
:param loop: :ref:`event loop<asyncio-event-loop>` used for
processing HTTP requests.
If *loop* is ``None`` the constructor
borrows it from *connector* if specified.
:func:`asyncio.get_event_loop` is used for getting default event
loop otherwise.
:param dict cookies: Cookies to send with the request (optional)
:param dict headers: HTTP Headers to send with
the request (optional)
:param aiohttp.helpers.BasicAuth auth: BasicAuth named tuple that represents
HTTP Basic Authorization (optional)
:param request_class: Request class implementation. ``ClientRequest`` by
default.
:param response_class: Response class implementation. ``ClientResponse`` by
default.
:param ws_response_class: WebSocketResponse class implementation.
``ClientWebSocketResponse`` by default.
.. versionadded:: 0.16
.. versionchanged:: 0.16
*request_class* default changed from ``None`` to ``ClientRequest``
.. versionchanged:: 0.16
*response_class* default changed from ``None`` to ``ClientResponse``
.. attribute:: closed
``True`` if the session has been closed, ``False`` otherwise.
A read-only property.
.. attribute:: connector
:class:`aiohttp.connector.BaseConnector` derived instance used
for the session.
A read-only property.
.. attribute:: cookies
The session cookies, :class:`http.cookies.SimpleCookie` instance.
A read-only property. Overriding `session.cookies = new_val` is
forbidden, but you may modify the object in-place if needed.
.. coroutinemethod:: request(method, url, *, params=None, data=None,\
headers=None, auth=None, allow_redirects=True,\
max_redirects=10, encoding='utf-8',\
version=HttpVersion(major=1, minor=1),\
compress=None, chunked=None, expect100=False,\
read_until_eof=True)
Performs an asynchronous http request. Returns a response object.
:param str method: HTTP method
:param str url: Request URL
:param dict params: Parameters to be sent in the query
string of the new request (optional)
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:param dict headers: HTTP Headers to send with
the request (optional)
:param aiohttp.helpers.BasicAuth auth: BasicAuth named tuple that
represents HTTP Basic Authorization
(optional)
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
:param aiohttp.protocol.HttpVersion version: Request http version
(optional)
:param bool compress: Set to ``True`` if request has to be compressed
with deflate encoding.
``None`` by default (optional).
:param int chunked: Set to chunk size for chunked transfer encoding.
``None`` by default (optional).
:param bool expect100: Expect 100-continue response from server.
``False`` by default (optional).
:param bool read_until_eof: Read response until EOF if response
does not have Content-Length header.
``True`` by default (optional).
.. coroutinemethod:: get(url, *, allow_redirects=True, **kwargs)
Perform a ``GET`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param str url: Request URL
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
.. coroutinemethod:: post(url, *, data=None, **kwargs)
Perform a ``POST`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param str url: Request URL
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
.. coroutinemethod:: put(url, *, data=None, **kwargs)
Perform a ``PUT`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param str url: Request URL
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
.. coroutinemethod:: delete(url, **kwargs)
Perform a ``DELETE`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param str url: Request URL
.. coroutinemethod:: head(url, *, allow_redirects=False, **kwargs)
Perform a ``HEAD`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param str url: Request URL
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``False`` by default (optional).
.. coroutinemethod:: options(url, *, allow_redirects=True, **kwargs)
Perform an ``OPTIONS`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param str url: Request URL
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
.. coroutinemethod:: patch(url, *, data=None, **kwargs)
Perform a ``PATCH`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param str url: Request URL
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
.. coroutinemethod:: ws_connect(url, *, protocols=(), timeout=10.0\
autoclose=True, autoping=True)
Create a websocket connection. Returns a
:class:`ClientWebSocketResponse` object.
:param str url: Websocket server url
:param tuple protocols: Websocket protocols
:param float timeout: Timeout for websocket read. 10 seconds by default
:param bool autoclose: Automatically close websocket connection on close
message from server. If `autoclose` is False
them close procedure has to be handled manually
:param bool autoping: automatically send `pong` on `ping`
message from server
.. versionadded:: 0.16
.. method:: close()
Close underlying connector.
Release all acquired resources.
.. method:: detach()
Detach connector from session without closing the former.
Session is switched to closed state anyway.
Basic API
---------
While we encourage :class:`ClientSession` usage we also provide simple
coroutines for making HTTP requests.
Basic API is good for performing simple HTTP requests without
keepaliving, cookies and complex connection stuff like properly configured SSL
certification chaining.
.. coroutinefunction:: request(method, url, *, params=None, data=None, \
headers=None, cookies=None, files=None, auth=None, \
allow_redirects=True, max_redirects=10, \
encoding='utf-8', \
version=HttpVersion(major=1, minor=1), \
compress=None, chunked=None, expect100=False, \
connector=None, loop=None,\
read_until_eof=True, request_class=None,\
response_class=None)
Perform an asynchronous http request. Return a response object
(:class:`ClientResponse` or derived from).
:param str method: HTTP method
:param str url: Requested URL
:param dict params: Parameters to be sent in the query
string of the new request (optional)
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:param dict headers: HTTP Headers to send with
the request (optional)
:param dict cookies: Cookies to send with the request (optional)
:param aiohttp.helpers.BasicAuth auth: BasicAuth named tuple that represents
HTTP Basic Authorization (optional)
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
:param aiohttp.protocol.HttpVersion version: Request http version (optional)
:param bool compress: Set to ``True`` if request has to be compressed
with deflate encoding.
``None`` by default (optional).
:param int chunked: Set to chunk size for chunked transfer encoding.
``None`` by default (optional).
:param bool expect100: Expect 100-continue response from server.
``False`` by default (optional).
:param aiohttp.connector.BaseConnector connector: BaseConnector sub-class
instance to support connection pooling.
:param bool read_until_eof: Read response until EOF if response
does not have Content-Length header.
``True`` by default (optional).
:param request_class: Custom Request class implementation (optional)
:param response_class: Custom Response class implementation (optional)
:param loop: :ref:`event loop<asyncio-event-loop>`
used for processing HTTP requests.
If param is ``None``, :func:`asyncio.get_event_loop`
is used for getting default event loop, but we strongly
recommend to use explicit loops everywhere.
(optional)
Usage::
>>> import aiohttp
>>> resp = yield from aiohttp.request('GET', 'http://python.org/')
>>> resp
<ClientResponse(python.org/) [200]>
>>> data = yield from resp.read()
.. coroutinefunction:: get(url, **kwargs)
Perform a GET request.
:param str url: Requested URL.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. coroutinefunction:: options(url, **kwargs)
Perform a OPTIONS request.
:param str url: Requested URL.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. coroutinefunction:: head(url, **kwargs)
Perform a HEAD request.
:param str url: Requested URL.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. coroutinefunction:: delete(url, **kwargs)
Perform a DELETE request.
:param str url: Requested URL.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. coroutinefunction:: post(url, *, data=None, **kwargs)
Perform a POST request.
:param str url: Requested URL.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. coroutinefunction:: put(url, *, data=None, **kwargs)
Perform a PUT request.
:param str url: Requested URL.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. coroutinefunction:: patch(url, *, data=None, **kwargs)
Perform a PATCH request.
:param str url: Requested URL.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
Connectors
----------
.. module:: aiohttp.connector
Connectors are transports for aiohttp client API.
There are standard connectors:
1. :class:`TCPConnector` for regular *TCP sockets* (both *HTTP* and
*HTTPS* schemes supported).
2. :class:`ProxyConnector` for connecting via HTTP proxy.
3. :class:`UnixConnector` for connecting via UNIX socket (it's used mostly for
testing purposes).
All connector classes should be derived from :class:`BaseConnector`.
By default all *connectors* except :class:`ProxyConnector` support
*keep-alive connections* (behavior is controlled by *force_close*
constructor's parameter).
BaseConnector
^^^^^^^^^^^^^
.. class:: BaseConnector(*, conn_timeout=None, keepalive_timeout=30, \
limit=None, \
share_cookies=False, force_close=False, loop=None)
Base class for all connectors.
:param float conn_timeout: timeout for connection establishing
(optional). Values ``0`` or ``None``
mean no timeout.
:param float keepalive_timeout: timeout for connection reusing
after releasing (optional). Values
``0`` or ``None`` mean no timeout.
:param int limit: limit for simultaneous connections to the same
endpoint. Endpoints are the same if they are
have equal ``(host, port, is_ssl)`` triple.
If *limit* is ``None`` the connector has no limit.
:param bool share_cookies: update :attr:`cookies` on connection
processing (optional, deprecated).
:param bool force_close: do close underlying sockets after
connection releasing (optional).
:param loop: :ref:`event loop<asyncio-event-loop>`
used for handling connections.
If param is ``None``, :func:`asyncio.get_event_loop`
is used for getting default event loop, but we strongly
recommend to use explicit loops everywhere.
(optional)
.. deprecated:: 0.15.2
*share_cookies* parameter is deprecated, use
:class:`~aiohttp.client.ClientSession` for handling cookies for
client connections.
.. attribute:: closed
Read-only property, ``True`` if connector is closed.
.. attribute:: force_close
Read-only property, ``True`` if connector should ultimately
close connections on releasing.
.. versionadded:: 0.16
.. attribute:: limit
The limit for simultaneous connections to the same
endpoint.
Endpoints are the same if they are have equal ``(host, port,
is_ssl)`` triple.
If *limit* is ``None`` the connector has no limit (default).
Read-only property.
.. versionadded:: 0.16
.. method:: close()
Close all opened connections.
.. coroutinemethod:: connect(request)
Get a free connection from pool or create new one if connection
is absent in the pool.
The call may be paused if :attr:`limit` is exhausted until used
connections returns to pool.
:param aiohttp.client.ClientRequest request: request object
which is connection
initiator.
:return: :class:`Connection` object.
.. coroutinemethod:: _create_connection(req)
Abstract method for actual connection establishing, should be
overridden in subclasses.
TCPConnector
^^^^^^^^^^^^
.. class:: TCPConnector(*, verify_ssl=True, fingerprint=None, use_dns_cache=False, \
family=socket.AF_INET, \
ssl_context=None, conn_timeout=None, \
keepalive_timeout=30, limit=None, share_cookies=False, \
force_close=False, loop=None)
Connector for working with *HTTP* and *HTTPS* via *TCP* sockets.
The most common transport. When you don't know what connector type
to use, use a :class:`TCPConnector` instance.
:class:`TCPConnector` inherits from :class:`BaseConnector`.
Constructor accepts all parameters suitable for
:class:`BaseConnector` plus several TCP-specific ones:
:param bool verify_ssl: Perform SSL certificate validation for
*HTTPS* requests (enabled by default). May be disabled to
skip validation for sites with invalid certificates.
:param bytes fingerprint: Pass the binary MD5, SHA1, or SHA256
digest of the expected certificate in DER format to verify
that the certificate the server presents matches. Useful
for `certificate pinning
<https://en.wikipedia.org/wiki/Transport_Layer_Security#Certificate_pinning>`_.
.. versionadded:: 0.16
:param bool use_dns_cache: use internal cache for DNS lookups, ``False``
by default.
Enabling an option *may* speedup connection
establishing a bit but may introduce some
*side effects* also.
.. versionadded:: 0.17
:param bool resolve: alias for *use_dns_cache* parameter.
.. deprecated:: 0.17
:param int family: TCP socket family, ``AF_INET`` by default
(*IPv4*). For *IPv6* use ``AF_INET6``.
:param ssl.SSLContext ssl_context: ssl context used for processing
*HTTPS* requests (optional).
*ssl_context* may be used for configuring certification
authority channel, supported SSL options etc.
.. attribute:: verify_ssl
Check *ssl certifications* if ``True``.
Read-only :class:`bool` property.
.. attribute:: ssl_context
:class:`ssl.SSLContext` instance for *https* requests, read-only property.
.. attribute:: family
*TCP* socket family e.g. :const:`socket.AF_INET` or
:const:`socket.AF_INET6`
Read-only property.
.. attribute:: dns_cache
Use quick lookup in internal *DNS* cache for host names if ``True``.
Read-only :class:`bool` property.
.. versionadded:: 0.17
.. attribute:: resolve
Alias for :attr:`dns_cache`.
.. deprecated:: 0.17
.. attribute:: cached_hosts
The cache of resolved hosts if :attr:`dns_cache` is enabled.
Read-only :class:`types.MappingProxyType` property.
.. versionadded:: 0.17
.. attribute:: resolved_hosts
Alias for :attr:`cached_hosts`
.. deprecated:: 0.17
.. attribute:: fingerprint
MD5, SHA1, or SHA256 hash of the expected certificate in DER
format, or ``None`` if no certificate fingerprint check
required.
Read-only :class:`bytes` property.
.. versionadded:: 0.16
.. method:: clear_dns_cache(self, host=None, port=None)
Clear internal *DNS* cache.
Remove specific entry if both *host* and *port* are specified,
clear all cache otherwise.
.. versionadded:: 0.17
.. method:: clear_resolved_hosts(self, host=None, port=None)
Alias for :meth:`clear_dns_cache`.
.. deprecated:: 0.17
ProxyConnector
^^^^^^^^^^^^^^
.. class:: ProxyConnector(proxy, *, proxy_auth=None, \
conn_timeout=None, \
keepalive_timeout=30, limit=None, \
share_cookies=False, \
force_close=True, loop=None)
HTTP Proxy connector.
Use :class:`ProxyConnector` for sending *HTTP/HTTPS* requests
through *HTTP proxy*.
:class:`ProxyConnector` is inherited from :class:`TCPConnector`.
Usage::
>>> conn = ProxyConnector(proxy="http://some.proxy.com")
>>> session = ClientSession(connector=conn)
>>> resp = yield from session.get('http://python.org')
Constructor accepts all parameters suitable for
:class:`TCPConnector` plus several proxy-specific ones:
:param str proxy: URL for proxy, e.g. ``"http://some.proxy.com"``.
:param aiohttp.helpers.BasicAuth proxy_auth: basic
authentication info used for proxies with authorization.
.. note::
:class:`ProxyConnector` in opposite to all other connectors
**doesn't** support *keep-alives* by default
(:attr:`force_close` is ``True``).
.. versionchanged:: 0.16
*force_close* parameter changed to ``True`` by default.
.. attribute:: proxy
Proxy *URL*, read-only :class:`str` property.
.. attribute:: proxy_auth
Proxy authentication info, read-only :class:`BasicAuth` property
or ``None`` for proxy without authentication.
.. versionadded:: 0.16
UnixConnector
^^^^^^^^^^^^^
.. class:: UnixConnector(path, *, \
conn_timeout=None, \
keepalive_timeout=30, limit=None, \
share_cookies=False, \
force_close=False, loop=None)
Unix socket connector.
Use :class:`ProxyConnector` for sending *HTTP/HTTPS* requests
through *UNIX Sockets* as underlying transport.
UNIX sockets are handy for writing tests and making very fast
connections between processes on the same host.
:class:`UnixConnector` is inherited from :class:`BaseConnector`.
Usage::
>>> conn = UnixConnector(path='/path/to/socket')
>>> session = ClientSession(connector=conn)
>>> resp = yield from session.get('http://python.org')
Constructor accepts all parameters suitable for
:class:`BaseConnector` plus UNIX-specific one:
:param str path: Unix socket path
.. attribute:: path
Path to *UNIX socket*, read-only :class:`str` property.
Connection
^^^^^^^^^^
.. class:: Connection
Encapsulates single connection in connector object.
End user should never create :class:`Connection` instances manually
but get it by :meth:`BaseConnector.connect` coroutine.
.. attribute:: closed
:class:`bool` read-only property, ``True`` if connection was
closed, released or detached.
.. attribute:: loop
Event loop used for connection
.. method:: close()
Close connection with forcibly closing underlying socket.
.. method:: release()
Release connection back to connector.
Underlying socket is not closed, the connection may be reused
later if timeout (30 seconds by default) for connection was not
expired.
.. method:: detach()
Detach underlying socket from connection.
Underlying socket is not closed, next :meth:`close` or
:meth:`release` calls don't return socket to free pool.
.. disqus::
|