HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/env/lib/python3.10/site-packages/tornado/__pycache__/web.cpython-310.pyc
o

we�/�@sdZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Zddlm
Z
ddlmZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZddl m!Z!m"Z"ddlm#Z#ddlm$Z$dd	l%m&Z&dd
lm'Z'ddlm(Z(ddlm)Z)dd
l*m+Z+m,Z,m-Z-ddlm.Z.ddl/m0Z0m1Z1ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:ddl;m<Z<m=Z=m>Z>e9Z?ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNddlmOZOddl@Z@e@jP�rddl@mQZQeCeRe=eSejTejfZUeCeVeReAeSeVfeAeSeRffZWdZX	dZY	dZZ	dZ[	Gdd�d�Z\e\�Z]Gdd�de^�Z_eLde_d�Z`deKe`deKe`fdd �ZadeKe_debfd!d"�Zcd#eHd$eDeEdfdeHd$eDeEdffd%d&�Zdd#eHd$eDeEdfdeHd$eDeEdffd'd(�ZeGd)d*�d*e8�ZfGd+d,�d,e6�ZgGd-d.�d.e'jh�ZiGd/d0�d0ej�ZkGd1d2�d2ej�ZlGd3d4�d4ek�ZmGd5d6�d6e_�ZnGd7d8�d8e_�ZoGd9d:�d:e_�ZpGd;d<�d<e_�ZqGd=d>�d>e^�ZrGd?d@�d@er�Zsd#eHd$eDeEdfdeHd$eDeEdffdAdB�ZtGdCdD�dDe^�ZuGdEdF�dFeu�ZvGdGdH�dHeu�ZwGdIdJ�dJeu�ZxGdKdL�dLe^�Zy			dndMeWdNeVdOeCeVeRfdPeDeSdQeDeHgezfdReDeSdeRfdSdT�Z{e�|dU�Z}dOeRdeSfdVdW�Z~	X		dodMeWdNeVdOeCdeVeRfdYezdQeDeHgezfdZeDeSdeDeRfd[d\�ZdMeCeVeRfdNeVdOeRdYezdQeHgezfdeDeRfd]d^�Z�dOeRdeFeSeReReReRffd_d`�Z�dMeWdNeVdOeRdYezdQeHgezfdeDeRfdadb�Z�dOeCeVeRfdeDeSfdcdd�Z�dMeCeVeRfdeeCeVeRfdeRfdfdg�Z�dMeCeVeRfdheRdeRfdidj�Z�dkeVdebfdldm�Z�dS)paP``tornado.web`` provides a simple web framework with asynchronous
features that allow it to scale to large numbers of open connections,
making it ideal for `long polling
<http://en.wikipedia.org/wiki/Push_technology#Long_polling>`_.

Here is a simple "Hello, world" example app:

.. testcode::

    import asyncio
    import tornado

    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.write("Hello, world")

    async def main():
        application = tornado.web.Application([
            (r"/", MainHandler),
        ])
        application.listen(8888)
        await asyncio.Event().wait()

    if __name__ == "__main__":
        asyncio.run(main())

.. testoutput::
   :hide:


See the :doc:`guide` for additional information.

Thread-safety notes
-------------------

In general, methods on `RequestHandler` and elsewhere in Tornado are
not thread-safe. In particular, methods such as
`~RequestHandler.write()`, `~RequestHandler.finish()`, and
`~RequestHandler.flush()` must only be called from the main thread. If
you use multiple threads it is important to use `.IOLoop.add_callback`
to transfer control back to the main thread before finishing the
request, or to limit your use of other threads to
`.IOLoop.run_in_executor` and ensure that your callbacks running in
the executor do not refer to Tornado objects.

�N)�isclass)�BytesIO)�	urlencode)�Future�"future_set_result_unless_cancelled)�escape)�gen)�
HTTPServer)�httputil)�iostream)�locale)�
access_log�app_log�gen_log)�template)�utf8�_unicode)�
AnyMatches�DefaultHostMatches�HostMatches�ReversibleRouter�Rule�ReversibleRuleRouter�URLSpec�	_RuleList)�
ObjectDict�unicode_type�_websocket_mask)�Dict�Any�Union�Optional�	Awaitable�Tuple�List�Callable�Iterable�	Generator�Type�TypeVar�cast�overload)�
TracebackType)�Set��c@seZdZdS)�_ArgDefaultMarkerN)�__name__�
__module__�__qualname__�r4r4�D/home/arjun/projects/env/lib/python3.10/site-packages/tornado/web.pyr0�sr0cs�eZdZdZdZiZe��Ze	�
d�ZdZdZ
dZdZdddejd	ed
df�fdd�Zd�d
d�ZeZ	ed
eeeffdd��Zded	ed
dfdd�ZeZeZeZeZeZeZ eZ!d
e"e#dfdd�Z$d�dd�Z%d�dd�Z&d�dd�Z'd�dd�Z(d�de)de"ed
dfd d!�Z*d
e)fd"d#�Z+d$ed%e,d
dfd&d'�Z-d$ed%e,d
dfd(d)�Z.d$ed
dfd*d+�Z/e	�
d,�Z0d%e,d
efd-d.�Z1e2d�d$ed0ed1e3d
efd2d3��Z4e2e5d/fd$ed0e6d1e3d
efd4d3��Z4e2	/d�d$ed0dd1e3d
e"efd5d3��Z4e5d/fd$ed0e7dee6fd1e3d
e"efd6d3�Z4d�d$ed1e3d
e8efd7d8�Z9e5d/fd$ed0e7dee6fd1e3d
e"efd9d:�Z:d�d$ed1e3d
e8efd;d<�Z;e5d/fd$ed0e7dee6fd1e3d
e"efd=d>�Z<d�d$ed1e3d
e8efd?d@�Z=	/d�d$ed0e7dee6fdAeee8e>fd1e3d
e"ef
dBdC�Z?	/d�d$edAeee8e>fd1e3d
e8efdDdE�Z@d�d%e>d$e"ed
efdFdG�ZAed
eeeBjCjDffdHdI��ZCd�d$ed0e"ed
e"efdJdK�ZE			L	d�dddddM�d$ed%e7ee>fdNe"edOe"e7eFeGeHjHfdPedQe"eFdRe"e)dSe3dTe3dUe"ed	ed
dfdVdW�ZId$ed	ed
dfdXdY�ZJd	ed
dfdZd[�ZK	\	d�d$ed%e7ee>fdQe"eFd]e"e)d	ed
dfd^d_�ZLeLZM	d�d$ed%e7ee>fd]e"e)d
e>fd`da�ZN		b	d�d$ed%e"edceFdde"e)d
e"e>f
dedf�ZOeOZP	d�d$ed%e"ed
e"e)fdgdh�ZQeQZR	d�diedje3dke"e)d
dfdldm�ZSdne7ee>eTfd
dfdodp�ZUdqed	ed
drfdsdt�ZVdueWed
efdvdw�ZXdxeWe>d
e>fdydz�ZYd{eWed
efd|d}�ZZd~eWe>d
e>fdd��Z[dqed	ed
e>fd�d��Z\d
eeeffd�d��Z]d�ed
e^j_fd�d��Z`d�d�e3d
drfd�d��Zad�dne"e7ee>eTfd
drfd�d��Zbd
ecjdfd�d��Zed�d�d��Zfd�de)d	ed
dfd�d��Zgde)d	ed
dfd�d��Zhed
eijjjkfd�d���Zjejjld%eijjjkd
dfd�d���Zjd
e"eijjjkfd�d��Zmd�d0ed
eijjjkfd�d��Zned
efd�d���Zoeojld%ed
dfd�d���Zod
efd�d��Zpd
efd�d��Zqd
e"efd�d��Zred
e>fd�d���Zsd
eGe"e)e>eFffd�d��Ztd�ed
eGe"e)e"e>e"eFffd�d��Zud�d�d��Zvd
efd�d��Zw	d�dPed�e"e3d	ed
efd�d��Zxd�d$ed�ed
dfd�d��Zyd$eded
efd�d��Zzd
e"efd�d��Z{d�d�d��Z|d
e3fd�d��Z}d�e8d�de>d	e>d
dfd�dĄZ~dne>d
e"e#dfd�dƄZd�d�dȄZ�d
efd�dʄZ�d�e�d
dfd�d̈́Z�d�d�d%e"e�d�e"e�d
dfd�d҄Z�d$ed�e�d�d
e�d�effd�dׄZ�d�e�d�efd
e�d�effd�dڄZ�d�d�d܄Z��Z�S)��RequestHandleraFBase class for HTTP request handlers.

    Subclasses must define at least one of the methods defined in the
    "Entry points" section below.

    Applications should not construct `RequestHandler` objects
    directly and subclasses should not override ``__init__`` (override
    `~RequestHandler.initialize` instead).

    )�GET�HEAD�POST�DELETE�PATCH�PUT�OPTIONSz[\x00-\x08\x0e-\x1f]FN�application�Application�request�kwargs�returncs�t���|�_|�_d�_d�_d�_d�_t�fdd�|j	�
�D���_t�|j
��jd<�jd�jd<����jjdusCJ��jj��j��jdi|��dS)NFTc3s"�|]\}}|��|�fVqdS�N)�
_ui_method)�.0�n�m��selfr4r5�	<genexpr>�s�
�z*RequestHandler.__init__.<locals>.<genexpr>�_tt_modules�modulesr4)�super�__init__r>r@�_headers_written�	_finished�_auto_finish�_prepared_futurer�
ui_methods�items�ui�_UIModuleNamespace�
ui_modules�clear�
connection�set_close_callback�on_connection_close�
initialize)rIr>r@rA��	__class__rHr5rN�s$

��zRequestHandler.__init__cC�dSrCr4rHr4r4r5�_initialize��zRequestHandler._initializecC�|jjS)z@An alias for `self.application.settings <Application.settings>`.)r>�settingsrHr4r4r5rcszRequestHandler.settings�argscOstd��)N�)�	HTTPError�rIrdrAr4r4r5�_unimplemented_methodsz$RequestHandler._unimplemented_methodcC�dS)a�Called at the beginning of a request before  `get`/`post`/etc.

        Override this method to perform common initialization regardless
        of the request method.

        Asynchronous support: Use ``async def`` or decorate this method with
        `.gen.coroutine` to make it asynchronous.
        If this method returns an  ``Awaitable`` execution will not proceed
        until the ``Awaitable`` is done.

        .. versionadded:: 3.1
           Asynchronous support.
        Nr4rHr4r4r5�prepareszRequestHandler.preparecCri)aCalled after the end of a request.

        Override this method to perform cleanup, logging, etc.
        This method is a counterpart to `prepare`.  ``on_finish`` may
        not produce any output, as it is called after the response
        has been sent to the client.
        Nr4rHr4r4r5�	on_finish'�zRequestHandler.on_finishcCs@t|j�r|jj��s|jj�t���|jj��dSdSdS)aFCalled in async handlers if the client closed the connection.

        Override this to clean up resources associated with
        long-lived connections.  Note that this method is called only if
        the connection was closed during asynchronous processing; if you
        need to do cleanup after every request override `on_finish`
        instead.

        Proxies may keep a connection open for a time (perhaps
        indefinitely) after the client has gone away, so this method
        may not be called promptly after the end user closes their
        connection.
        N)	�_has_stream_request_bodyr^r@�_body_future�done�
set_exceptionr�StreamClosedError�	exceptionrHr4r4r5r[1s
�z"RequestHandler.on_connection_closecCsHt�dtjdt�t���d��|_|��g|_d|_	tj
d|_dS)z1Resets all headers and content for this response.zTornadoServer/%sztext/html; charset=UTF-8)�Server�Content-Type�Date��N)r
�HTTPHeaders�tornado�version�format_timestamp�time�_headers�set_default_headers�
_write_buffer�_status_code�	responses�_reasonrHr4r4r5rXDs��zRequestHandler.clearcCri)aBOverride this to set HTTP headers at the beginning of the request.

        For example, this is the place to set a custom ``Server`` header.
        Note that setting such headers in the normal flow of request
        processing may not do what you want, since headers may be reset
        during error handling.
        Nr4rHr4r4r5r}Rrlz"RequestHandler.set_default_headers�status_code�reasoncCs2||_|durt�|�|_dStj�|d�|_dS)a�Sets the status code for our response.

        :arg int status_code: Response status code.
        :arg str reason: Human-readable reason phrase describing the status
            code. If ``None``, it will be filled in from
            `http.client.responses` or "Unknown".

        .. versionchanged:: 5.0

           No longer validates that the response code is in
           `http.client.responses`.
        N�Unknown)rr�
native_strr�r
r��get)rIr�r�r4r4r5�
set_status\s
zRequestHandler.set_statuscCs|jS)z)Returns the status code for our response.)rrHr4r4r5�
get_statuso�zRequestHandler.get_status�name�valuecCs|�|�|j|<dS)z�Sets the given response header name and value.

        All header values are converted to strings (`datetime` objects
        are formatted according to the HTTP specification for the
        ``Date`` header).

        N)�_convert_header_valuer|�rIr�r�r4r4r5�
