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
|
.. _aiohttp-web-reference:
HTTP Server Reference
=====================
.. highlight:: python
.. module:: aiohttp.web
.. versionchanged:: 0.12
The module was deeply refactored in backward incompatible manner.
.. _aiohttp-web-request:
Request
-------
The Request object contains all the information about an incoming HTTP request.
Every :ref:`handler<aiohttp-web-handler>` accepts a request instance as the
first positional parameter.
.. note::
You should never create the :class:`Request` instance manually --
:mod:`aiohttp.web` does it for you.
.. class:: Request
.. attribute:: scheme
A string representing the scheme of the request.
The scheme is ``'https'`` if transport for request handling is
*SSL* or ``secure_proxy_ssl_header`` is matching.
``'http'`` otherwise.
Read-only :class:`str` property.
.. attribute:: method
*HTTP method*, read-only property.
The value is upper-cased :class:`str` like ``"GET"``,
``"POST"``, ``"PUT"`` etc.
.. attribute:: version
*HTTP version* of request, Read-only property.
Returns :class:`aiohttp.protocol.HttpVersion` instance.
.. attribute:: host
*HOST* header of request, Read-only property.
Returns :class:`str` or ``None`` if HTTP request has no *HOST* header.
.. attribute:: path_qs
The URL including PATH_INFO and the query string. e.g, ``/app/blog?id=10``
Read-only :class:`str` property.
.. attribute:: path
The URL including *PATH INFO* without the host or scheme. e.g.,
``/app/blog``. The path is URL-unquoted. For raw path info see
:attr:`raw_path`.
Read-only :class:`str` property.
.. attribute:: raw_path
The URL including raw *PATH INFO* without the host or scheme.
Warning, the path may be quoted and may contains non valid URL
characters, e.g.
``/my%2Fpath%7Cwith%21some%25strange%24characters``.
For unquoted version please take a look on :attr:`path`.
Read-only :class:`str` property.
.. attribute:: query_string
The query string in the URL, e.g., ``id=10``
Read-only :class:`str` property.
.. attribute:: GET
A multidict with all the variables in the query string.
Read-only :class:`~aiohttp.multidict.MultiDictProxy` lazy property.
.. versionchanged:: 0.17
A multidict contains empty items for query string like ``?arg=``.
.. attribute:: POST
A multidict with all the variables in the POST parameters.
POST property available only after :meth:`Request.post` coroutine call.
Read-only :class:`~aiohttp.multidict.MultiDictProxy`.
:raises RuntimeError: if :meth:`Request.post` was not called \
before accessing the property.
.. attribute:: headers
A case-insensitive multidict proxy with all headers.
Read-only :class:`~aiohttp.multidict.CIMultiDictProxy` property.
.. attribute:: keep_alive
``True`` if keep-alive connection enabled by HTTP client and
protocol version supports it, otherwise ``False``.
Read-only :class:`bool` property.
.. attribute:: match_info
Read-only property with :class:`~aiohttp.abc.AbstractMatchInfo`
instance for result of route resolving.
.. note::
Exact type of property depends on used router. If
``app.router`` is :class:`UrlDispatcher` the property contains
:class:`UrlMappingMatchInfo` instance.
.. attribute:: app
An :class:`Application` instance used to call :ref:`request handler
<aiohttp-web-handler>`, Read-only property.
.. attribute:: transport
An :ref:`transport<asyncio-transport>` used to process request,
Read-only property.
The property can be used, for example, for getting IP address of
client's peer::
peername = request.transport.get_extra_info('peername')
if peername is not None:
host, port = peername
.. attribute:: cookies
A multidict of all request's cookies.
Read-only :class:`~aiohttp.multidict.MultiDictProxy` lazy property.
.. attribute:: content
A :class:`~aiohttp.streams.FlowControlStreamReader` instance,
input stream for reading request's *BODY*.
Read-only property.
.. versionadded:: 0.15
.. attribute:: has_body
Return ``True`` if request has *HTTP BODY*, ``False`` otherwise.
Read-only :class:`bool` property.
.. versionadded:: 0.16
.. attribute:: payload
A :class:`~aiohttp.streams.FlowControlStreamReader` instance,
input stream for reading request's *BODY*.
Read-only property.
.. deprecated:: 0.15
Use :attr:`~Request.content` instead.
.. attribute:: content_type
Read-only property with *content* part of *Content-Type* header.
Returns :class:`str` like ``'text/html'``
.. note::
Returns value is ``'application/octet-stream'`` if no
Content-Type header present in HTTP headers according to
:rfc:`2616`
.. 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
*Content-Type* has no charset information.
.. attribute:: content_length
Read-only property that returns length of the request's BODY.
The value is parsed from the *Content-Length* HTTP header.
Returns :class:`int` or ``None`` if *Content-Length* is absent.
.. attribute:: if_modified_since
Read-only property that returns the date specified in the
*If-Modified-Since* header.
Returns :class:`datetime.datetime` or ``None`` if
*If-Modified-Since* header is absent or is not a valid
HTTP date.
.. coroutinemethod:: read()
Read request body, returns :class:`bytes` object with body content.
.. note::
The method **does** store read data internally, subsequent
:meth:`~Request.read` call will return the same value.
.. coroutinemethod:: text()
Read request body, decode it using :attr:`charset` encoding or
``UTF-8`` if no encoding was specified in *MIME-type*.
Returns :class:`str` with body content.
.. note::
The method **does** store read data internally, subsequent
:meth:`~Request.text` call will return the same value.
.. coroutinemethod:: json(*, loader=json.loads)
Read request body decoded as *json*.
The method is just a boilerplate :ref:`coroutine <coroutine>`
implemented as::
@asyncio.coroutine
def json(self, *, loader=json.loads):
body = yield from self.text()
return loader(body)
:param callable loader: any :term:`callable` that accepts
:class:`str` and returns :class:`dict`
with parsed JSON (:func:`json.loads` by
default).
.. note::
The method **does** store read data internally, subsequent
:meth:`~Request.json` call will return the same value.
.. coroutinemethod:: post()
A :ref:`coroutine <coroutine>` that reads POST parameters from
request body.
Returns :class:`~aiohttp.multidict.MultiDictProxy` instance filled
with parsed data.
If :attr:`method` is not *POST*, *PUT* or *PATCH* or
:attr:`content_type` is not empty or
*application/x-www-form-urlencoded* or *multipart/form-data*
returns empty multidict.
.. note::
The method **does** store read data internally, subsequent
:meth:`~Request.post` call will return the same value.
.. coroutinemethod:: release()
Release request.
Eat unread part of HTTP BODY if present.
.. note::
User code may never call :meth:`~Request.release`, all
required work will be processed by :mod:`aiohttp.web`
internal machinery.
.. _aiohttp-web-response:
Response classes
----------------
For now, :mod:`aiohttp.web` has two classes for the *HTTP response*:
:class:`StreamResponse` and :class:`Response`.
Usually you need to use the second one. :class:`StreamResponse` is
intended for streaming data, while :class:`Response` contains *HTTP
BODY* as an attribute and sends own content as single piece with the
correct *Content-Length HTTP header*.
For sake of design decisions :class:`Response` is derived from
:class:`StreamResponse` parent class.
The response supports *keep-alive* handling out-of-the-box if
*request* supports it.
You can disable *keep-alive* by :meth:`~StreamResponse.force_close` though.
The common case for sending an answer from
:ref:`web-handler<aiohttp-web-handler>` is returning a
:class:`Response` instance::
def handler(request):
return Response("All right!")
StreamResponse
^^^^^^^^^^^^^^
.. class:: StreamResponse(*, status=200, reason=None)
The base class for the *HTTP response* handling.
Contains methods for setting *HTTP response headers*, *cookies*,
*response status code*, writing *HTTP response BODY* and so on.
The most important thing you should know about *response* --- it
is *Finite State Machine*.
That means you can do any manipulations with *headers*,
*cookies* and *status code* only before :meth:`start`
called.
Once you call :meth:`start` any change of
the *HTTP header* part will raise :exc:`RuntimeError` exception.
Any :meth:`write` call after :meth:`write_eof` is also forbidden.
:param int status: HTTP status code, ``200`` by default.
:param str reason: HTTP reason. If param is ``None`` reason will be
calculated basing on *status*
parameter. Otherwise pass :class:`str` with
arbitrary *status* explanation..
.. attribute:: started
Read-only :class:`bool` property, ``True`` if :meth:`start` has
been called, ``False`` otherwise.
.. attribute:: status
Read-only property for *HTTP response status code*, :class:`int`.
``200`` (OK) by default.
.. attribute:: reason
Read-only property for *HTTP response reason*, :class:`str`.
.. method:: set_status(status, reason=None)
Set :attr:`status` and :attr:`reason`.
*reason* value is auto calculated if not specified (``None``).
.. attribute:: keep_alive
Read-only property, copy of :attr:`Request.keep_alive` by default.
Can be switched to ``False`` by :meth:`force_close` call.
.. method:: force_close
Disable :attr:`keep_alive` for connection. There are no ways to
enable it back.
.. attribute:: compression
Read-only :class:`bool` property, ``True`` if compression is enabled.
``False`` by default.
.. versionadded:: 0.14
.. seealso:: :meth:`enable_compression`
.. method:: enable_compression(force=None)
Enable compression.
When *force* is unset compression encoding is selected based on
the request's *Accept-Encoding* header.
*Accept-Encoding* is not checked if *force* is set to a
:class:`ContentCoding`.
.. versionadded:: 0.14
.. seealso:: :attr:`compression`
.. attribute:: chunked
Read-only property, indicates if chunked encoding is on.
Can be enabled by :meth:`enable_chunked_encoding` call.
.. versionadded:: 0.14
.. seealso:: :attr:`enable_chunked_encoding`
.. method:: enable_chunked_encoding
Enables :attr:`chunked` encoding for response. There are no ways to
disable it back. With enabled :attr:`chunked` encoding each `write()`
operation encoded in separate chunk.
.. versionadded:: 0.14
.. seealso:: :attr:`chunked`
.. attribute:: headers
:class:`~aiohttp.multidict.CIMultiDict` instance
for *outgoing* *HTTP headers*.
.. attribute:: cookies
An instance of :class:`http.cookies.SimpleCookie` for *outgoing* cookies.
.. warning::
Direct setting up *Set-Cookie* header may be overwritten by
explicit calls to cookie manipulation.
We are encourage using of :attr:`cookies` and
:meth:`set_cookie`, :meth:`del_cookie` for cookie
manipulations.
.. method:: set_cookie(name, value, *, path='/', expires=None, \
domain=None, max_age=None, \
secure=None, httponly=None, version=None)
Convenient way for setting :attr:`cookies`, allows to specify
some additional properties like *max_age* in a single call.
:param str name: cookie name
:param str value: cookie value (will be converted to
:class:`str` if value has another type).
:param expires: expiration date (optional)
:param str domain: cookie domain (optional)
:param int max_age: defines the lifetime of the cookie, in
seconds. The delta-seconds value is a
decimal non- negative integer. After
delta-seconds seconds elapse, the client
should discard the cookie. A value of zero
means the cookie should be discarded
immediately. (optional)
:param str path: specifies the subset of URLs to
which this cookie applies. (optional, ``'/'`` by default)
:param bool secure: attribute (with no value) directs
the user agent to use only (unspecified)
secure means to contact the origin server
whenever it sends back this cookie.
The user agent (possibly under the user's
control) may determine what level of
security it considers appropriate for
"secure" cookies. The *secure* should be
considered security advice from the server
to the user agent, indicating that it is in
the session's interest to protect the cookie
contents. (optional)
:param bool httponly: ``True`` if the cookie HTTP only (optional)
:param int version: a decimal integer, identifies to which
version of the state management
specification the cookie
conforms. (Optional, *version=1* by default)
.. versionchanged:: 0.14.3
Default value for *path* changed from ``None`` to ``'/'``.
.. method:: del_cookie(name, *, path='/', domain=None)
Deletes cookie.
:param str name: cookie name
:param str domain: optional cookie domain
:param str path: optional cookie path, ``'/'`` by default
.. versionchanged:: 0.14.3
Default value for *path* changed from ``None`` to ``'/'``.
.. attribute:: content_length
*Content-Length* for outgoing response.
.. attribute:: content_type
*Content* part of *Content-Type* for outgoing response.
.. attribute:: charset
*Charset* aka *encoding* part of *Content-Type* for outgoing response.
The value converted to lower-case on attribute assigning.
.. attribute:: last_modified
*Last-Modified* header for outgoing response.
This property accepts raw :class:`str` values,
:class:`datetime.datetime` objects, Unix timestamps specified
as an :class:`int` or a :class:`float` object, and the
value ``None`` to unset the header.
.. method:: start(request)
:param aiohttp.web.Request request: HTTP request object, that the
response answers.
Send *HTTP header*. You should not change any header data after
calling this method.
.. method:: write(data)
Send byte-ish data as the part of *response BODY*.
:meth:`start` must be called before.
Raises :exc:`TypeError` if data is not :class:`bytes`,
:class:`bytearray` or :class:`memoryview` instance.
Raises :exc:`RuntimeError` if :meth:`start` has not been called.
Raises :exc:`RuntimeError` if :meth:`write_eof` has been called.
.. coroutinemethod:: drain()
A :ref:`coroutine<coroutine>` to let the write buffer of the
underlying transport a chance to be flushed.
The intended use is to write::
resp.write(data)
yield from resp.drain()
Yielding from :meth:`drain` gives the opportunity for the loop
to schedule the write operation and flush the buffer. It should
especially be used when a possibly large amount of data is
written to the transport, and the coroutine does not yield-from
between calls to :meth:`write`.
.. versionadded:: 0.14
.. coroutinemethod:: write_eof()
A :ref:`coroutine<coroutine>` *may* be called as a mark of the
*HTTP response* processing finish.
*Internal machinery* will call this method at the end of
the request processing if needed.
After :meth:`write_eof` call any manipulations with the *response*
object are forbidden.
Response
^^^^^^^^
.. class:: Response(*, status=200, headers=None, content_type=None, \
body=None, text=None)
The most usable response class, inherited from :class:`StreamResponse`.
Accepts *body* argument for setting the *HTTP response BODY*.
The actual :attr:`body` sending happens in overridden
:meth:`~StreamResponse.write_eof`.
:param bytes body: response's BODY
:param int status: HTTP status code, 200 OK by default.
:param collections.abc.Mapping headers: HTTP headers that should be added to
response's ones.
:param str text: response's BODY
:param str content_type: response's content type
.. attribute:: body
Read-write attribute for storing response's content aka BODY,
:class:`bytes`.
Setting :attr:`body` also recalculates
:attr:`~StreamResponse.content_length` value.
Resetting :attr:`body` (assigning ``None``) sets
:attr:`~StreamResponse.content_length` to ``None`` too, dropping
*Content-Length* HTTP header.
.. attribute:: text
Read-write attribute for storing response's content, represented as str,
:class:`str`.
Setting :attr:`str` also recalculates
:attr:`~StreamResponse.content_length` value and
:attr:`~StreamResponse.body` value
Resetting :attr:`body` (assigning ``None``) sets
:attr:`~StreamResponse.content_length` to ``None`` too, dropping
*Content-Length* HTTP header.
WebSocketResponse
^^^^^^^^^^^^^^^^^
.. class:: WebSocketResponse(*, timeout=10.0, autoclose=True, \
autoping=True, protocols=())
Class for handling server-side websockets.
After starting (by :meth:`start` call) the response you
cannot use :meth:`~StreamResponse.write` method but should to
communicate with websocket client by :meth:`send_str`,
:meth:`receive` and others.
.. method:: start(request)
Starts websocket. After the call you can use websocket methods.
:param aiohttp.web.Request request: HTTP request object, that the
response answers.
:raises HTTPException: if websocket handshake has failed.
.. method:: can_start(request)
Performs checks for *request* data to figure out if websocket
can be started on the request.
If :meth:`can_start` call is success then :meth:`start` will success too.
:param aiohttp.web.Request request: HTTP request object, that the
response answers.
:return: ``(ok, protocol)`` pair, *ok* is ``True`` on success,
*protocol* is websocket subprotocol which is passed by
client and accepted by server (one of *protocols*
sequence from :class:`WebSocketResponse` ctor). *protocol* may be
``None`` if client and server subprotocols are nit overlapping.
.. note:: The method never raises exception.
.. attribute:: closed
Read-only property, ``True`` if connection has been closed or in process
of closing.
:const:`~aiohttp.websocket.MSG_CLOSE` message has been received from peer.
.. attribute:: close_code
Read-only property, close code from peer. It is set to ``None`` on
opened connection.
.. attribute:: protocol
Websocket *subprotocol* chosen after :meth:`start` call.
May be ``None`` if server and client protocols are
not overlapping.
.. method:: exception()
Returns last occurred exception or None.
.. method:: ping(message=b'')
Send :const:`~aiohttp.websocket.MSG_PING` to peer.
:param message: optional payload of *ping* message,
:class:`str` (converted to *UTF-8* encoded bytes)
or :class:`bytes`.
:raise RuntimeError: if connections is not started or closing.
.. method:: pong(message=b'')
Send *unsolicited* :const:`~aiohttp.websocket.MSG_PONG` to peer.
:param message: optional payload of *pong* message,
:class:`str` (converted to *UTF-8* encoded bytes)
or :class:`bytes`.
:raise RuntimeError: if connections is not started or closing.
.. method:: send_str(data)
Send *data* to peer as :const:`~aiohttp.websocket.MSG_TEXT` message.
:param str data: data to send.
:raise RuntimeError: if connection is not started or closing
:raise TypeError: if data is not :class:`str`
.. method:: send_bytes(data)
Send *data* to peer as :const:`~aiohttp.websocket.MSG_BINARY` message.
:param data: data to send.
:raise RuntimeError: if connection is not started or closing
:raise TypeError: if data is not :class:`bytes`,
:class:`bytearray` or :class:`memoryview`.
.. coroutinemethod:: close(*, code=1000, message=b'')
A :ref:`coroutine<coroutine>` that initiates closing
handshake by sending :const:`~aiohttp.websocket.MSG_CLOSE` message.
:param int code: closing code
:param message: optional payload of *pong* message,
:class:`str` (converted to *UTF-8* encoded bytes)
or :class:`bytes`.
:raise RuntimeError: if connection is not started or closing
.. coroutinemethod:: receive()
A :ref:`coroutine<coroutine>` that waits upcoming *data*
message from peer and returns it.
The coroutine implicitly handles
:const:`~aiohttp.websocket.MSG_PING`,
:const:`~aiohttp.websocket.MSG_PONG` and
:const:`~aiohttp.websocket.MSG_CLOSE` without returning the
message.
It process *ping-pong game* and performs *closing handshake* internally.
After websocket closing raises
:exc:`~aiohttp.errors.WSClientDisconnectedError` with
connection closing data.
:return: :class:`~aiohttp.websocket.Message`
:raise RuntimeError: if connection is not started
:raise: :exc:`~aiohttp.errors.WSClientDisconnectedError` on closing.
.. coroutinemethod:: receive_str()
A :ref:`coroutine<coroutine>` that calls :meth:`receive_mgs` but
also asserts the message type is
:const:`~aiohttp.websocket.MSG_TEXT`.
:return str: peer's message content.
:raise TypeError: if message is :const:`~aiohttp.websocket.MSG_BINARY`.
.. coroutinemethod:: receive_bytes()
A :ref:`coroutine<coroutine>` that calls :meth:`receive_mgs` but
also asserts the message type is
:const:`~aiohttp.websocket.MSG_BINARY`.
:return bytes: peer's message content.
:raise TypeError: if message is :const:`~aiohttp.websocket.MSG_TEXT`.
.. versionadded:: 0.14
.. seealso:: :ref:`WebSockets handling<aiohttp-web-websockets>`
.. _aiohttp-web-app-and-router:
Application and Router
----------------------
Application
^^^^^^^^^^^
Application is a synonym for web-server.
To get fully working example, you have to make *application*, register
supported urls in *router* and create a *server socket* with
:class:`aiohttp.RequestHandlerFactory` as a *protocol
factory*. *RequestHandlerFactory* could be constructed with
:meth:`make_handler`.
*Application* contains a *router* instance and a list of callbacks that
will be called during application finishing.
*Application* is a :class:`dict`, so you can use it as registry for
arbitrary properties for later access from
:ref:`handler<aiohttp-web-handler>` via :attr:`Request.app` property::
app = Application(loop=loop)
app['database'] = yield from aiopg.create_engine(**db_config)
@asyncio.coroutine
def handler(request):
with (yield from request.app['database']) as conn:
conn.execute("DELETE * FROM table")
.. class:: Application(*, loop=None, router=None, logger=<default>, \
middlewares=(), **kwargs)
The class inherits :class:`dict`.
: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 router: :class:`aiohttp.abc.AbstractRouter` instance, the system
creates :class:`UrlDispatcher` by default if
*router* is ``None``.
:param logger: :class:`logging.Logger` instance for storing application logs.
By default the value is ``logging.getLogger("aiohttp.web")``
:param middlewares: :class:`list` of middleware factories, see
:ref:`aiohttp-web-middlewares` for details.
.. versionadded:: 0.13
.. attribute:: router
Read-only property that returns *router instance*.
.. attribute:: logger
:class:`logging.Logger` instance for storing application logs.
.. attribute:: loop
:ref:`event loop<asyncio-event-loop>` used for processing HTTP requests.
.. method:: make_handler(**kwargs)
Creates HTTP protocol factory for handling requests.
:param kwargs: additional parameters for :class:`RequestHandlerFactory`
constructor.
You should pass result of the method as *protocol_factory* to
:meth:`~BaseEventLoop.create_server`, e.g.::
loop = asyncio.get_event_loop()
app = Application(loop=loop)
# setup route table
# app.router.add_route(...)
yield from loop.create_server(app.make_handler(),
'0.0.0.0', 8080)
.. coroutinemethod:: finish()
A :ref:`coroutine<coroutine>` that should be called after
server stopping.
This method executes functions registered by
:meth:`register_on_finish` in LIFO order.
If callback raises an exception, the error will be stored by
:meth:`~asyncio.BaseEventLoop.call_exception_handler` with keys:
*message*, *exception*, *application*.
.. method:: register_on_finish(self, func, *args, **kwargs):
Register *func* as a function to be executed at termination.
Any optional arguments that are to be passed to *func* must be
passed as arguments to :meth:`register_on_finish`. It is possible to
register the same function and arguments more than once.
During the call of :meth:`finish` all functions registered are called in
last in, first out order.
*func* may be either regular function or :ref:`coroutine<coroutine>`,
:meth:`finish` will un-yield (`yield from`) the later.
.. note::
Application object has :attr:`route` attribute but has no
``add_route()`` method. The reason is: we want to support
different route implementations (even maybe not url-matching
based but traversal ones).
For sake of that fact we have very trivial ABC for
:class:`AbstractRouter`: it should have only
:meth:`AbstractRouter.resolve` coroutine.
No methods for adding routes or route reversing (getting URL by
route name). All those are router implementation details (but,
sure, you need to deal with that methods after choosing the
router for your application).
RequestHandlerFactory
^^^^^^^^^^^^^^^^^^^^^
RequestHandlerFactory is responsible for creating HTTP protocol objects that
can handle http connections.
.. attribute:: connections
List of all currently opened connections.
.. method:: finish_connections(timeout)
A :ref:`coroutine<coroutine>` that should be called to close all opened
connections.
Router
^^^^^^
For dispatching URLs to :ref:`handlers<aiohttp-web-handler>`
:mod:`aiohttp.web` uses *routers*.
Router is any object that implements :class:`AbstractRouter` interface.
:mod:`aiohttp.web` provides an implementation called :class:`UrlDispatcher`.
:class:`Application` uses :class:`UrlDispatcher` as :meth:`router` by default.
.. class:: UrlDispatcher()
Straightforward url-matching router, implements
:class:`collections.abc.Mapping` for access to *named routes*.
Before running :class:`Application` you should fill *route
table* first by calling :meth:`add_route` and :meth:`add_static`.
:ref:`Handler<aiohttp-web-handler>` lookup is performed by iterating on
added *routes* in FIFO order. The first matching *route* will be used
to call corresponding *handler*.
If on route creation you specify *name* parameter the result is
*named route*.
*Named route* can be retrieved by ``app.router[name]`` call, checked for
existence by ``name in app.router`` etc.
.. seealso:: :ref:`Route classes <aiohttp-web-route>`
.. method:: add_route(method, path, handler, *, \
name=None, expect_handler=None)
Append :ref:`handler<aiohttp-web-handler>` to the end of route table.
*path* may be either *constant* string like ``'/a/b/c'`` or
*variable rule* like ``'/a/{var}'`` (see
:ref:`handling variable pathes<aiohttp-web-variable-handler>`)
Pay attention please: *handler* is converted to coroutine internally when
it is a regular function.
:param str method: HTTP method for route. Should be one of
``'GET'``, ``'POST'``, ``'PUT'``,
``'DELETE'``, ``'PATCH'``, ``'HEAD'``,
``'OPTIONS'`` or ``'*'`` for any method.
The parameter is case-insensitive, e.g. you
can push ``'get'`` as well as ``'GET'``.
:param str path: route path. Should be started with slash (``'/'``).
:param callable handler: route handler.
:param str name: optional route name.
:param coroutine expect_handler: optional *expect* header handler.
:returns: new :class:`PlainRoute` or :class:`DynamicRoute` instance.
.. method:: add_static(prefix, path, *, name=None, expect_handler=None, \
chunk_size=256*1024, response_factory=None)
Adds router for returning static files.
Useful for handling static content like images, javascript and css files.
.. warning::
Use :meth:`add_static` for development only. In production,
static content should be processed by web servers like *nginx*
or *apache*.
:param str prefix: URL path prefix for handled static files
:param str path: path to the folder in file system that contains
handled static files.
:param str name: optional route name.
:param coroutine expect_handler: optional *expect* header handler.
:param int chunk_size: size of single chunk for file
downloading, 64Kb by default.
Increasing *chunk_size* parameter to,
say, 1Mb may increase file downloading
speed but consumes more memory.
.. versionadded:: 0.16
:param callable response_factory: factory to use to generate a new
response, defaults to
:class:`StreamResponse` and should
expose a compatible API.
.. versionadded:: 0.17
:returns: new :class:`StaticRoute` instance.
.. coroutinemethod:: resolve(requst)
A :ref:`coroutine<coroutine>` that returns
:class:`AbstractMatchInfo` for *request*.
The method never raises exception, but returns
:class:`AbstractMatchInfo` instance with:
1. :attr:`~AbstractMatchInfo.route` assigned to
:class:`SystemRoute` instance
2. :attr:`~AbstractMatchInfo.handler` which raises
:exc:`HTTPNotFound` or :exc:`HTTPMethodNotAllowed` on handler's
execution if there is no registered route for *request*.
*Middlewares* can process that exceptions to render
pretty-looking error page for example.
Used by internal machinery, end user unlikely need to call the method.
.. note:: The method uses :attr:`Request.raw_path` for pattern
matching against registered routes.
.. versionchanged:: 0.14
The method don't raise :exc:`HTTPNotFound` and
:exc:`HTTPMethodNotAllowed` anymore.
.. _aiohttp-web-route:
Route
^^^^^
Default router :class:`UrlDispatcher` operates with *routes*.
User should not instantiate route classes by hand but can give *named
route instance* by ``router[name]`` if he have added route by
:meth:`UrlDispatcher.add_route` or :meth:`UrlDispatcher.add_static`
calls with non-empty *name* parameter.
The main usage of *named routes* is constructing URL by route name for
passing it into *template engine* for example::
url = app.router['route_name'].url(query={'a': 1, 'b': 2})
There are three concrete route classes:* :class:`DynamicRoute` for
urls with :ref:`variable pathes<aiohttp-web-variable-handler>` spec.
* :class:`PlainRoute` for urls without :ref:`variable
pathes<aiohttp-web-variable-handler>`
* :class:`DynamicRoute` for urls with :ref:`variable
pathes<aiohttp-web-variable-handler>` spec.
* :class:`StaticRoute` for static file handlers.
.. class:: Route
Base class for routes served by :class:`UrlDispatcher`.
.. attribute:: method
HTTP method handled by the route, e.g. *GET*, *POST* etc.
.. attribute:: handler
:ref:`handler<aiohttp-web-handler>` that processes the route.
.. attribute:: name
Name of the route.
.. method:: match(path)
Abstract method, accepts *URL path* and returns :class:`dict` with
parsed *path parts* for :class:`UrlMappingMatchInfo` or ``None`` if
the route cannot handle given *path*.
The method exists for internal usage, end user unlikely need to call it.
.. method:: url(*, query=None, **kwargs)
Abstract method for constructing url handled by the route.
*query* is a mapping or list of *(name, value)* pairs for
specifying *query* part of url (parameter is processed by
:func:`~urllib.parse.urlencode`).
Other available parameters depends on concrete route class and
described in descendant classes.
.. class:: PlainRoute
The route class for handling plain *URL path*, e.g. ``"/a/b/c"``
.. method:: url(*, parts, query=None)
Construct url, doesn't accepts extra parameters::
>>> route.url(query={'d': 1, 'e': 2})
'/a/b/c/?d=1&e=2'``
.. class:: DynamicRoute
The route class for handling :ref:`variable
path<aiohttp-web-variable-handler>`, e.g. ``"/a/{name1}/{name2}"``
.. method:: url(*, parts, query=None)
Construct url with given *dynamic parts*::
>>> route.url(parts={'name1': 'b', 'name2': 'c'},
query={'d': 1, 'e': 2})
'/a/b/c/?d=1&e=2'
.. class:: StaticRoute
The route class for handling static files, created by
:meth:`UrlDispatcher.add_static` call.
.. method:: url(*, filename, query=None)
Construct url for given *filename*::
>>> route.url(filename='img/logo.png', query={'param': 1})
'/path/to/static/img/logo.png?param=1'
.. class:: SystemRoute
The route class for internal purposes.
Now it has used for handling *404: Not Found* and *405: Method Not Allowed*.
.. method:: url()
Always raises :exc:`RuntimeError`, :class:`SystemRoute` should not
be used in url construction expressions.
MatchInfo
^^^^^^^^^
After route matching web application calls found handler if any.
Matching result can be accessible from handler as
:attr:`Request.match_info` attribute.
In general the result may be any object derived from
:class:`AbstractMatchInfo` (:class:`UrlMappingMatchInfo` for default
:class:`UrlDispatcher` router).
.. class:: UrlMappingMatchInfo
Inherited from :class:`dict` and :class:`AbstractMatchInfo`. Dict
items are given from :meth:`Route.match` call return value.
.. attribute:: route
:class:`Route` instance for url matching.
Utilities
---------
.. class:: FileField
A :func:`~collections.namedtuple` that is returned as multidict value
by :meth:`Request.POST` if field is uploaded file.
.. attribute:: name
Field name
.. attribute:: filename
File name as specified by uploading (client) side.
.. attribute:: file
An :class:`io.IOBase` instance with content of uploaded file.
.. attribute:: content_type
*MIME type* of uploaded file, ``'text/plain'`` by default.
.. seealso:: :ref:`aiohttp-web-file-upload`
Constants
---------
.. class:: ContentCoding
An :class:`enum.Enum` class of available Content Codings.
.. attribute:: deflate
.. attribute:: gzip
.. attribute:: identity
.. disqus::
|