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 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
|
.. _aiohttp-client-reference:
Client Reference
================
.. module:: aiohttp
.. currentmodule:: aiohttp
Client Session
--------------
Client session is the recommended interface for making HTTP requests.
Session encapsulates a *connection pool* (*connector* instance) and
supports keepalives by default. Unless you are connecting to a large,
unknown number of different servers over the lifetime of your
application, it is suggested you use a single session for the
lifetime of your application to benefit from connection pooling.
Usage example::
import aiohttp
import asyncio
async def fetch(client):
async with client.get('http://python.org') as resp:
assert resp.status == 200
return await resp.text()
async def main(loop):
async with aiohttp.ClientSession(loop=loop) as client:
html = await fetch(client)
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
.. versionadded:: 0.17
The client session supports the context manager protocol for self closing.
.. class:: ClientSession(*, connector=None, loop=None, cookies=None, \
headers=None, skip_auto_headers=None, \
auth=None, \
version=aiohttp.HttpVersion11, \
cookie_jar=None)
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 headers: HTTP Headers to send with
the request (optional).
May be either *iterable of key-value pairs* or
:class:`~collections.abc.Mapping`
(e.g. :class:`dict`,
:class:`~aiohttp.CIMultiDict`).
:param skip_auto_headers: set of headers for which autogeneration
should be skipped.
*aiohttp* autogenerates headers like ``User-Agent`` or
``Content-Type`` if these headers are not explicitly
passed. Using ``skip_auto_headers`` parameter allows to skip
that generation. Note that ``Content-Length`` autogeneration can't
be skipped.
Iterable of :class:`str` or :class:`~aiohttp.upstr` (optional)
:param aiohttp.BasicAuth auth: an object that represents HTTP Basic
Authorization (optional)
:param version: supported HTTP version, ``HTTP 1.1`` by default.
.. versionadded:: 0.21
:param cookie_jar: Cookie Jar, :class:`AbstractCookieJar` instance.
By default every session instance has own private cookie jar for
automatic cookies processing but user may redefine this behavior
by providing own jar implementation.
One example is not processing cookies at all when working in
proxy mode.
.. versionadded:: 0.22
.. versionchanged:: 1.0
``.cookies`` attribute was dropped. Use :attr:`cookie_jar`
instead.
.. 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:: cookie_jar
The session cookies, :class:`~aiohttp.AbstractCookieJar` instance.
Gives access to cookie jar's content and modifiers.
A read-only property.
.. versionadded:: 1.0
.. attribute:: loop
A loop instance used for session creation.
A read-only property.
.. comethod:: request(method, url, *, params=None, data=None,\
headers=None, skip_auto_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,\
proxy=None, proxy_auth=None,\
timeout=5*60)
:async-with:
:coroutine:
Performs an asynchronous HTTP request. Returns a response object.
:param str method: HTTP method
:param url: Request URL, :class:`str` or :class:`~yarl.URL`.
:param params: Mapping, iterable of tuple of *key*/*value* pairs or
string to be sent as parameters in the query
string of the new request. Ignored for subsequent
redirected requests (optional)
Allowed values are:
- :class:`collections.abc.Mapping` e.g. :class:`dict`,
:class:`aiohttp.MultiDict` or
:class:`aiohttp.MultiDictProxy`
- :class:`collections.abc.Iterable` e.g. :class:`tuple` or
:class:`list`
- :class:`str` with preferably url-encoded content
(**Warning:** content will not be encoded by *aiohttp*)
: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 skip_auto_headers: set of headers for which autogeneration
should be skipped.
*aiohttp* autogenerates headers like ``User-Agent`` or
``Content-Type`` if these headers are not explicitly
passed. Using ``skip_auto_headers`` parameter allows to skip
that generation.
Iterable of :class:`str` or :class:`~aiohttp.upstr`
(optional)
:param aiohttp.BasicAuth auth: an object 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).
:param proxy: Proxy URL, :class:`str` or :class:`~yarl.URL` (optional)
:param aiohttp.BasicAuth proxy_auth: an object that represents proxy HTTP
Basic Authorization (optional)
:param int timeout: a timeout for IO operations, 5min by default.
Use ``None`` or ``0`` to disable timeout checks.
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionadded:: 1.0
Added ``proxy`` and ``proxy_auth`` parameters.
Added ``timeout`` parameter.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: get(url, *, allow_redirects=True, **kwargs)
:async-with:
:coroutine:
Perform a ``GET`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: post(url, *, data=None, **kwargs)
:async-with:
:coroutine:
Perform a ``POST`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: put(url, *, data=None, **kwargs)
:async-with:
:coroutine:
Perform a ``PUT`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: delete(url, **kwargs)
:async-with:
:coroutine:
Perform a ``DELETE`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: head(url, *, allow_redirects=False, **kwargs)
:async-with:
:coroutine:
Perform a ``HEAD`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``False`` by default (optional).
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: options(url, *, allow_redirects=True, **kwargs)
:async-with:
:coroutine:
Perform an ``OPTIONS`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: patch(url, *, data=None, **kwargs)
:async-with:
:coroutine:
Perform a ``PATCH`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: ws_connect(url, *, protocols=(), timeout=10.0,\
auth=None,\
autoclose=True,\
autoping=True,\
origin=None, \
proxy=None, proxy_auth=None)
:async-with:
:coroutine:
Create a websocket connection. Returns a
:class:`ClientWebSocketResponse` object.
:param url: Websocket server url, :class:`str` or :class:`~yarl.URL`
:param tuple protocols: Websocket protocols
:param float timeout: Timeout for websocket read. 10 seconds by default
:param aiohttp.BasicAuth auth: an object that represents HTTP
Basic Authorization (optional)
: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
:param str origin: Origin header to send to server
:param str proxy: Proxy URL, :class:`str` or :class:`~yarl.URL` (optional)
:param aiohttp.BasicAuth proxy_auth: an object that represents proxy HTTP
Basic Authorization (optional)
.. versionadded:: 0.16
Add :meth:`ws_connect`.
.. versionadded:: 0.18
Add *auth* parameter.
.. versionadded:: 0.19
Add *origin* parameter.
.. versionadded:: 1.0
Added ``proxy`` and ``proxy_auth`` parameters.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: close()
Close underlying connector.
Release all acquired resources.
.. versionchanged:: 0.21
The method is converted into coroutine (but technically
returns a future for keeping backward compatibility during
transition period).
.. 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, 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)
Perform an asynchronous HTTP request. Return a response object
(:class:`ClientResponse` or derived from).
:param str method: HTTP method
:param url: Requested URL, :class:`str` or :class:`~yarl.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.BasicAuth auth: an object 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.
``False`` instructs aiohttp to not compress data
even if the Content-Encoding header is set. Use it
when sending pre-compressed data.
``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 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)
:return ClientResponse: a :class:`client response <ClientResponse>` object.
Usage::
import aiohttp
async def fetch():
async with aiohttp.request('GET', 'http://python.org/') as resp:
assert resp.status == 200
print(await resp.text())
.. deprecated:: 0.21
Use :meth:`ClientSession.request`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: get(url, **kwargs)
Perform a GET request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.get`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: options(url, **kwargs)
Perform an OPTIONS request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.options`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: head(url, **kwargs)
Perform a HEAD request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.head`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: delete(url, **kwargs)
Perform a DELETE request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.delete`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: post(url, *, data=None, **kwargs)
Perform a POST request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.post`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: put(url, *, data=None, **kwargs)
Perform a PUT request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.put`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: patch(url, *, data=None, **kwargs)
Perform a PATCH request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.patch`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: ws_connect(url, *, protocols=(), \
timeout=10.0, connector=None, auth=None,\
autoclose=True, autoping=True, loop=None,\
origin=None, headers=None)
This function creates a websocket connection, checks the response and
returns a :class:`ClientWebSocketResponse` object. In case of failure
it may raise a :exc:`~aiohttp.errors.WSServerHandshakeError` exception.
:param url: Websocket server url, :class:`str` or :class:`~yarl.URL`
:param tuple protocols: Websocket protocols
:param float timeout: Timeout for websocket read. 10 seconds by default
:param obj connector: object :class:`TCPConnector`
: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
:param aiohttp.helpers.BasicAuth auth: BasicAuth named tuple that
represents HTTP Basic Authorization
(optional)
:param loop: :ref:`event loop<asyncio-event-loop>` used
for processing HTTP requests.
If param is ``None`` :func:`asyncio.get_event_loop`
used for getting default event loop, but we strongly
recommend to use explicit loops everywhere.
:param str origin: Origin header to send to server
:param headers: :class:`dict`, :class:`CIMultiDict` or
:class:`CIMultiDictProxy` for providing additional
headers for websocket handshake request.
.. versionadded:: 0.18
Add *auth* parameter.
.. versionadded:: 0.19
Add *origin* parameter.
.. versionadded:: 0.20
Add *headers* parameter.
.. deprecated:: 0.21
Use :meth:`ClientSession.ws_connect`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. _aiohttp-client-reference-connectors:
Connectors
----------
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 (deprecated).
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=20, \
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``. For disabling *keep-alive*
feature use ``force_close=True``
flag.
: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 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)
.. versionchanged:: 1.0
``limit`` changed from unlimited (``None``) to 20.
Expect a max of up to 20 connections to the same endpoint,
if it is not specified.
For limitless connections, pass `None` explicitly.
.. 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
.. comethod:: close()
Close all opened connections.
.. versionchanged:: 0.21
The method is converted into coroutine (but technically
returns a future for keeping backward compatibility during
transition period).
.. comethod:: 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.
.. comethod:: _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=True, \
family=0, \
ssl_context=None, conn_timeout=None, \
keepalive_timeout=30, limit=None, \
force_close=False, loop=None, local_addr=None,
resolver=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 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>`_.
Note: use of MD5 or SHA1 digests is insecure and deprecated.
.. versionadded:: 0.16
:param bool use_dns_cache: use internal cache for DNS lookups, ``True``
by default.
Enabling an option *may* speedup connection
establishing a bit but may introduce some
*side effects* also.
.. versionadded:: 0.17
.. versionchanged:: 1.0
The default is changed to ``True``
:param aiohttp.abc.AbstractResolver resolver: Custom resolver
instance to use. ``aiohttp.DefaultResolver`` by
default (asynchronous if ``aiodns>=1.1`` is installed).
Custom resolvers allow to resolve hostnames differently than the
way the host is configured.
.. versionadded:: 0.22
.. versionchanged:: 1.0
The resolver is ``aiohttp.AsyncResolver`` now if
:term:`aiodns` is installed.
:param bool resolve: alias for *use_dns_cache* parameter.
.. deprecated:: 0.17
:param int family: TCP socket family, both IPv4 and IPv6 by default.
For *IPv4* only use :const:`socket.AF_INET`,
for *IPv6* only -- :const:`socket.AF_INET6`.
.. versionchanged:: 0.18
*family* is `0` by default, that means both IPv4 and IPv6 are
accepted. To specify only concrete version please pass
:const:`socket.AF_INET` or :const:`socket.AF_INET6`
explicitly.
: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.
:param tuple local_addr: tuple of ``(local_host, local_port)`` used to bind
socket locally if specified.
.. versionadded:: 0.21
.. 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, \
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`.
.. deprecated:: 1.0
Use :meth:`ClientSession.request` with :attr:`proxy` and
:attr:`proxy_auth` parameters.
Usage::
conn = ProxyConnector(proxy="http://some.proxy.com")
session = ClientSession(connector=conn)
async with session.get('http://python.org') as resp:
assert resp.status == 200
Constructor accepts all parameters suitable for
:class:`TCPConnector` plus several proxy-specific ones:
:param str proxy: URL for proxy :class:`str` or :class:`~yarl.URL`,
e.g. ``URL("http://some.proxy.com")``.
:param aiohttp.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:`~yarl.URL` property.
.. versionchanged:: 1.1
The attribute type was changed from :class:`str` to
:class:`~yarl.URL`.
.. 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, \
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)
async with session.get('http://python.org') as resp:
...
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.
Response object
---------------
.. class:: ClientResponse
Client response returned be :meth:`ClientSession.request` and family.
User never creates the instance of ClientResponse class but gets it
from API calls.
:class:`ClientResponse` supports async context manager protocol, e.g.::
resp = await client_session.get(url)
async with resp:
assert resp.status == 200
After exiting from ``async with`` block response object will be
*released* (see :meth:`release` coroutine).
.. versionadded:: 0.18
Support for ``async with``.
.. attribute:: version
Response's version, :class:`HttpVersion` instance.
.. attribute:: status
HTTP status code of response (:class:`int`), e.g. ``200``.
.. attribute:: reason
HTTP status reason of response (:class:`str`), e.g. ``"OK"``.
.. attribute:: method
Request's method (:class:`str`).
.. attribute:: url
URL of request (:class:`str`).
.. deprecated:: 1.1
.. attribute:: url_obj
URL of request (:class:`~yarl.URL`).
.. versionadded:: 1.1
.. attribute:: connection
:class:`Connection` used for handling response.
.. attribute:: content
Payload stream, contains response's BODY (:class:`StreamReader`).
Reading from the stream raises
:exc:`aiohttp.ClientDisconnectedError` if the response object is
closed before read calls.
.. attribute:: cookies
HTTP cookies of response (*Set-Cookie* HTTP header,
:class:`~http.cookies.SimpleCookie`).
.. attribute:: headers
A case-insensitive multidict proxy with HTTP headers of
response, :class:`CIMultiDictProxy`.
.. attribute:: raw_headers
HTTP headers of response as unconverted bytes, a sequence of
``(key, value)`` pairs.
.. attribute:: content_type
Read-only property with *content* part of *Content-Type* header.
.. note::
Returns value is ``'application/octet-stream'`` if no
Content-Type header present in HTTP headers according to
:rfc:`2616`. To make sure Content-Type header is not present in
the server reply, use :attr:`headers` or :attr:`raw_headers`, e.g.
``'CONTENT-TYPE' not in resp.headers``.
.. attribute:: charset
Read-only property that specifies the *encoding* for the request's BODY.
The value is parsed from the *Content-Type* HTTP header.
Returns :class:`str` like ``'utf-8'`` or ``None`` if no *Content-Type*
header present in HTTP headers or it has no charset information.
.. attribute:: history
A :class:`~collections.abc.Sequence` of :class:`ClientResponse`
objects of preceding requests if there were redirects, an empty
sequence otherwise.
.. method:: close()
Close response and underlying connection.
For :term:`keep-alive` support see :meth:`release`.
.. comethod:: read()
Read the whole response's body as :class:`bytes`.
Close underlying connection if data reading gets an error,
release connection otherwise.
:return bytes: read *BODY*.
.. seealso:: :meth:`close`, :meth:`release`.
.. comethod:: release()
Finish response processing, release underlying connection and
return it into free connection pool for re-usage by next upcoming
request.
.. method:: raise_for_status()
Raise an HttpProcessingError if the response status is 400 or higher.
Do nothing for success responses (less than 400).
.. comethod:: text(encoding=None)
Read response's body and return decoded :class:`str` using
specified *encoding* parameter.
If *encoding* is ``None`` content encoding is autocalculated
using :term:`cchardet` or :term:`chardet` as fallback if
*cchardet* is not available.
Close underlying connection if data reading gets an error,
release connection otherwise.
:param str encoding: text encoding used for *BODY* decoding, or
``None`` for encoding autodetection
(default).
:return str: decoded *BODY*
.. comethod:: json(encoding=None, loads=json.loads)
Read response's body as *JSON*, return :class:`dict` using
specified *encoding* and *loader*.
If *encoding* is ``None`` content encoding is autocalculated
using :term:`cchardet` or :term:`chardet` as fallback if
*cchardet* is not available.
Close underlying connection if data reading gets an error,
release connection otherwise.
:param str encoding: text encoding used for *BODY* decoding, or
``None`` for encoding autodetection
(default).
:param callable loads: :func:`callable` used for loading *JSON*
data, :func:`json.loads` by default.
:return: *BODY* as *JSON* data parsed by *loads* parameter or
``None`` if *BODY* is empty or contains white-spaces
only.
ClientWebSocketResponse
-----------------------
To connect to a websocket server :func:`aiohttp.ws_connect` or
:meth:`aiohttp.ClientSession.ws_connect` coroutines should be used, do
not create an instance of class :class:`ClientWebSocketResponse`
manually.
.. class:: ClientWebSocketResponse()
Class for handling client-side websockets.
.. attribute:: closed
Read-only property, ``True`` if :meth:`close` has been called of
:const:`~aiohttp.WSMsgType.CLOSE` message has been received from peer.
.. attribute:: protocol
Websocket *subprotocol* chosen after :meth:`start` call.
May be ``None`` if server and client protocols are
not overlapping.
.. method:: exception()
Returns exception if any occurs or returns None.
.. method:: ping(message=b'')
Send :const:`~aiohttp.WSMsgType.PING` to peer.
:param message: optional payload of *ping* message,
:class:`str` (converted to *UTF-8* encoded bytes)
or :class:`bytes`.
.. method:: send_str(data)
Send *data* to peer as :const:`~aiohttp.WSMsgType.TEXT` message.
:param str data: data to send.
:raise TypeError: if data is not :class:`str`
.. method:: send_bytes(data)
Send *data* to peer as :const:`~aiohttp.WSMsgType.BINARY` message.
:param data: data to send.
:raise TypeError: if data is not :class:`bytes`,
:class:`bytearray` or :class:`memoryview`.
.. method:: send_json(data, *, dumps=json.loads)
Send *data* to peer as JSON string.
:param data: data to send.
:param callable dumps: any :term:`callable` that accepts an object and
returns a JSON string
(:func:`json.dumps` by default).
:raise RuntimeError: if connection is not started or closing
:raise ValueError: if data is not serializable object
:raise TypeError: if value returned by ``dumps(data)`` is not
:class:`str`
.. comethod:: close(*, code=1000, message=b'')
A :ref:`coroutine<coroutine>` that initiates closing handshake by sending
:const:`~aiohttp.WSMsgType.CLOSE` message. It waits for
close response from server. It add timeout to `close()` call just wrap
call with `asyncio.wait()` or `asyncio.wait_for()`.
:param int code: closing code
:param message: optional payload of *pong* message,
:class:`str` (converted to *UTF-8* encoded bytes)
or :class:`bytes`.
.. comethod:: receive()
A :ref:`coroutine<coroutine>` that waits upcoming *data*
message from peer and returns it.
The coroutine implicitly handles
:const:`~aiohttp.WSMsgType.PING`,
:const:`~aiohttp.WSMsgType.PONG` and
:const:`~aiohttp.WSMsgType.CLOSE` without returning the
message.
It process *ping-pong game* and performs *closing handshake* internally.
:return: :class:`~aiohttp.WSMessage`, `tp` is a type from
:class:`~aiohttp.WSMsgType` enumeration.
.. coroutinemethod:: receive_str()
A :ref:`coroutine<coroutine>` that calls :meth:`receive` but
also asserts the message type is
:const:`~aiohttp.WSMsgType.TEXT`.
:return str: peer's message content.
:raise TypeError: if message is :const:`~aiohttp.WSMsgType.BINARY`.
.. coroutinemethod:: receive_bytes()
A :ref:`coroutine<coroutine>` that calls :meth:`receive` but
also asserts the message type is
:const:`~aiohttp.WSMsgType.BINARY`.
:return bytes: peer's message content.
:raise TypeError: if message is :const:`~aiohttp.WSMsgType.TEXT`.
.. coroutinemethod:: receive_json(*, loads=json.loads)
A :ref:`coroutine<coroutine>` that calls :meth:`receive_str` and loads
the JSON string to a Python dict.
:param callable loads: any :term:`callable` that accepts
:class:`str` and returns :class:`dict`
with parsed JSON (:func:`json.loads` by
default).
:return dict: loaded JSON content
:raise TypeError: if message is :const:`~aiohttp.WSMsgType.BINARY`.
:raise ValueError: if message is not valid JSON.
Utilities
---------
BasicAuth
^^^^^^^^^
.. class:: BasicAuth(login, password='', encoding='latin1')
HTTP basic authentication helper.
:param str login: login
:param str password: password
:param str encoding: encoding (`'latin1'` by default)
Should be used for specifying authorization data in client API,
e.g. *auth* parameter for :meth:`ClientSession.request`.
.. classmethod:: decode(auth_header, encoding='latin1')
Decode HTTP basic authentication credentials.
:param str auth_header: The ``Authorization`` header to decode.
:param str encoding: (optional) encoding ('latin1' by default)
:return: decoded authentication data, :class:`BasicAuth`.
.. method:: encode()
Encode credentials into string suitable for ``Authorization``
header etc.
:return: encoded authentication data, :class:`str`.
CookieJar
^^^^^^^^^
.. class:: CookieJar(unsafe=False, loop=None)
The cookie jar instance is available as :attr:`ClientSession.cookie_jar`.
The jar contains :class:`~http.cookies.Morsel` items for storing
internal cookie data.
API provides a count of saved cookies::
len(session.cookie_jar)
These cookies may be iterated over::
for cookie in session.cookie_jar:
print(cookie.key)
print(cookie["domain"])
The class implements :class:`collections.abc.Iterable`,
:class:`collections.abc.Sized` and
:class:`aiohttp.AbstractCookieJar` interfaces.
Implements cookie storage adhering to RFC 6265.
:param bool unsafe: (optional) Whether to accept cookies from IPs.
:param bool loop: an :ref:`event loop<asyncio-event-loop>` instance.
See :class:`aiohttp.abc.AbstractCookieJar`
.. method:: update_cookies(cookies, response_url=None)
Update cookies returned by server in ``Set-Cookie`` header.
:param cookies: a :class:`collections.abc.Mapping`
(e.g. :class:`dict`, :class:`~http.cookies.SimpleCookie`) or
*iterable* of *pairs* with cookies returned by server's
response.
:param str response_url: URL of response, ``None`` for *shared
cookies*. Regular cookies are coupled with server's URL and
are sent only to this server, shared ones are sent in every
client request.
.. method:: filter_cookies(request_url)
Return jar's cookies acceptable for URL and available in
``Cookie`` header for sending client requests for given URL.
:param str response_url: request's URL for which cookies are asked.
:return: :class:`http.cookies.SimpleCookie` with filtered
cookies for given URL.
.. method:: save(file_path)
Write a pickled representation of cookies into the file
at provided path.
:param file_path: Path to file where cookies will be serialized,
:class:`str` or :class:`pathlib.Path` instance.
.. method:: load(file_path)
Load a pickled representation of cookies from the file
at provided path.
:param file_path: Path to file from where cookies will be
imported, :class:`str` or :class:`pathlib.Path` instance.
.. disqus::
:title: aiohttp client reference
|