set_headersszRequestHandler.set_headercCs|j�||�|��dS)z�Adds the given response header and value.

        Unlike `set_header`, `add_header` may be called multiple times
        to return multiple values for the same header.
        N)r|�addr�r�r4r4r5�
add_header}szRequestHandler.add_headercCs||jvr|j|=dSdS)z�Clears an outgoing header, undoing a previous `set_header` call.

        Note that this method does not apply to multi-valued headers
        set by `add_header`.
        N)r|)rIr�r4r4r5�clear_header�s
�zRequestHandler.clear_headerz[\x00-\x1f]cCsvt|t�r|}n&t|t�r|�d�}nt|tj�rt|�St|tj�r(t�|�St	d|��t
j�|�r9t
d|��|S)N�latin1zUnsupported header value %rzUnsafe header value %r)�
isinstance�str�bytes�decode�numbers�Integral�datetimer
rz�	TypeErrorr6�_INVALID_HEADER_CHAR_RE�search�
ValueError)rIr��retvalr4r4r5r��s



z$RequestHandler._convert_header_valueT�default�stripcCr_rCr4�rIr�r�r�r4r4r5�get_argument��zRequestHandler.get_argumentcCr_rCr4r�r4r4r5r���cCr_rCr4r�r4r4r5r��r�cC�|�|||jj|�S)arReturns the value of the argument with the given name.

        If default is not provided, the argument is considered to be
        required, and we raise a `MissingArgumentError` if it is missing.

        If the argument appears in the request more than once, we return the
        last value.

        This method searches both the query and body arguments.
        )�
_get_argumentr@�	argumentsr�r4r4r5r��scCs t|t�sJ�|�||jj|�S)z�Returns a list of the arguments with the given name.

        If the argument is not present, returns an empty list.

        This method searches both the query and body arguments.
        )r��bool�_get_argumentsr@r��rIr�r�r4r4r5�
get_arguments�szRequestHandler.get_argumentscCr�)ajReturns the value of the argument with the given name
        from the request body.

        If default is not provided, the argument is considered to be
        required, and we raise a `MissingArgumentError` if it is missing.

        If the argument appears in the url more than once, we return the
        last value.

        .. versionadded:: 3.2
        )r�r@�body_argumentsr�r4r4r5�get_body_argument��z RequestHandler.get_body_argumentcC�|�||jj|�S)z�Returns a list of the body arguments with the given name.

        If the argument is not present, returns an empty list.

        .. versionadded:: 3.2
        )r�r@r�r�r4r4r5�get_body_arguments��z!RequestHandler.get_body_argumentscCr�)arReturns the value of the argument with the given name
        from the request query string.

        If default is not provided, the argument is considered to be
        required, and we raise a `MissingArgumentError` if it is missing.

        If the argument appears in the url more than once, we return the
        last value.

        .. versionadded:: 3.2
        )r�r@�query_argumentsr�r4r4r5�get_query_argument�r�z!RequestHandler.get_query_argumentcCr�)z�Returns a list of the query arguments with the given name.

        If the argument is not present, returns an empty list.

        .. versionadded:: 3.2
        )r�r@r�r�r4r4r5�get_query_argumentsr�z"RequestHandler.get_query_arguments�sourcecCs2|j|||d�}|st|t�rt|��|S|dS)N)r����)r�r�r0�MissingArgumentError)rIr�r�r�r�rdr4r4r5r�s
zRequestHandler._get_argumentcCsVg}|�|g�D] }|j||d�}t|t�rtj�d|�}|r#|��}|�|�q|S)N�r�� )	r��decode_argumentr�rr6�_remove_control_chars_regex�subr��append)rIr�r�r��values�v�sr4r4r5r�s
zRequestHandler._get_argumentsc
Cs8zt|�WStytdd|pd|dd�f��w)aDecodes an argument from the request.

        The argument has been percent-decoded and is now a byte string.
        By default, this method decodes the argument as utf-8 and returns
        a unicode string, but this may be overridden in subclasses.

        This method is used as a filter for both `get_argument()` and for
        values extracted from the url and passed to `get()`/`post()`/etc.

        The name of the argument is provided if known, but may be None
        (e.g. for unnamed groups in the url regex).
        �zInvalid unicode in %s: %r�urlN�()r�UnicodeDecodeErrorrf)rIr�r�r4r4r5r�.s
��zRequestHandler.decode_argumentcCrb)zRAn alias for
        `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.)r@�cookiesrHr4r4r5r�BszRequestHandler.cookiescCs*|jjdur||jjvr|jj|jS|S)a-Returns the value of the request cookie with the given name.

        If the named cookie is not present, returns ``default``.

        This method only returns cookies that were present in the request.
        It does not see the outgoing cookies set by `set_cookie` in this
        handler.
        N)r@r�r�)rIr�r�r4r4r5�
get_cookieHs	zRequestHandler.get_cookie�/)�max_age�httponly�secure�samesite�domain�expires�path�expires_daysr�r�r�r�cKs8t�|�}t�|�}t�d||�rtd||f��t|d�s%tj��|_	||j	vr.|j	|=||j	|<|j	|}|r>||d<|durR|sRt
j
�t
jj
�t
j|d�}|r[t�|�|d<|ra||d<|rit|�|d	<|rod
|d<|	rud
|d<|
r{|
|d
<|r�|��D]\}
}|||
<q�t�dt|����d�t�dSdS)a}Sets an outgoing cookie name/value with the given options.

        Newly-set cookies are not immediately visible via `get_cookie`;
        they are not present until the next request.

        Most arguments are passed directly to `http.cookies.Morsel` directly.
        See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
        for more information.

        ``expires`` may be a numeric timestamp as returned by `time.time`,
        a time tuple as returned by `time.gmtime`, or a
        `datetime.datetime` object. ``expires_days`` is provided as a convenience
        to set an expiration time in days from today (if both are set, ``expires``
        is used).

        .. deprecated:: 6.3
           Keyword arguments are currently accepted case-insensitively.
           In Tornado 7.0 this will be changed to only accept lowercase
           arguments.
        z[\x00-\x20]zInvalid cookie %r: %r�_new_cookier�N��daysr�r�zmax-ageTr�r�r�z$Deprecated arguments to set_cookie: z (should be lowercase))rr��rer�r��hasattr�httpr��SimpleCookier�r��now�timezone�utc�	timedeltar
rzr�rT�warnings�warn�set�keys�DeprecationWarning)rIr�r�r�r�r�r�r�r�r�r�rA�morsel�kr�r4r4r5�
set_cookieUsJ
%

�


�
��zRequestHandler.set_cookiecKsZdD]}||vrtd|�d���qtj�tjj�tjdd�}|j|fd|d�|��dS)	a�Deletes the cookie with the given name.

        This method accepts the same arguments as `set_cookie`, except for
        ``expires`` and ``max_age``. Clearing a cookie requires the same
        ``domain`` and ``path`` arguments as when it was set. In some cases the
        ``samesite`` and ``secure`` arguments are also required to match. Other
        arguments are ignored.

        Similar to `set_cookie`, the effect of this method will not be
        seen until the following request.

        .. versionchanged:: 6.3

           Now accepts all keyword arguments that ``set_cookie`` does.
           The ``samesite`` and ``secure`` flags have recently become
           required for clearing ``samesite="none"`` cookies.
        )r�r�z3clear_cookie() got an unexpected keyword argument '�'imr��)r�r�N)r�r�r�r�r�r�r�)rIr�rA�excluded_argr�r4r4r5�clear_cookie�s
���zRequestHandler.clear_cookiecKs$|jjD]}|j|fi|��qdS)acAttempt to delete all the cookies the user sent with this request.

        See `clear_cookie` for more information on keyword arguments. Due to
        limitations of the cookie protocol, it is impossible to determine on the
        server side which values are necessary for the ``domain``, ``path``,
        ``samesite``, or ``secure`` arguments, this method can only be
        successful if you consistently use the same values for these arguments
        when setting cookies.

        Similar to `set_cookie`, the effect of this method will not be seen
        until the following request.

        .. versionchanged:: 3.2

           Added the ``path`` and ``domain`` parameters.

        .. versionchanged:: 6.3

           Now accepts all keyword arguments that ``set_cookie`` does.

        .. deprecated:: 6.3

           The increasingly complex rules governing cookies have made it
           impossible for a ``clear_all_cookies`` method to work reliably
           since all we know about cookies are their names. Applications
           should generally use ``clear_cookie`` one at a time instead.
        N)r@r�r�)rIrAr�r4r4r5�clear_all_cookies�s�z RequestHandler.clear_all_cookies�rycKs(|j||j|||d�fd|i|��dS)a�Signs and timestamps a cookie so it cannot be forged.

        You must specify the ``cookie_secret`` setting in your Application
        to use this method. It should be a long, random sequence of bytes
        to be used as the HMAC secret for the signature.

        To read a cookie set with this method, use `get_signed_cookie()`.

        Note that the ``expires_days`` parameter sets the lifetime of the
        cookie in the browser, but is independent of the ``max_age_days``
        parameter to `get_signed_cookie`.
        A value of None limits the lifetime to the current browser session.

        Secure cookies may contain arbitrary byte values, not just unicode
        strings (unlike regular cookies)

        Similar to `set_cookie`, the effect of this method will not be
        seen until the following request.

        .. versionchanged:: 3.2.1

           Added the ``version`` argument.  Introduced cookie version 2
           and made it the default.

        .. versionchanged:: 6.3

           Renamed from ``set_secure_cookie`` to ``set_signed_cookie`` to
           avoid confusion with other uses of "secure" in cookie attributes
           and prefixes. The old name remains as an alias.
        )ryr�N)r��create_signed_value)rIr�r�r�ryrAr4r4r5�set_signed_cookie�s&��
�z RequestHandler.set_signed_cookiecCs^|�dd�|jjd}d}t|t�r&|jj�d�dur td��|jjd}t|||||d�S)a�Signs and timestamps a string so it cannot be forged.

        Normally used via set_signed_cookie, but provided as a separate
        method for non-cookie uses.  To decode a value not stored
        as a cookie use the optional value argument to get_signed_cookie.

        .. versionchanged:: 3.2.1

           Added the ``version`` argument.  Introduced cookie version 2
           and made it the default.
        �
cookie_secret�secure cookiesN�key_versionz5key_version setting must be used for secret_key dicts)ryr�)�require_settingr>rcr��dictr��	Exceptionr�)rIr�r�ry�secretr�r4r4r5r�s

�z"RequestHandler.create_signed_value��max_age_days�min_versioncCs8|�dd�|dur|�|�}t|jjd||||d�S)aReturns the given signed cookie if it validates, or None.

        The decoded cookie value is returned as a byte string (unlike
        `get_cookie`).

        Similar to `get_cookie`, this method only returns cookies that
        were present in the request. It does not see outgoing cookies set by
        `set_signed_cookie` in this handler.

        .. versionchanged:: 3.2.1

           Added the ``min_version`` argument.  Introduced cookie version 2;
           both versions 1 and 2 are accepted by default.

         .. versionchanged:: 6.3

           Renamed from ``get_secure_cookie`` to ``get_signed_cookie`` to
           avoid confusion with other uses of "secure" in cookie attributes
           and prefixes. The old name remains as an alias.

        r�r�N)r�r�)r�r��decode_signed_valuer>rc)rIr�r�r�r�r4r4r5�get_signed_cookie,s

�z RequestHandler.get_signed_cookiecCs2|�dd�|dur|�|�}|durdSt|�S)a~Returns the signing key version of the secure cookie.

        The version is returned as int.

        .. versionchanged:: 6.3

           Renamed from ``get_secure_cookie_key_version`` to
           ``set_signed_cookie_key_version`` to avoid confusion with other
           uses of "secure" in cookie attributes and prefixes. The old name
           remains as an alias.

        r�r�N)r�r��get_signature_key_versionr�r4r4r5�get_signed_cookie_key_versionUs
z,RequestHandler.get_signed_cookie_key_versionr��	permanent�statuscCsp|jrtd��|dur|rdnd}nt|t�r#d|kr"dks%J�J�|�|�|�dt|��|��dS)a:Sends a redirect to the given (optionally relative) URL.

        If the ``status`` argument is specified, that value is used as the
        HTTP status code; otherwise either 301 (permanent) or 302
        (temporary) is chosen based on the ``permanent`` argument.
        The default is 302 (temporary).
        z/Cannot redirect after headers have been writtenNi-i.i,i��Location)rOr�r��intr�r�r�finish)rIr�r�r�r4r4r5�redirectms
&
zRequestHandler.redirect�chunkcCst|jrtd��t|tttf�sd}t|t�r|d7}t|��t|t�r.t�	|�}|�
dd�t|�}|j�
|�dS)a�Writes the given chunk to the output buffer.

        To write the output to the network, use the `flush()` method below.

        If the given chunk is a dictionary, we write it as JSON and set
        the Content-Type of the response to be ``application/json``.
        (if you want to send JSON as a different ``Content-Type``, call
        ``set_header`` *after* calling ``write()``).

        Note that lists are not converted to JSON because of a potential
        cross-site security vulnerability.  All JSON output should be
        wrapped in a dictionary.  More details at
        http://haacked.com/archive/2009/06/25/json-hijacking.aspx/ and
        https://github.com/facebook/tornado/issues/1009
        zCannot write() after finish()z5write() only accepts bytes, unicode, and dict objectsz|. Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.writertzapplication/json; charset=UTF-8N)rP�RuntimeErrorr�r�rr��listr�r�json_encoder�rr~r�)rIr��messager4r4r5�write�s
�

zRequestHandler.write�
template_namezFuture[None]cKs~|jrtd��|j|fi|��}g}g}g}g}g}g}	t|di���D]j}
|
��}|r3|�t|��|
��}|rMt	|t
tf�rH|�t|��n|�
|�|
��}|rZ|�t|��|
��}|rtt	|t
tf�ro|�t|��n|�
|�|
��}
|
r�|�t|
��|
��}|r�|	�t|��q$|r�|�|�}|�d�}|d|�t|�d||d�}|r�|�|�}|�d�}|d|�|d||d�}|r�|�|�}|�d�}|d|�t|�d||d�}|�r|�|�}|�d�}|d|�|d||d�}|�r|�d�}|d|�d�|�d||d�}|	�r:|�d�}|d|�d�|	�d||d�}|�|�S)a�Renders the template with the given arguments as the response.

        ``render()`` calls ``finish()``, so no other output methods can be called
        after it.

        Returns a `.Future` with the same semantics as the one returned by `finish`.
        Awaiting this `.Future` is optional.

        .. versionchanged:: 5.1

           Now returns a `.Future` instead of ``None``.
        zCannot render() after finish()�_active_moduless</body>N�
s</head>�)rPr�
render_string�getattrr��embedded_javascriptr�r�javascript_filesr�rr�r�extend�embedded_css�	css_files�	html_head�	html_body�render_linked_js�rindex�render_embed_js�render_linked_css�index�render_embed_css�joinr�)rIrrA�html�js_embed�js_files�	css_embedr�
html_heads�html_bodies�module�
embed_part�	file_part�	head_part�	body_part�js�sloc�js_bytes�css�hloc�	css_bytesr4r4r5�render�sp


�

$

 

$

 
&
&
zRequestHandler.renderrcC�Vg}t�}|D]}t|�s|�|�}||vr |�|�|�|�qd�dd�|D��S)z�Default method used to render the final js links for the
        rendered webpage.

        Override this method in a sub-classed controller to change the output.
        r�cs�"�|]}dt�|�dVqdS)z
<script src="z"" type="text/javascript"></script>N�r�xhtml_escape�rE�pr4r4r5rJ�s����
�z2RequestHandler.render_linked_js.<locals>.<genexpr>�r��is_absolute�
static_urlr�r�r)rIr�paths�unique_pathsr�r4r4r5r�s


�
�zRequestHandler.render_linked_jsrcC�dd�|�dS)z�Default method used to render the final embedded js for the
        rendered webpage.

        Override this method in a sub-classed controller to change the output.
        s,<script type="text/javascript">
//<![CDATA[
rs
//]]>
</script>�r)rIrr4r4r5rs���zRequestHandler.render_embed_jsrcCr+)z�Default method used to render the final css links for the
        rendered webpage.

        Override this method in a sub-classed controller to change the output.
        r�csr,)z<link href="z$" type="text/css" rel="stylesheet"/>Nr-r/r4r4r5rJs
��
�z3RequestHandler.render_linked_css.<locals>.<genexpr>r1)rIrr4r5r�r4r4r5rs


�
�z RequestHandler.render_linked_cssrcCr6)z�Default method used to render the final embedded css for the
        rendered webpage.

        Override this method in a sub-classed controller to change the output.
        s<style type="text/css">
rs	
</style>r7)rIrr4r4r5r%szRequestHandler.render_embed_cssc	Ks�|��}|s8t�d�}|jj}|jj|kr(|jdur(|j}|jj|kr(|jdus|jjdus0J�tj�|jj�}t	j
�|t	jvrL|�|�}|t	j|<nt	j|}Wd�n1s[wY|�
|�}|��}|�|�|jdi|��S)z�Generate the given template with the given arguments.

        We return the generated byte string (in utf8). To generate and
        write a template as a response, use render() above.
        rNr4)�get_template_path�sys�	_getframe�f_code�co_filename�f_back�osr��dirnamer6�_template_loader_lock�_template_loaders�create_template_loader�load�get_template_namespace�update�generate)	rIrrA�
template_path�frame�web_file�loader�t�	namespacer4r4r5r	-s(
�


��

zRequestHandler.render_stringcCs>t||j|j|j|jj|jj|j|j|jd�	}|�	|j
�|S)aBReturns a dictionary to be used as the default template namespace.

        May be overridden by subclasses to add or modify values.

        The results of this method will be combined with additional
        defaults in the `tornado.template` module and keyword arguments
        to `render` or `render_string`.
        )	�handlerr@�current_userr�_�pgettextr3�xsrf_form_html�reverse_url)r�r@rNr�	translaterPr3rQrRrErU)rIrLr4r4r5rDGs	�z%RequestHandler.get_template_namespacerGcCsV|jj}d|vr|dSi}d|vr|d|d<d|vr"|d|d<tj|fi|��S)a]Returns a new template loader for the given path.

        May be overridden by subclasses.  By default returns a
        directory-based loader on the given path, using the
        ``autoescape`` and ``template_whitespace`` application
        settings.  If a ``template_loader`` application setting is
        supplied, uses that instead.
        �template_loader�
autoescape�template_whitespace�
whitespace)r>rcr�Loader)rIrGrcrAr4r4r5rB^s	z%RequestHandler.create_template_loader�include_footerscCs|jjdusJ�d�|j�}g|_|jscd|_|jD]}|dus"J�|�|j|j||�\|_|_}q|jj	dkr:d}t
|d�rP|j��D]}|�
d|�d��qDt�d|j|j�}|jj�||j|�S|jD]}|�||�}qf|jj	dkr||jj�|�St�}|�d�|S)z�Flushes the current output buffer to the network.

        .. versionchanged:: 4.0
           Now returns a `.Future` if no callback is given.

        .. versionchanged:: 6.0

           The ``callback`` argument was removed.
        NrTr8r�z
Set-Cookier�)r@rYrr~rO�_transforms�transform_first_chunkrr|�methodr�r�r�r��OutputStringr
�ResponseStartLiner��
write_headers�transform_chunkrr�
set_result)rIrYr��	transform�cookie�
start_line�futurer4r4r5�flushss<

��
�

zRequestHandler.flushcCs*|jrtd��|dur|�|�|jsi|jdkr3|jjdvr3d|jvr3|��|�	�r3g|_
|�d�|jdvsEd|jkrCdkrTnn|j
rOJd	|j��|��nd
|jvrit
dd�|j
D��}|�d
|�|jjdusqJ�|jj�d�|jd
d�}|jj��|��d
|_|��|��|S)aDFinishes this response, ending the HTTP request.

        Passing a ``chunk`` to ``finish()`` is equivalent to passing that
        chunk to ``write()`` and then calling ``finish()`` with no arguments.

        Returns a `.Future` which may optionally be awaited to track the sending
        of the response to the client. This `.Future` resolves when all the response
        data has been sent, and raises an error if the connection is closed before all
        data can be sent.

        .. versionchanged:: 5.1

           Now returns a `.Future` instead of ``None``.
        zfinish() called twiceNrv�r7r8�Etag�0)��ri�dzCannot send body with %s�Content-Lengthcss�|]}t|�VqdSrC)�len)rE�partr4r4r5rJ�s�z(RequestHandler.finish.<locals>.<genexpr>T)rY)rPrrrOrr@r\r|�set_etag_header�check_etag_headerr~r��_clear_representation_headers�sumr�rYrZrfr��_logrk�
_break_cycles)rIr��content_lengthrer4r4r5r��s:



$�

zRequestHandler.finishcCsd|_|jj��S)aNTake control of the underlying stream.

        Returns the underlying `.IOStream` object and stops all
        further HTTP processing. Intended for implementing protocols
        like websockets that tunnel over an HTTP handshake.

        This method is only supported when HTTP/1.1 is used.

        .. versionadded:: 5.1
        T)rPr@rY�detachrHr4r4r5rv�szRequestHandler.detachcCs
d|_dSrC)rUrHr4r4r5rt��
zRequestHandler._break_cycles��cKs�|jr&t�d�|js$z|��WdSty#tjddd�YdSwdS|��|�d�}d|vrD|dd}t|t	�rD|j
rD|j
}|j||d	�z|j|fi|��Wntyft
jd
dd�Ynw|jsp|��dSdS)a�Sends the given HTTP error code to the browser.

        If `flush()` has already been called, it is not possible to send
        an error, so this method will simply terminate the response.
        If output has been written but not yet flushed, it will be discarded
        and replaced with the error page.

        Override `write_error()` to customize the error page that is returned.
        Additional keyword arguments are passed through to `write_error`.
        z0Cannot send error response after headers writtenz Failed to flush partial responseT��exc_infoNr�rzr.)r�z!Uncaught exception in write_error)rOr�errorrPr�r�rXr�r�rfr�r��write_errorr)rIr�rAr�rrr4r4r5�
send_error�s4

��
��zRequestHandler.send_errorcKsd|j�d�r%d|vr%|�dd�tj|d�D]}|�|�q|��dS|�d||jd��dS)a�Override to implement custom error pages.

        ``write_error`` may call `write`, `render`, `set_header`, etc
        to produce output as usual.

        If this error was caused by an uncaught exception (including
        HTTPError), an ``exc_info`` triple will be available as
        ``kwargs["exc_info"]``.  Note that this exception may not be
        the "current" exception for purposes of methods like
        ``sys.exc_info()`` or ``traceback.format_exc``.
        �serve_tracebackrzrt�
text/plainzS<html><title>%(code)d: %(message)s</title><body>%(code)d: %(message)s</body></html>)�coderN)rcr�r��	traceback�format_exceptionrr�r�)rIr�rA�liner4r4r5r|s
��zRequestHandler.write_errorcCs@t|d�s|��}|dur||_|jS|��|_|jsJ�|jS)a^The locale for the current session.

        Determined by either `get_user_locale`, which you can override to
        set the locale based on, e.g., a user preference stored in a
        database, or `get_browser_locale`, which uses the ``Accept-Language``
        header.

        .. versionchanged: 4.1
           Added a property setter.
        �_localeN)r��get_user_localer��get_browser_locale)rI�locr4r4r5r1s

�
zRequestHandler.localecC�
||_dSrC)r��rIr�r4r4r5rF�
cCri)aOverride to determine the locale from the authenticated user.

        If None is returned, we fall back to `get_browser_locale()`.

        This method should return a `tornado.locale.Locale` object,
        most likely obtained via a call like ``tornado.locale.get("en")``
        Nr4rHr4r4r5r�JrlzRequestHandler.get_user_locale�en_USc
Cs�d|jjvru|jjd�d�}g}|D]J}|���d�}t|�dkrN|d���d�rNzt|d��dd��}|dkr?t��WnttfyMd	}Ynwd
}|dkr]|�	|d|f�q|ru|j
dd�d
d�dd�|D�}tj|�St�|�S)z�Determines the user's locale from ``Accept-Language`` header.

        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        zAccept-Language�,�;r.zq=r/Nrgg�?cSs|dS)Nr.r4)�pairr4r4r5�<lambda>j�z3RequestHandler.get_browser_locale.<locals>.<lambda>T)�key�reversecSsg|]}|d�qS)rr4)rEr�r4r4r5�
<listcomp>ksz5RequestHandler.get_browser_locale.<locals>.<listcomp>)
r@�headers�splitr�rm�
startswith�floatr�r�r��sortrr�)rIr��	languages�locales�language�parts�score�codesr4r4r5r�Ts.���

z!RequestHandler.get_browser_localecCst|d�s
|��|_|jS)a�The authenticated user for this request.

        This is set in one of two ways:

        * A subclass may override `get_current_user()`, which will be called
          automatically the first time ``self.current_user`` is accessed.
          `get_current_user()` will only be called once per request,
          and is cached for future access::

              def get_current_user(self):
                  user_cookie = self.get_signed_cookie("user")
                  if user_cookie:
                      return json.loads(user_cookie)
                  return None

        * It may be set as a normal variable, typically from an overridden
          `prepare()`::

              @gen.coroutine
              def prepare(self):
                  user_id_cookie = self.get_signed_cookie("user_id")
                  if user_id_cookie:
                      self.current_user = yield load_user(user_id_cookie)

        Note that `prepare()` may be a coroutine while `get_current_user()`
        may not, so the latter form is necessary if loading the user requires
        asynchronous operations.

        The user object may be any type of the application's choosing.
        �
_current_user)r��get_current_userr�rHr4r4r5rNos
 
zRequestHandler.current_usercCr�rC)r�r�r4r4r5rN�r�cCri)zrOverride to determine the current user from, e.g., a cookie.

        This method may not be a coroutine.
        Nr4rHr4r4r5r��szRequestHandler.get_current_usercCs|�dd�|jjdS)z�Override to customize the login URL based on the request.

        By default, we use the ``login_url`` application setting.
        �	login_urlz@tornado.web.authenticated)r�r>rcrHr4r4r5�
get_login_url�szRequestHandler.get_login_urlcCs|jj�d�S)z�Override to customize template path for each handler.

        By default, we use the ``template_path`` application setting.
        Return None to load templates relative to the calling file.
        rG)r>rcr�rHr4r4r5r8�sz RequestHandler.get_template_pathc	Cs�t|d�sn|��\}}}|j�dd�}|j�di�}|dkr%t�|�|_n(|dkrHt�d�}d�	dt�|�t�t
||��ttt
|���g�|_ntd	|��|d
urn|jr\d|vr\d|d<|j�d
d�}|j||jfi|��|jS)a�The XSRF-prevention token for the current user/session.

        To prevent cross-site request forgery, we set an '_xsrf' cookie
        and include the same '_xsrf' value as an argument with all POST
        requests. If the two do not match, we reject the form submission
        as a potential forgery.

        See http://en.wikipedia.org/wiki/Cross-site_request_forgery

        This property is of type `bytes`, but it contains only ASCII
        characters. If a character string is required, there is no
        need to base64-encode it; just decode the byte string as
        UTF-8.

        .. versionchanged:: 3.2.2
           The xsrf token will now be have a random mask applied in every
           request, which makes it safe to include the token in pages
           that are compressed.  See http://breachattack.com for more
           information on the issue fixed by this change.  Old (version 1)
           cookies will be converted to version 2 when this method is called
           unless the ``xsrf_cookie_version`` `Application` setting is
           set to 1.

        .. versionchanged:: 4.3
           The ``xsrf_cookie_kwargs`` `Application` setting may be
           used to supply additional cookie options (which will be
           passed directly to `set_cookie`). For example,
           ``xsrf_cookie_kwargs=dict(httponly=True, secure=True)``
           will set the ``secure`` and ``httponly`` flags on the
           ``_xsrf`` cookie.
        �_xsrf_token�xsrf_cookie_versionr/�xsrf_cookie_kwargsr.��|�2zunknown xsrf cookie version %dNr�r��xsrf_cookie_name�_xsrf)r��_get_raw_xsrf_tokenrcr��binascii�b2a_hexr�r>�urandomrrrr�r�r�rNr�)rIry�token�	timestamp�output_version�
cookie_kwargs�mask�cookie_namer4r4r5�
xsrf_token�s,
!
��
	zRequestHandler.xsrf_tokencCs�t|d�sB|j�dd�}|�|�}|r|�|�\}}}nd\}}}|dur0d}t�d�}t��}|dus6J�|dus<J�|||f|_|jS)a�Read or generate the xsrf token in its raw form.

        The raw_xsrf_token is a tuple containing:

        * version: the version of the cookie from which this token was read,
          or None if we generated a new token in this request.
        * token: the raw token data; random (non-ascii) bytes.
        * timestamp: the time this token was generated (will not be accurate
          for version 1 cookies)
        �_raw_xsrf_tokenr�r��NNNN�)	r�rcr�r��_decode_xsrf_tokenr>r�r{r�)rIr�rcryr�r�r4r4r5r��s



z"RequestHandler._get_raw_xsrf_tokenrcc	Cs�zdt�t|��}|r=t|�d��}|dkr9|�d�\}}}}t�t|��}t|t�t|���}	t|�}
||	|
fWSt	d��d}z	t�t|��}	Wntj
tfyXt|�}	Ynwtt���}
||	|
fWSt	yut
jddd�YdSw)	z_Convert a cookie string into a the tuple form returned by
        _get_raw_xsrf_token.
        r.r/�|zUnknown xsrf cookie versionz(Uncaught exception in _decode_xsrf_tokenTryr�)�_signed_value_version_re�matchrr��groupr�r��a2b_hexrr��Errorr�r{r�debug)rIrcrGryrO�mask_str�masked_token�
timestamp_strr�r�r�r4r4r5r�s.��z!RequestHandler._decode_xsrf_tokencCs�|�dd�p|jj�d�p|jj�d�}|stdd��|�|�\}}}|��\}}}|s1tdd��t�t	|�t	|��s@tdd��dS)	a�Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.

        To prevent cross-site request forgery, we set an ``_xsrf``
        cookie and include the same value as a non-cookie
        field with all ``POST`` requests. If the two do not match, we
        reject the form submission as a potential forgery.

        The ``_xsrf`` value may be set as either a form field named ``_xsrf``
        or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
        (the latter is accepted for compatibility with Django).

        See http://en.wikipedia.org/wiki/Cross-site_request_forgery

        .. versionchanged:: 3.2.2
           Added support for cookie version 2.  Both versions 1 and 2 are
           supported.
        r�NzX-XsrftokenzX-Csrftoken�z"'_xsrf' argument missing from POSTz#'_xsrf' argument has invalid formatz(XSRF cookie does not match POST argument)
r�r@r�r�rfr�r��hmac�compare_digestr)rIr�rO�expected_tokenr4r4r5�check_xsrf_cookie's��


�z RequestHandler.check_xsrf_cookiecCsdt�|j�dS)a�An HTML ``<input/>`` element to be included with all POST forms.

        It defines the ``_xsrf`` input value, which we check on all POST
        requests to prevent cross-site request forgery. If you have set
        the ``xsrf_cookies`` application setting, you must include this
        HTML within all of your HTML forms.

        In a template, this method should be called with ``{% module
        xsrf_form_html() %}``

        See `check_xsrf_cookie()` above for more information.
        z)<input type="hidden" name="_xsrf" value="z"/>)rr.r�rHr4r4r5rQMs
���zRequestHandler.xsrf_form_html�include_hostcKsf|�dd�|j�dt�j}|durt|dd�}|r%|jjd|jj}nd}|||j|fi|��S)	a�Returns a static URL for the given relative static file path.

        This method requires you set the ``static_path`` setting in your
        application (which specifies the root directory of your static
        files).

        This method returns a versioned url (by default appending
        ``?v=<signature>``), which allows the static files to be
        cached indefinitely.  This can be disabled by passing
        ``include_version=False`` (in the default implementation;
        other static file implementations are not required to support
        this, but they may support other options).

        By default this method returns URLs relative to the current
        host, but if ``include_host`` is true the URL returned will be
        absolute.  If this handler has an ``include_host`` attribute,
        that value will be used as the default for all `static_url`
        calls that do not pass ``include_host`` as a keyword argument.

        �static_pathr3�static_handler_classNr�Fz://r�)	r�rcr��StaticFileHandler�make_static_urlr
r@�protocol�host)rIr�r�rA�get_url�baser4r4r5r3`s��zRequestHandler.static_url�this feature�featurecCs"|jj�|�std||f��dS)z<Raises an exception if the given app setting is not defined.z>You must define the '%s' setting in your application to use %sN)r>rcr�r�)rIr�r�r4r4r5r��s���zRequestHandler.require_settingcGs|jj|g|�R�S)z$Alias for `Application.reverse_url`.)r>rR)rIr�rdr4r4r5rR��zRequestHandler.reverse_urlcCs*t��}|jD]}|�|�qd|��S)aComputes the etag header to be used for this request.

        By default uses a hash of the content written so far.

        May be overridden to provide custom etag implementations,
        or may return None to disable tornado's default etag support.
        �"%s")�hashlib�sha1r~rE�	hexdigest)rI�hasherrnr4r4r5�compute_etag�s
zRequestHandler.compute_etagcCs$|��}|dur|�d|�dSdS)z�Sets the response's Etag header using ``self.compute_etag()``.

        Note: no header will be set if ``compute_etag()`` returns ``None``.

        This method is called automatically when the request is finished.
        Nrh)r�r�)rI�etagr4r4r5ro�s�zRequestHandler.set_etag_headercCs�t|j�dd��}t�dt|jj�dd���}|r|sdSd}|ddkr)d}|Sd	td
tfdd�}|D]}||�||�krCd}|Sq4|S)
a�Checks the ``Etag`` header against requests's ``If-None-Match``.

        Returns ``True`` if the request's Etag matches and a 304 should be
        returned. For example::

            self.set_etag_header()
            if self.check_etag_header():
                self.set_status(304)
                return

        This method is called automatically when the request is finished,
        but may be called earlier for applications that override
        `compute_etag` and want to do an early check for ``If-None-Match``
        before completing the request.  The ``Etag`` header should be set
        (perhaps with `set_etag_header`) before calling this method.
        rhr�s\*|(?:W/)?"[^"]*"�
If-None-MatchFr�*T�xrBcSs|�d�r|dd�S|S)NsW/r/�r�)r�r4r4r5�val�sz-RequestHandler.check_etag_header.<locals>.val)rr|r�r��findallr@r�r�)rI�
computed_etag�etagsr�r�r�r4r4r5rp�s$�
��z RequestHandler.check_etag_header�
transforms�OutputTransformc�s��|�_z��jj�jvrtd���fdd�|D��_t�fdd�|��D���_�jjdvr9�j	j
�d�r9�����
�}|durF|IdH}�jdurQt�jd��jrWWdSt�j�rrz	�jjIdHWntjyqYWdSwt��jj���}|�ji�j��}|dur�|IdH}�jr��js����WdSWdSWdSty�}zEzz��|�Wnty�tjd	d
d�YnwWd}nd}w�jdurވj��s�j�d�WYd}~dSWYd}~dSWYd}~dSd}~ww)z7Executes this request with the given output transforms.recsg|]}��|��qSr4�r�)rE�argrHr4r5r���z+RequestHandler._execute.<locals>.<listcomp>c3s&�|]\}}|�j||d�fVqdS)r�Nr�)rEr�r�rHr4r5rJ�s�
�z*RequestHandler._execute.<locals>.<genexpr>)r7r8r=�xsrf_cookiesNzException in exception handlerTry) rZr@r\�SUPPORTED_METHODSrf�	path_argsr�rT�path_kwargsr>rcr�r�rjrRrrPrmr^rnrrqr
�lowerrQr�r��_handle_request_exceptionrr{rora)rIr�rdrA�resultr\�er4rHr5�_execute�s\�
��


�
������zRequestHandler._executecC�t��)z�Implement this method to handle streamed request data.

        Requires the `.stream_request_body` decorator.

        May be a coroutine for flow control.
        ��NotImplementedError)rIr�r4r4r5�
data_receivedszRequestHandler.data_receivedcCs|j�|�dS)z�Logs the current request.

        Sort of deprecated since this functionality was moved to the
        Application, but left in place for the benefit of existing apps
        that have overridden this method.
        N)r>�log_requestrHr4r4r5rsszRequestHandler._logcCsd|jj|jj|jjfS)Nz
%s %s (%s))r@r\�uri�	remote_iprHr4r4r5�_request_summary!s
�zRequestHandler._request_summaryr�cCs�t|t�r|js|j|j�dSz	|jt���Wnty)t	j
ddd�Ynw|jr/dSt|t�r@|j|j
t��d�dS|jdt��d�dS)NzError in exception loggerTryrx)r��FinishrPr�rd�
log_exceptionr9rzr�rr{rfr}r�)rIr�r4r4r5r�(s
�
z(RequestHandler._handle_request_exception�typzOptional[Type[BaseException]]�tbcCsnt|t�r&|jr$d|j}|j|��gt|j�}tj|g|�R�dSdSt	j
d|��|j|||fd�dS)aKOverride to customize logging of uncaught exceptions.

        By default logs instances of `HTTPError` as warnings without
        stack traces (on the ``tornado.general`` logger), and all
        other exceptions as errors with stack traces (on the
        ``tornado.application`` logger).

        .. versionadded:: 3.1
        z%d %s: zUncaught exception %s
%rryN)r�rf�log_messager�r�rrdr�warningrr{r@)rIr�r�r��formatrdr4r4r5r�>s

�
�zRequestHandler.log_exceptionr�UIModule.csdtf���fdd�}|S)NrBcsBt�d�si�_��jvr����j�<�j�j|i|��}|S)Nr)r�rr*)rdrA�rendered�rr�rIr4r5r*[s

z)RequestHandler._ui_module.<locals>.render)r�)rIr�rr*r4rr5�
_ui_moduleZszRequestHandler._ui_moduler\cs��fdd�S)Ncs��g|�Ri|��SrCr4)rdrA�r\rIr4r5r�fr�z+RequestHandler._ui_method.<locals>.<lambda>r4)rIr\r4rr5rDe�zRequestHandler._ui_methodcCs gd�}|D]}|�|�qdS)N)�Content-EncodingzContent-Languagert)r�)rIr��hr4r4r5rqhs�z,RequestHandler._clear_representation_headers�rBNrC�T)NNr�N)r�N)Nr�N)FN)F)rx)r�)r�)�r1r2r3�__doc__r�rA�	threading�Lockr@r��compiler��_stream_request_bodyrZr�r�r
�HTTPServerRequestrrNr`r\�propertyrr�rcrh�headr��post�delete�patch�put�optionsr!r"rjrkr[rXr}r�r�r��_HeaderTypesr�r�r�r�r�r+r�r��_ARG_DEFAULTr0r r$r�r�r�r�r�r�r�r�r�r�r��Morselr�r�r#r�r�r�r�r��set_secure_cookier�r��get_secure_cookier��get_secure_cookie_key_versionr�r�rr*r&rrrrr	rDr�
BaseLoaderrBrfr�r�IOStreamrvrtr}r|rxr�Locale�setterr�r�rNr�r�r8r�r�r�r�rQr3r�rRr�rorpr�r�rsr��
BaseExceptionr�r,r�r(r%rrDrq�
__classcell__r4r4r]r5r6�s`
����
 







	��������������
�����
�����
������
�����
� �
��
�����
���
��
�S#��
����
�-��
��
������
�'���
�����
� K"29
&
#9�
�
$&����
�&

(���
�=
		���
�""r6�_RequestHandlerType)�bound�clsrBcCst|t�s
td|��d|_|S)aApply to `RequestHandler` subclasses to enable streaming body support.

    This decorator implies the following changes:

    * `.HTTPServerRequest.body` is undefined, and body arguments will not
      be included in `RequestHandler.get_argument`.
    * `RequestHandler.prepare` is called when the request headers have been
      read instead of after the entire body has been read.
    * The subclass must define a method ``data_received(self, data):``, which
      will be called zero or more times as data is available.  Note that
      if the request has an empty body, ``data_received`` may not be called.
    * ``prepare`` and ``data_received`` may return Futures (such as via
      ``@gen.coroutine``, in which case the next method will not be called
      until those futures have completed.
    * The regular HTTP method (``post``, ``put``, etc) will be called after
      the entire body has been read.

    See the `file receiver demo <https://github.com/tornadoweb/tornado/tree/stable/demos/file_upload/>`_
    for example usage.
    �+expected subclass of RequestHandler, got %rT��
issubclassr6r�r�r&r4r4r5�stream_request_bodyvs

r+cCst|t�s
td|��|jS)Nr'r(r*r4r4r5rm�s

rmr\.c�,t���dtdttdf�fdd��}|S)a#Use this decorator to remove trailing slashes from the request path.

    For example, a request to ``/foo/`` would redirect to ``/foo`` with this
    decorator. Your request handler mapping should use a regular expression
    like ``r'/foo/*'`` in conjunction with using the decorator.
    rIrBNcsv|jj�d�r0|jjdvr,|jj�d�}|r+|jjr"|d|jj7}|j|dd�dSntd���|g|�Ri|��S�Nr�rg�?T�r��)r@r��endswithr\�rstrip�queryr�rf�rIrdrAr��r\r4r5�wrapper�s�zremoveslash.<locals>.wrapper��	functools�wrapsr6r!r"�r\r6r4r5r5�removeslash�s
�
�r;cr,)a&Use this decorator to add a missing trailing slash to the request path.

    For example, a request to ``/foo`` would redirect to ``/foo/`` with this
    decorator. Your request handler mapping should use a regular expression
    like ``r'/foo/?'`` in conjunction with using the decorator.
    rIrBNcsn|jj�d�s,|jjdvr(|jjd}|jjr|d|jj7}|j|dd�dStd���|g|�Ri|��Sr-)r@r�r1r\r3r�rfr4r5r4r5r6�szaddslash.<locals>.wrapperr7r:r4r5r5�addslash�s
�
�
r<c	sreZdZdZ	ddddeeddf�fdd�
Zd	edef�fd
d�Zde	d
e
jde	dee
jf�fdd�Z
�ZS)�_ApplicationRoutera�Routing implementation used internally by `Application`.

    Provides a binding between `Application` and `RequestHandler`.
    This implementation extends `~.routing.ReversibleRuleRouter` in a couple of ways:
        * it allows to use `RequestHandler` subclasses as `~.routing.Rule` target and
        * it allows to use a list/tuple of rules as `~.routing.Rule` target.
        ``process_rule`` implementation will substitute this list with an appropriate
        `_ApplicationRouter` instance.
    Nr>r?�rulesrBcs$t|t�sJ�||_t��|�dSrC)r�r?r>rMrN)rIr>r>r]r4r5rN�sz_ApplicationRouter.__init__�rulecs0t��|�}t|jttf�rt|j|j�|_|SrC)rM�process_ruler��targetr�tupler=r>)rIr?r]r4r5r@�s�z_ApplicationRouter.process_rulerAr@�
target_paramscs>t|�rt|t�r|jj||fi|��St�j||fi|��SrC)rr)r6r>�get_handler_delegaterM�get_target_delegate)rIrAr@rCr]r4r5rE�s��z&_ApplicationRouter.get_target_delegaterC)r1r2r3rr!rrNrr@rr
r�HTTPMessageDelegaterEr#r4r4r]r5r=�s(����
����r=c@s�eZdZdZ			d6deedeedeeedde	ddf
d	d
�Z
	d7eje
jjddd�d
edeedejdedeedede	defdd�Zdededdfdd�Zdedddfdd�Zde	ddfdd�Zd e	ddfd!d"�Zd#ejdeedfd$d%�Zd#ejde	dd&fd'd(�Z			d6d#ejd)eed*eeee	fd+eee d,eeee fdd&fd-d.�Z!d/ed0e	defd1d2�Z"d3eddfd4d5�Z#dS)8r?a�
A collection of request handlers that make up a web application.

    Instances of this class are callable and can be passed directly to
    HTTPServer to serve the application::

        application = web.Application([
            (r"/", MainPageHandler),
        ])
        http_server = httpserver.HTTPServer(application)
        http_server.listen(8080)

    The constructor for this class takes in a list of `~.routing.Rule`
    objects or tuples of values corresponding to the arguments of
    `~.routing.Rule` constructor: ``(matcher, target, [target_kwargs], [name])``,
    the values in square brackets being optional. The default matcher is
    `~.routing.PathMatches`, so ``(regexp, target)`` tuples can also be used
    instead of ``(PathMatches(regexp), target)``.

    A common routing target is a `RequestHandler` subclass, but you can also
    use lists of rules as a target, which create a nested routing configuration::

        application = web.Application([
            (HostMatches("example.com"), [
                (r"/", MainPageHandler),
                (r"/feed", FeedHandler),
            ]),
        ])

    In addition to this you can use nested `~.routing.Router` instances,
    `~.httputil.HTTPMessageDelegate` subclasses and callables as routing targets
    (see `~.routing` module docs for more information).

    When we receive requests, we iterate over the list in order and
    instantiate an instance of the first request class whose regexp
    matches the request path. The request class can be specified as
    either a class object or a (fully-qualified) name.

    A dictionary may be passed as the third element (``target_kwargs``)
    of the tuple, which will be used as keyword arguments to the handler's
    constructor and `~RequestHandler.initialize` method. This pattern
    is used for the `StaticFileHandler` in this example (note that a
    `StaticFileHandler` can be installed automatically with the
    static_path setting described below)::

        application = web.Application([
            (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
        ])

    We support virtual hosts with the `add_handlers` method, which takes in
    a host regular expression as the first argument::

        application.add_handlers(r"www\.myhost\.com", [
            (r"/article/([0-9]+)", ArticleHandler),
        ])

    If there's no match for the current request's host, then ``default_host``
    parameter value is matched against host regular expressions.


    .. warning::

       Applications that do not use TLS may be vulnerable to :ref:`DNS
       rebinding <dnsrebinding>` attacks. This attack is especially
       relevant to applications that only listen on ``127.0.0.1`` or
       other private networks. Appropriate host patterns must be used
       (instead of the default of ``r'.*'``) to prevent this risk. The
       ``default_host`` argument must not be used in applications that
       may be vulnerable to DNS rebinding.

    You can serve static files by sending the ``static_path`` setting
    as a keyword argument. We will serve those files from the
    ``/static/`` URI (this is configurable with the
    ``static_url_prefix`` setting), and we will serve ``/favicon.ico``
    and ``/robots.txt`` from the same directory.  A custom subclass of
    `StaticFileHandler` can be specified with the
    ``static_handler_class`` setting.

    .. versionchanged:: 4.5
       Integration with the new `tornado.routing` module.

    N�handlers�default_hostr�r�rcrBcKs�|durg|_|�d�s|�d�r|j�t�n||_||_||_tttd�|_	i|_
|�|�di��|�|�di��|j�d�rz|jd}t
|pLg�}|�dd�}|�d	t�}|�d
i�}||d<t�|�dd
dfD]}	|�d|	||f�qn|j�d�r�|j�dd�|j�dd�|j�dd�|j�dd�t||�|_t|tt�|j�g�|_|j�d�r�ddlm}
|
��dSdS)N�compress_response�gzip)�linkifyrQ�TemplaterWrSr��static_url_prefix�/static/r��static_handler_argsr�z(.*)z/(favicon\.ico)z/(robots\.txt)rr��
autoreloadT�compiled_template_cacheF�static_hash_cacher~)rP)r�r�r��GZipContentEncodingrHrc�_linkify�_xsrf_form_html�TemplateModulerWrS�_load_ui_modules�_load_ui_methodsrr�r�r�insert�
setdefaultr=�wildcard_routerrr�default_routerrxrP�start)rIrGrHr�rcr�rMr�rO�patternrPr4r4r5rNIsT��
����zApplication.__init__F)�family�backlog�flags�
reuse_port�port�addressr_r`rarbrAc	Ks*t|fi|��}|j||||||d�|S)a�Starts an HTTP server for this application on the given port.

        This is a convenience alias for creating an `.HTTPServer` object and
        calling its listen method.  Keyword arguments not supported by
        `HTTPServer.listen <.TCPServer.listen>` are passed to the `.HTTPServer`
        constructor.  For advanced uses (e.g. multi-process mode), do not use
        this method; create an `.HTTPServer` and call its
        `.TCPServer.bind`/`.TCPServer.start` methods directly.

        Note that after calling this method you still need to call
        ``IOLoop.current().start()`` (or run within ``asyncio.run``) to start
        the server.

        Returns the `.HTTPServer` object.

        .. versionchanged:: 4.3
           Now returns the `.HTTPServer` object.

        .. versionchanged:: 6.2
           Added support for new keyword arguments in `.TCPServer.listen`,
           including ``reuse_port``.
        )rdr_r`rarb)r	�listen)	rIrcrdr_r`rarbrA�serverr4r4r5re�s!�zApplication.listen�host_pattern�
host_handlerscCsTt|�}t|t||��}|jj�d|�|jdur(|j�t	||j
�|fg�dSdS)z�Appends the given handlers to our handler list.

        Host patterns are processed sequentially in the order they were
        added. All matching patterns will be considered.
        r�N)rrr=r\r>rYrHr[�	add_rulesrrg)rIrgrh�host_matcherr?r4r4r5�add_handlers�s
��zApplication.add_handlers�transform_classcCs|j�|�dSrC)r�r�)rIrlr4r4r5�
add_transform��zApplication.add_transform�methodscs�t�tj�r|�t�fdd�t��D���dSt�t�r)�D]}|�|�qdS���D]\}}|�d�sJt	|d�rJ|d�
�|dkrJ||j|<q-dS)Nc3��|]
}|t�|�fVqdSrC�r
�rErF�ror4r5rJ���z/Application._load_ui_methods.<locals>.<genexpr>rO�__call__r)r��types�
ModuleTyperXr��dirrrTr�r�r�rS)rIrorGr��fnr4rsr5rX�s$
���
��zApplication._load_ui_methodsrLc	s�t�tj�r|�t�fdd�t��D���dSt�t�r)�D]}|�|�qdSt�t�s0J����D]\}}zt|t	�rC||j
|<Wq4tyMYq4wdS)Nc3rprCrqrr�rLr4r5rJ�rtz/Application._load_ui_modules.<locals>.<genexpr>)r�rvrwrWr�rxrrTr)rrWr�)rIrLrGr�r&r4rzr5rW�s $
�

���zApplication._load_ui_modulesr@cCs|�|�}|��SrC)�find_handler�execute)rIr@�
dispatcherr4r4r5ru�s
zApplication.__call__�_HandlerDelegatecKsZ|j�|�}|durtd|�S|j�d�r$|�||jd|j�di��S|�|tddi�S)Nr~�default_handler_class�default_handler_argsr�r0)r\r{r*rcr�rD�ErrorHandler)rIr@rA�router4r4r5r{�s
�zApplication.find_handler�target_class�
target_kwargsr�r�cCst||||||�S)aeReturns `~.httputil.HTTPMessageDelegate` that can serve a request
        for application and `RequestHandler` subclass.

        :arg httputil.HTTPServerRequest request: current HTTP request.
        :arg RequestHandler target_class: a `RequestHandler` class.
        :arg dict target_kwargs: keyword arguments for ``target_class`` constructor.
        :arg list path_args: positional arguments for ``target_class`` HTTP method that
            will be executed while handling a request (``get``, ``post`` or any other).
        :arg dict path_kwargs: keyword arguments for ``target_class`` HTTP method.
        )r~)rIr@r�r�r�r�r4r4r5rD�s�z Application.get_handler_delegater�rdcGs,|jj|g|�R�}|dur|Std|��)a3Returns a URL path for handler named ``name``

        The handler must be added to the application as a named `URLSpec`.

        Args will be substituted for capturing groups in the `URLSpec` regex.
        They will be converted to strings if necessary, encoded as utf8,
        and url-escaped.
        Nz%s not found in named urls)r\rR�KeyError)rIr�rd�reversed_urlr4r4r5rR	s	zApplication.reverse_urlrMcCsrd|jvr|jd|�dS|��dkrtj}n
|��dkr"tj}ntj}d|j��}|d|��|��|�dS)a!Writes a completed HTTP request to the logs.

        By default writes to the python root logger.  To change
        this behavior either subclass Application and override this method,
        or pass a function in the application settings dictionary as
        ``log_function``.
        �log_functionNr�rxg@�@z%d %s %.2fms)	rcr�r
�infor�r{r@�request_timer�)rIrM�
log_methodr�r4r4r5r�	s
�zApplication.log_requestr�rC)$r1r2r3rr!rr�r$r(rrN�socket�	AF_UNSPECrx�netutil�_DEFAULT_BACKLOGr��
AddressFamilyr�r	rerkrmrXrWr
rr"rur{r6rr�rDrRr�r4r4r4r5r?�s�T�����
�;��������	�

�,�

���
�����
��
�r?c@s�eZdZdedejdeedee	e
efdeee
dee	e
e
fddfd	d
�Zdeejejfdejdeedfd
d�Zde
deedfdd�Zddd�Zddd�Zdeedfdd�ZdS)r~r>r@�
handler_class�handler_kwargsr�r�rBNcCsN||_|j|_||_||_|pi|_|pg|_|pi|_g|_t|j�|_	dSrC)
r>rYr@r�r�r�r��chunksrmr+)rIr>r@r�r�r�r�r4r4r5rN5	s	


z_HandlerDelegate.__init__rdr�cCs|jrt�|j_|��SdSrC)r+rr@rnr|)rIrdr�r4r4r5�headers_receivedH	s
z!_HandlerDelegate.headers_received�datacCs"|jr	|j�|�S|j�|�dSrC)r+rMr�r�r�)rIr�r4r4r5r�R	sz_HandlerDelegate.data_receivedcCs>|jrt|jjd�dSd�|j�|j_|j��|��dS)Nr)	r+rr@rnrr��body�_parse_bodyr|rHr4r4r5r�Y	s

z_HandlerDelegate.finishcCs|jr
|j��dSd|_dSrC)r+rMr[r�rHr4r4r5r[a	s
z$_HandlerDelegate.on_connection_closecs��jj�dd�s'tj�tj��D]}|��qWd�n1s"wY�jj�dd�s;�jj�dt�}|���j	�j�j
fi�j���_�fdd��jj
D�}�jr\t��j_t��jj|g�j�Ri�j���}|�dd���jjS)	NrQTrRr�csg|]}|�j��qSr4)r@)rErKrHr4r5r�x	r�z,_HandlerDelegate.execute.<locals>.<listcomp>cSs|��SrC)r�)�fr4r4r5r��	r�z*_HandlerDelegate.execute.<locals>.<lambda>)r>rcr�r6r@rAr��resetr�r�r@r�rMr�r+rrRr�convert_yieldedr�r�r��add_done_callback)rIrJr�r��futr4rHr5r|g	s0
�����
�z_HandlerDelegate.executer	)r1r2r3r?r
rr(r6r!rr�rr$r�rNr �RequestStartLiner^rwr"r�r�r�r[r|r4r4r4r5r~4	s6����
��
���

�


r~c@sFeZdZdZ		d
dedeedededdf
d	d
�Zdefdd�Z	dS)rfa�An exception that will turn into an HTTP error response.

    Raising an `HTTPError` is a convenient alternative to calling
    `RequestHandler.send_error` since it automatically ends the
    current function.

    To customize the response sent with an `HTTPError`, override
    `RequestHandler.write_error`.

    :arg int status_code: HTTP status code.  Must be listed in
        `httplib.responses <http.client.responses>` unless the ``reason``
        keyword argument is given.
    :arg str log_message: Message to be written to the log for this error
        (will not be shown to the user unless the `Application` is in debug
        mode).  May contain ``%s``-style placeholders, which will be filled
        in with remaining positional parameters.
    :arg str reason: Keyword-only argument.  The HTTP "reason" phrase
        to pass in the status line along with ``status_code``.  Normally
        determined automatically from ``status_code``, but can be used
        to use a non-standard numeric code.
    rxNr�r�rdrArBcOsB||_||_||_|�dd�|_|r|s|�dd�|_dSdSdS)Nr��%z%%)r�r�rdr�r��replace)rIr�r�rdrAr4r4r5rN�	s�zHTTPError.__init__cCsBd|j|jp
tj�|jd�f}|jr|d|j|jdS|S)NzHTTP %d: %sr�z (�))r�r�r
r�r�r�rd)rIrr4r4r5�__str__�	s�zHTTPError.__str__)rxN)
r1r2r3rr�r!r�rrNr�r4r4r4r5rf�	s �����
�rfc@seZdZdZdS)r�a�An exception that ends the request without producing an error response.

    When `Finish` is raised in a `RequestHandler`, the request will
    end (calling `RequestHandler.finish` if it hasn't already been
    called), but the error-handling methods (including
    `RequestHandler.write_error`) will not be called.

    If `Finish()` was created with no arguments, the pending response
    will be sent as-is. If `Finish()` was given an argument, that
    argument will be passed to `RequestHandler.finish()`.

    This can be a more convenient way to implement custom error pages
    than overriding ``write_error`` (especially in library code)::

        if self.current_user is None:
            self.set_status(401)
            self.set_header('WWW-Authenticate', 'Basic realm="something"')
            raise Finish()

    .. versionchanged:: 4.3
       Arguments passed to ``Finish()`` will be passed on to
       `RequestHandler.finish`.
    N)r1r2r3rr4r4r4r5r��	sr�cs*eZdZdZdeddf�fdd�Z�ZS)r�z�Exception raised by `RequestHandler.get_argument`.

    This is a subclass of `HTTPError`, so if it is uncaught a 400 response
    code will be used instead of 500 (and a stack trace will not be logged).

    .. versionadded:: 3.1
    �arg_namerBNcst��dd|�||_dS)Nr�zMissing argument %s)rMrNr�)rIr�r]r4r5rN�	s
zMissingArgumentError.__init__)r1r2r3rr�rNr#r4r4r]r5r��	sr�c@s6eZdZdZdeddfdd�Zddd�Zdd	d
�ZdS)r�zBGenerates an error response with ``status_code`` for all requests.r�rBNcCs|�|�dSrC)r�)rIr�r4r4r5r\�	rzErrorHandler.initializecCs
t|j��rC)rfrrHr4r4r5rj�	�
zErrorHandler.preparecCr_rCr4rHr4r4r5r��	r�zErrorHandler.check_xsrf_cookier	)r1r2r3rr�r\rjr�r4r4r4r5r��	s

r�c@s>eZdZdZd
dededdfdd�Zd	ed
eddfdd�ZdS)�RedirectHandlera_Redirects the client to the given URL for all GET requests.

    You should provide the keyword argument ``url`` to the handler, e.g.::

        application = web.Application([
            (r"/oldpath", web.RedirectHandler, {"url": "/newpath"}),
        ])

    `RedirectHandler` supports regular expression substitutions. E.g., to
    swap the first and second parts of a path while preserving the remainder::

        application = web.Application([
            (r"/(.*?)/(.*?)/(.*)", web.RedirectHandler, {"url": "/{1}/{0}/{2}"}),
        ])

    The final URL is formatted with `str.format` and the substrings that match
    the capturing groups. In the above example, a request to "/a/b/c" would be
    formatted like::

        str.format("/{1}/{0}/{2}", "a", "b", "c")  # -> "/b/a/c"

    Use Python's :ref:`format string syntax <formatstrings>` to customize how
    values are substituted.

    .. versionchanged:: 4.5
       Added support for substitutions into the destination URL.

    .. versionchanged:: 5.0
       If any query arguments are present, they will be copied to the
       destination URL.
    Tr�r�rBNcC�||_||_dSrC)�_url�
_permanent)rIr�r�r4r4r5r\
�
zRedirectHandler.initializerdrAcOsH|jj|i|��}|jjrt�|tt�|jj���}|j||j	d�dS)Nr/)
r�rr@r�r
�
url_concatr�	qs_to_qslr�r�)rIrdrA�to_urlr4r4r5r�
s�zRedirectHandler.getr
)	r1r2r3rr�r�r\rr�r4r4r4r5r��	s r�c
@seZdZdZdZiZe��Zd>de	de
e	ddfdd�Zed?d	d
��Z
de	dedfdd�Zd@de	deddfdd�Zde
e	fdd�Zd?dd�Zdefdd�Zede	de	de	fdd��Zde	de	de
e	fdd�Ze	dAde	de
ede
edeeddffd d!��Zede	de	fd"d#��Zdejfd$d%�Zdefd&d'�Zde
e j fd(d)�Z!de	fd*d+�Z"de	ddfd,d-�Z#de	d.e
e j d/e	defd0d1�Z$e	
d@d2e%e	e&fde	d3ede	fd4d5��Z'd6e	de	fd7d8�Z(ed2e%e	e&fde	de
e	fd9d:��Z)ed;e	de
e	fd<d=��Z*dS)Br�aMA simple handler that can serve static content from a directory.

    A `StaticFileHandler` is configured automatically if you pass the
    ``static_path`` keyword argument to `Application`.  This handler
    can be customized with the ``static_url_prefix``, ``static_handler_class``,
    and ``static_handler_args`` settings.

    To map an additional path to this handler for a static data directory
    you would add a line to your application like::

        application = web.Application([
            (r"/content/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
        ])

    The handler constructor requires a ``path`` argument, which specifies the
    local root directory of the content to be served.

    Note that a capture group in the regex is required to parse the value for
    the ``path`` argument to the get() method (different than the constructor
    argument above); see `URLSpec` for details.

    To serve a file like ``index.html`` automatically when a directory is
    requested, set ``static_handler_args=dict(default_filename="index.html")``
    in your application settings, or add ``default_filename`` as an initializer
    argument for your ``StaticFileHandler``.

    To maximize the effectiveness of browser caching, this class supports
    versioned urls (by default using the argument ``?v=``).  If a version
    is given, we instruct the browser to cache this file indefinitely.
    `make_static_url` (also available as `RequestHandler.static_url`) can
    be used to construct a versioned url.

    This handler is intended primarily for use in development and light-duty
    file serving; for heavy traffic it will be more efficient to use
    a dedicated static file server (such as nginx or Apache).  We support
    the HTTP ``Accept-Ranges`` mechanism to return partial content (because
    some browsers require this functionality to be present to seek in
    HTML5 audio or video).

    **Subclassing notes**

    This class is designed to be extensible by subclassing, but because
    of the way static urls are generated with class methods rather than
    instance methods, the inheritance patterns are somewhat unusual.
    Be sure to use the ``@classmethod`` decorator when overriding a
    class method.  Instance methods may use the attributes ``self.path``
    ``self.absolute_path``, and ``self.modified``.

    Subclasses should only override methods discussed in this section;
    overriding other methods is error-prone.  Overriding
    ``StaticFileHandler.get`` is particularly problematic due to the
    tight coupling with ``compute_etag`` and other methods.

    To change the way static urls are generated (e.g. to match the behavior
    of another server or CDN), override `make_static_url`, `parse_url_path`,
    `get_cache_time`, and/or `get_version`.

    To replace all interaction with the filesystem (e.g. to serve
    static content from a database), override `get_content`,
    `get_content_size`, `get_modified_time`, `get_absolute_path`, and
    `validate_absolute_path`.

    .. versionchanged:: 3.1
       Many of the methods for subclasses were added in Tornado 3.1.
    i�Nr��default_filenamerBcCr�rC)�rootr�)rIr�r�r4r4r5r\o
r�zStaticFileHandler.initializecCs2|j�i|_Wd�dS1swYdSrC)�_lock�_static_hashesr*r4r4r5r�s
s"�zStaticFileHandler.resetcCs|j|dd�S)NF)�include_body)r��rIr�r4r4r5rx
rzStaticFileHandler.headTr�c	�s.�|�|�|_~|�|j|j�}|�|j|�|_|jdurdS|��|_|��|�	�r3|�
d�dSd}|jj�
d�}|rCt�|�}|��}|r�|\}}|dur_|dkr_||7}|dkr_d}|duro||kss|duro||kss|dkr�|�
d�|�dd�|�dd|f�dS|dur�||kr�|}||p�||p�dkr�|�
d	�|�dt�|||��nd}}|dur�|dur�||}	n|dur�|}	n|dur�||}	n|}	|�d
|	�|�r|�|j||�}
t|
t�r�|
g}
|
D]}z|�|�|��IdHWq�tj�y	YdSwdS|jjdk�sJ�dS)Nri�Rangeri�rtrz
Content-Rangez
bytes */%s��rlr8)�parse_url_pathr��get_absolute_pathr��validate_absolute_path�
absolute_path�get_modified_time�modified�set_headers�should_return_304r�r@r�r�r
�_parse_request_range�get_content_sizer��_get_content_range�get_contentr�r�rrfrrqr\)rIr�r�r��
request_range�range_header�sizer]�endru�contentr�r4r4r5r�{
sx�





��



��zStaticFileHandler.getcCs,|jdusJ�|�|j�}|sdSd|fS)aSets the ``Etag`` header based on static url version.

        This allows efficient ``If-None-Match`` checks against cached
        versions, and sends the correct ``Etag`` for a partial response
        (i.e. the same ``Etag`` as the full file).

        .. versionadded:: 3.1
        Nr�)r��_get_cached_version)rI�version_hashr4r4r5r��
s
	
zStaticFileHandler.compute_etagcCs�|�dd�|��|jdur|�d|j�|��}|r"|�d|�|�|j|j|�}|dkrK|�dtj�tjj	�tj
|d��|�d	d
t|��|�|j�dS)z]Sets the content and caching headers on the response.

        .. versionadded:: 3.1
        z
Accept-Rangesr�Nz
Last-Modifiedrtr�Expires)�secondsz
Cache-Controlzmax-age=)
r�ror��get_content_type�get_cache_timer�r�r�r�r�r�r��set_extra_headers)rI�content_type�
cache_timer4r4r5r��
s"

��zStaticFileHandler.set_headerscCsr|jj�d�r|��S|jj�d�}|dur7tj�|�}|jdur)|jt	j
jd�}|jdus0J�||jkr7dSdS)zgReturns True if the headers indicate that we should return 304.

        .. versionadded:: 3.1
        r�zIf-Modified-SinceN)�tzinfoTF)
r@r�r�rp�email�utils�parsedate_to_datetimer�r�r�r�r�r�)rI�	ims_value�if_sincer4r4r5r��
s

z#StaticFileHandler.should_return_304r�cCstj�tj�||��}|S)a�Returns the absolute location of ``path`` relative to ``root``.

        ``root`` is the path configured for this `StaticFileHandler`
        (in most cases the ``static_path`` `Application` setting).

        This class method may be overridden in subclasses.  By default
        it returns a filesystem path, but other strings may be used
        as long as they are unique and understood by the subclass's
        overridden `get_content`.

        .. versionadded:: 3.1
        )r>r��abspathr)r&r�r�r�r4r4r5r�
sz#StaticFileHandler.get_absolute_pathr�cCs�tj�|�}|�tjj�s|tjj7}|tjj�|�s#tdd|j��tj�|�rV|jdurV|j	j�d�sN|j	j�d�rAtdd��|j
|j	jddd�dStj�||j�}tj�|�s`td	��tj�
|�smtdd
|j��|S)a�Validate and return the absolute path.

        ``root`` is the configured path for the `StaticFileHandler`,
        and ``path`` is the result of `get_absolute_path`

        This is an instance method called during request processing,
        so it may raise `HTTPError` or use methods like
        `RequestHandler.redirect` (return None after redirecting to
        halt further processing).  This is where 404 errors for missing files
        are generated.

        This method may modify the path before returning it, but note that
        any such modifications will not be understood by `make_static_url`.

        In instance methods, this method's result is available as
        ``self.absolute_path``.

        .. versionadded:: 3.1
        r�z"%s is not in root static directoryNr�z//z-cannot redirect path with two initial slashesTr/r0z%s is not a file)r>r�r�r1�sepr�rf�isdirr�r@r�r�exists�isfile)rIr�r�r4r4r5r�s&�z(StaticFileHandler.validate_absolute_pathr�r]r�ccs��t|d��M}|dur|�|�|dur||pd}nd}	d}|dur*||kr*|}|�|�}|r?|dur;|t|�8}|Vn|durI|dksIJ�	Wd�dSq1sVwYdS)aZRetrieve the content of the requested resource which is located
        at the given absolute path.

        This class method may be overridden by subclasses.  Note that its
        signature is different from other overridable class methods
        (no ``settings`` argument); this is deliberate to ensure that
        ``abspath`` is able to stand on its own as a cache key.

        This method should either return a byte string or an iterator
        of byte strings.  The latter is preferred for large files
        as it helps reduce memory fragmentation.

        .. versionadded:: 3.1
        �rbNrTi)�open�seek�readrm)r&r�r]r��file�	remaining�
chunk_sizer�r4r4r5r�Ys,�

��zStaticFileHandler.get_contentcCsJ|�|�}t��}t|t�r|�|�|��S|D]}|�|�q|��S)z�Returns a version string for the resource at the given path.

        This class method may be overridden by subclasses.  The
        default implementation is a SHA-512 hash of the file's contents.

        .. versionadded:: 3.1
        )r�r��sha512r�r�rEr�)r&r�r�r�r�r4r4r5�get_content_version�s
	

�z%StaticFileHandler.get_content_versioncCs,|jdusJ�t|d�st�|j�|_|jS)N�_stat_result)r�r�r>�statr�rHr4r4r5�_stat�s
zStaticFileHandler._statcCs|��}|jS)a%Retrieve the total size of the resource at the given path.

        This method may be overridden by subclasses.

        .. versionadded:: 3.1

        .. versionchanged:: 4.0
           This method is now always called, instead of only when
           partial results are requested.
        )r��st_size)rI�stat_resultr4r4r5r��sz"StaticFileHandler.get_content_sizecCs$|��}tj�t|j�tjj�}|S)a�Returns the time that ``self.absolute_path`` was last modified.

        May be overridden in subclasses.  Should return a `~datetime.datetime`
        object or None.

        .. versionadded:: 3.1

        .. versionchanged:: 6.4
           Now returns an aware datetime object instead of a naive one.
           Subclasses that override this method may return either kind.
        )r�r��
fromtimestampr��st_mtimer�r�)rIr�r�r4r4r5r��s
	�z#StaticFileHandler.get_modified_timecCsF|jdusJ�t�|j�\}}|dkrdS|durdS|dur!|SdS)zhReturns the ``Content-Type`` header to be used for this request.

        .. versionadded:: 3.1
        NrJzapplication/gzipzapplication/octet-stream)r��	mimetypes�
guess_type)rI�	mime_type�encodingr4r4r5r��sz"StaticFileHandler.get_content_typecCri)z1For subclass to add extra headers to the responseNr4r�r4r4r5r��r�z#StaticFileHandler.set_extra_headersr�r�cCsd|jjvr	|jSdS)a�Override to customize cache control behavior.

        Return a positive number of seconds to make the result
        cacheable for that amount of time or 0 to mark resource as
        cacheable for an unspecified amount of time (subject to
        browser heuristics).

        By default returns cache expiry of 10 years for resources requested
        with ``v`` argument.
        r�r)r@r��
CACHE_MAX_AGE)rIr�r�r�r4r4r5r��s
z StaticFileHandler.get_cache_timerc�include_versioncCs8|�dd�|}|s|S|�||�}|s|Sd||fS)aConstructs a versioned url for the given path.

        This method may be overridden in subclasses (but note that it
        is a class method rather than an instance method).  Subclasses
        are only required to implement the signature
        ``make_static_url(cls, settings, path)``; other keyword
        arguments may be passed through `~RequestHandler.static_url`
        but are not standard.

        ``settings`` is the `Application.settings` dictionary.  ``path``
        is the static path being requested.  The url returned should be
        relative to the current host.

        ``include_version`` determines whether the generated URL should
        include the query string containing the version hash of the
        file corresponding to the given ``path``.

        rMrNz%s?v=%s)r��get_version)r&rcr�r�r�r�r4r4r5r��sz!StaticFileHandler.make_static_url�url_pathcCs tjjdkr|�dtjj�}|S)a"Converts a static URL path into a filesystem path.

        ``url_path`` is the path component of the URL with
        ``static_url_prefix`` removed.  The return value should be
        filesystem path relative to ``static_path``.

        This is the inverse of `make_static_url`.
        r�)r>r�r�r�)rIr�r4r4r5r�s	z StaticFileHandler.parse_url_pathcCs|�|d|�}|�|�S)a%Generate the version string to be used in static URLs.

        ``settings`` is the `Application.settings` dictionary and ``path``
        is the relative location of the requested asset on the filesystem.
        The returned value should be a string, or ``None`` if no version
        could be determined.

        .. versionchanged:: 3.1
           This method was previously recommended for subclasses to override;
           `get_content_version` is now preferred as it allows the base
           class to handle caching of the result.
        r�)r�r�)r&rcr��abs_pathr4r4r5r�s
zStaticFileHandler.get_versionr�c	Cs�|j�=|j}||vr(z	|�|�||<Wnty't�d|�d||<Ynw|�|�}|r8|Wd�SWd�dS1sCwYdS)NzCould not open static file %r)r�r�r�r�rr{r�)r&r��hashes�hshr4r4r5r�&s$�
�	
��z%StaticFileHandler._get_cached_versionrCr	r
)NN)+r1r2r3rr�r�rr
r�r�r!r\�classmethodr�r"rr�r�r�r�r�r�r�r�r'r�r�r�r>r�r�r�r�r�r�r�r�rrr�r�r�r�r4r4r4r5r�'
svBS
;�����&���
��
����
$r�c@s8eZdZdZdeejgdfddfdd�Zd	dd�ZdS)
�FallbackHandleraNA `RequestHandler` that wraps another HTTP server callback.

    The fallback is a callable object that accepts an
    `~.httputil.HTTPServerRequest`, such as an `Application` or
    `tornado.wsgi.WSGIContainer`.  This is most useful to use both
    Tornado ``RequestHandlers`` and WSGI in the same server.  Typical
    usage::

        wsgi_app = tornado.wsgi.WSGIContainer(
            django.core.handlers.wsgi.WSGIHandler())
        application = tornado.web.Application([
            (r"/foo", FooHandler),
            (r".*", FallbackHandler, dict(fallback=wsgi_app)),
        ])
    �fallbackNrBcCr�rC)r�)rIr�r4r4r5r\GrwzFallbackHandler.initializecCs|�|j�d|_|��dS)NT)r�r@rPrkrHr4r4r5rjLszFallbackHandler.preparer	)	r1r2r3rr%r
rr\rjr4r4r4r5r�6s�
�r�c
@sfeZdZdZdejddfdd�Zdedejd	e	d
e
deeeje	ff
dd�Zd	e	d
e
de	fd
d�Z
dS)r�z�A transform modifies the result of an HTTP request (e.g., GZip encoding)

    Applications are not expected to create their own OutputTransforms
    or interact with them directly; the framework chooses which transforms
    (if any) to apply.
    r@rBNcCr_rCr4�rIr@r4r4r5rNZrazOutputTransform.__init__r�r�r��	finishingcCs
|||fSrCr4)rIr�r�r�r�r4r4r5r[]s
z%OutputTransform.transform_first_chunkcCs|SrCr4�rIr�r�r4r4r5r`frazOutputTransform.transform_chunk)r1r2r3rr
rrNr�rwr�r�r#r[r`r4r4r4r5r�Rs����
�	r�c
@s�eZdZdZegd��ZdZdZdej	ddfdd	�Z
d
edefdd�Z
d
edejdededeeejeff
dd�Zdededefdd�ZdS)rSaIApplies the gzip content encoding to the response.

    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11

    .. versionchanged:: 4.0
        Now compresses all mime types beginning with ``text/``, instead
        of just a whitelist. (the whitelist is still used for certain
        non-text mime types).
    )zapplication/javascriptzapplication/x-javascriptzapplication/xmlzapplication/atom+xmlzapplication/jsonzapplication/xhtml+xmlz
image/svg+xml�ir@rBNcCsd|j�dd�v|_dS)NrJ�Accept-Encodingr�)r�r��	_gzippingr�r4r4r5rN��zGZipContentEncoding.__init__�ctypecCs|�d�p	||jvS)Nztext/)r��
CONTENT_TYPES)rIr�r4r4r5�_compressible_type��z&GZipContentEncoding._compressible_typer�r�r�r�cCs�d|vr
|dd7<nd|d<|jr5t|�dd���d�d}|�|�o3|p/t|�|jko3d|v|_|jrcd	|d<t�|_t	j
d
|j|jd�|_|�
||�}d|vrc|r`tt|��|d<n|d=|||fS)
N�Varyz, Accept-Encodingr�rtr�r�rrrJ�w)�mode�fileobj�
compresslevelrl)r�rr�r�r�rm�
MIN_LENGTHr�_gzip_valuerJ�GzipFile�
GZIP_LEVEL�
_gzip_filer`r�)rIr�r�r�r�r�r4r4r5r[�s,
��
�
z)GZipContentEncoding.transform_first_chunkcCsR|jr'|j�|�|r|j��n|j��|j��}|j�d�|j�d�|S)Nr)	r�r
r�closerfr�getvalue�truncater�r�r4r4r5r`�s

z#GZipContentEncoding.transform_chunk)r1r2r3rr�r�r	rr
rrNr�r�r�r�rwr�r#r[r`r4r4r4r5rSjs*�����
�%rScr,)a�Decorate methods with this to require that the user be logged in.

    If the user is not logged in, they will be redirected to the configured
    `login url <RequestHandler.get_login_url>`.

    If you configure a login url with a query parameter, Tornado will
    assume you know what you're doing and use it as-is.  If not, it
    will add a `next` parameter so the login page knows where to send
    you once you're logged in.
    rIrBNcs�|js@|jjdvr<|��}d|vr5tj�|�jr|j��}n|jj	dus&J�|jj	}|dt
t|d��7}|�|�dSt
d���|g|�Ri|��S)Nrgr.)�nextr�)rNr@r\r��urllib�parse�urlsplit�scheme�full_urlr�rr�r�rf)rIrdrAr��next_urlr5r4r5r6�s
zauthenticated.<locals>.wrapperr7r:r4r5r5�
authenticated�s�
�rc@s�eZdZdZdeddfdd�Zedefdd��Zd	ed
ede	fdd�Z
dee	fd
d�Zdee
e	fdd�Zdee	fdd�Zdee
e	fdd�Zdee	fdd�Zdee	fdd�Zde	d
edefdd�ZdS)ra2A re-usable, modular UI unit on a page.

    UI modules often execute additional queries, and they can include
    additional CSS and JavaScript that will be included in the output
    page, which is automatically inserted on page render.

    Subclasses of UIModule must override the `render` method.
    rMrBNcCs"||_|j|_|j|_|j|_dSrC)rMr@rUr�rIrMr4r4r5rN�szUIModule.__init__cCrbrC)rMrNrHr4r4r5rN�szUIModule.current_userrdrAcOr�)z6Override in subclasses to return this module's output.r�rgr4r4r5r*�r�zUIModule.rendercCri)zJOverride to return a JavaScript string
        to be embedded in the page.Nr4rHr4r4r5r
�zUIModule.embedded_javascriptcCri)z�Override to return a list of JavaScript files needed by this module.

        If the return values are relative paths, they will be passed to
        `RequestHandler.static_url`; otherwise they will be used as-is.
        Nr4rHr4r4r5r
�zUIModule.javascript_filescCri)zJOverride to return a CSS string
        that will be embedded in the page.Nr4rHr4r4r5r
rzUIModule.embedded_csscCri)z�Override to returns a list of CSS files required by this module.

        If the return values are relative paths, they will be passed to
        `RequestHandler.static_url`; otherwise they will be used as-is.
        Nr4rHr4r4r5r
rzUIModule.css_filescCri)z[Override to return an HTML string that will be put in the <head/>
        element.
        Nr4rHr4r4r5r
r�zUIModule.html_headcCri)zfOverride to return an HTML string that will be put at the end of
        the <body/> element.
        Nr4rHr4r4r5r"
r�zUIModule.html_bodyr�cKs|jj|fi|��S)z.Renders a template and returns it as a string.)rMr	)rIr�rAr4r4r5r	(
r�zUIModule.render_string)r1r2r3rr6rNrrrNr�r*r!rr&rrrrrr�r	r4r4r4r5r�s	rc@s"eZdZdededefdd�ZdS)rT�textrArBcKstj|fi|��SrC)rrK)rIrrAr4r4r5r*.
sz_linkify.renderN)r1r2r3r�rr*r4r4r4r5rT-
srTc@seZdZdefdd�ZdS)rUrBcCs
|j��SrC)rMrQrHr4r4r5r*3
r�z_xsrf_form_html.renderN)r1r2r3r�r*r4r4r4r5rU2
srUcs�eZdZdZdeddf�fdd�Zdededefd	d
�Z	dede
efdd
�Zdefdd�Zde
efdd�Z
defdd�Zde
efdd�Zdefdd�Zdefdd�Z�ZS)rVa�UIModule that simply renders the given template.

    {% module Template("foo.html") %} is similar to {% include "foo.html" %},
    but the module version gets its own namespace (with kwargs passed to
    Template()) instead of inheriting the outer template's namespace.

    Templates rendered through this module also get access to UIModule's
    automatic JavaScript/CSS features.  Simply call set_resources
    inside the template and give it keyword arguments corresponding to
    the methods on UIModule: {{ set_resources(js_files=static_url("my.js")) }}
    Note that these resources are output once per template file, not once
    per instantiation of the template, so they must not depend on
    any arguments to the template.
    rMrBNcst��|�g|_i|_dSrC)rMrN�_resource_list�_resource_dictrr]r4r5rNG
s
zTemplateModule.__init__r�rAcs*dtf��fdd�}�j�fd|i|��S)NrBcs>��jvr�j�|�|�j�<dS�j�|krtd��dS)NzCset_resources called with different resources for the same templater�)rrr�r�)rA�r�rIr4r5�
set_resourcesN
s

��z,TemplateModule.render.<locals>.set_resourcesr)r�r	)rIr�rArr4rr5r*M
szTemplateModule.renderr�cs�fdd�|jD�S)Nc3s �|]}�|vr|�VqdSrCr4)rE�r�r�r4r5rJ]
s�z0TemplateModule._get_resources.<locals>.<genexpr>)r�rIr�r4rr5�_get_resources\
rzTemplateModule._get_resourcescC�d�|�d��S)N�
r�rr!rHr4r4r5r_
rnz"TemplateModule.embedded_javascriptcC�<g}|�d�D]}t|ttf�r|�|�q|�|�q|S)Nr�r!r�rr�r�r
�rIr�r�r4r4r5rb
�zTemplateModule.javascript_filescCr")Nr#rr$rHr4r4r5rk
rnzTemplateModule.embedded_csscCr%)Nrr&r'r4r4r5rn
r(zTemplateModule.css_filescCr")Nr�rr$rHr4r4r5rw
rnzTemplateModule.html_headcCr")Nr�rr$rHr4r4r5rz
rnzTemplateModule.html_body)r1r2r3rr6rNr�rr�r*r&r!rrrrrrr#r4r4r]r5rV7
s		rVc@sfeZdZdZdedeeeefddfdd�Z	dede
d	effd
d�Zdede
d	effdd
�ZdS)rVzALazy namespace which creates UIModule proxies bound to a handler.rMrWrBNcCr�rC)rMrW)rIrMrWr4r4r5rN�
s
z_UIModuleNamespace.__init__r�.cCs|j�||j|�SrC)rMrrWr r4r4r5�__getitem__�
rz_UIModuleNamespace.__getitem__c
Cs0z||WSty}ztt|���d}~wwrC)r��AttributeErrorr�)rIr�r�r4r4r5�__getattr__�
s
��z_UIModuleNamespace.__getattr__)
r1r2r3rr6rr�r(rrNr%r)r+r4r4r4r5rV~
s��
�rVr�r�r�ry�clockr�c
Cs|durt}|dur
tj}ttt|����}t�t|��}|dkr9t|t�r(J�t	||||�}d�
|||g�}|S|dkr�dtttfdtfdd�}d�
d|t|pRd	��||�||�||�d
g�}	t|t�rz|dusnJd��|dksvJd��||}t
||	�}|	|Std
|��)Nr.r�r/r�rBcSstdt|��t|�S)Nz%d:)rrm)r�r4r4r5�format_field�
r�z)create_signed_value.<locals>.format_fieldr�rrz2Key version must be set when sign key dict is usedz2Version must be at least 2 for key version supportzUnsupported version %d)�DEFAULT_SIGNED_VALUE_VERSIONr{rr�r��base64�	b64encoder�r��_create_signature_v1rr r��_create_signature_v2r�)
r�r�r�ryr,r�r��	signaturer-�to_signr4r4r5r��
s>��

�
r�s^([1-9][0-9]*)\|(.*)$cCsZt�|�}|dur
d}|Szt|�d��}|dkrd}W|SW|Sty,d}Y|Sw)Nr.i�)r�r�r�r�r�)r�rGryr4r4r5�_get_version�
s
��
��r5r�r�r�cCs�|durtj}|dur
t}|dkrtd|��|sdSt|�}t|�}||kr)dS|dkr<t|t�r4J�t|||||�S|dkrHt|||||�SdS)Nr/zUnsupported min_version %dr.)	r{� DEFAULT_SIGNED_VALUE_MIN_VERSIONr�rr5r�r��_decode_signed_value_v1�_decode_signed_value_v2)r�r�r�r�r,r�ryr4r4r5r��
s$r�cCs�t|��d�}t|�dkrdSt|||d|d�}t�|d|�s*t�d|�dSt|d�}||�|dkrAt�d|�dS||�d	krPt�d
|�dS|d�	d�r_t�d|�dSzt
�|d�WStyqYdSw)
Nr��rr.r/zInvalid cookie signature %r�QzExpired cookie %ri��(z1Cookie timestamp in future; possible tampering %r�0zTampered cookie %r)
rr�rmr1r�r�rr�r�r�r/�	b64decoder�)r�r�r�r�r,r�r3r�r4r4r5r7
s,�r7cCshdtdtttffdd�}|dd�}||�\}}||�\}}||�\}}||�\}}t|�||||fS)Nr�rBcSsX|�d�\}}}t|�}|d|�}|||d�dkr td��||dd�}||fS)N�:r.r�zmalformed v2 signed value field)�	partitionr�r�)r��lengthrO�restrF�field_valuer4r4r5�_consume_field.sz)_decode_fields_v2.<locals>._consume_fieldr/)r�r#r�)r�rBr@r�r��
name_field�value_field�
passed_sigr4r4r5�_decode_fields_v2-srFc
Cs�zt|�\}}}}}	Wn
tyYdSw|dt|	��}
t|t�r5z||}Wn
ty4YdSwt||
�}t�|	|�sBdS|t	|�krJdSt
|�}||�|dkrYdSzt�|�WSt
yiYdSw)Nr:)rFr�rmr�r�r�r2r�r�rr�r/r<r�)
r�r�r�r�r,r��timestamp_bytesrCrDrE�
signed_string�expected_sigr�r4r4r5r8As>��
�
�r8cCsJt|�}t|�}|dkrdSzt|�\}}}}}W|Sty$YdSw)Nr/)rr5rFr�)r�ryr�rOr4r4r5r�is��r�r�cGs8tjt|�tjd�}|D]	}|�t|��qt|���S�N)�	digestmod)r��newrr�r�rEr�)r�r��hashrnr4r4r5r1vsr1r�cCs.tjt|�tjd�}|�t|��t|���SrJ)r�rLrr��sha256rEr�)r�r�rMr4r4r5r2}sr2r�cst�fdd�dD��S)Nc3s�|]}��|�VqdSrCr�)rEr��r�r4r5rJ�s�zis_absolute.<locals>.<genexpr>)r�zhttp:zhttps:)�anyrOr4rOr5r2�sr2r�)r�NN)�rr/r�r��email.utilsr�r8rJr�r��http.cookiesr��inspectr�iorr�r��os.pathr>r�r�r9rr{r�rxr�rv�urllib.parserr�tornado.concurrentrrrr�tornado.httpserverr	r
rr�tornado.logr
rrr�tornado.escaperr�tornado.routingrrrrrrrr�tornado.utilrrrr��typingrrr r!r"r#r$r%r&r'r(r)r*r+r,�
TYPE_CHECKINGr-r�r�r�rr��_CookieSecretTypes�"MIN_SUPPORTED_SIGNED_VALUE_VERSION�"MAX_SUPPORTED_SIGNED_VALUE_VERSIONr.r6r0r�objectr6r$r+r�rmr;r<r=r?rFr~r�rfr�r�r�r�r�r�r�rSrrrTrUrVrVr�r�rr�r5r�r7rFr8r�r1r2r2r4r4r4r5�<module>sh/(
@ I�
��
�'@Y00[�
�%CG���
����
�
@�������
�
����
�
� #����
�
�(&