
    Mh"9                       d Z ddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
ZddlmZ ddlmZ ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZ ddl m!Z!m"Z" ddlm#Z# ddlm$Z$ dd	l%m&Z& dd
lm'Z' ddlm(Z( ddlm)Z) ddl*m+Z+m,Z,m-Z- ddlm.Z. ddl/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: ddl;m<Z<m=Z=m>Z> e9Z?ddl@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZN ddlmOZO ddl@Z@e@jP        rddl@mQZQ eCeRe=eSejT        ej        f         ZUeCeVeReAeSeVf         eAeSeRf         f         ZWdZX	 dZY	 dZZ	 dZ[	  G d d          Z\ e\            Z] G d d          Z^ eLde^          Z_deKe_         deKe_         fdZ`deKe^         deafd Zbd!eHd"eDeEd                  f         deHd"eDeEd                  f         fd#Zcd!eHd"eDeEd                  f         deHd"eDeEd                  f         fd$Zd G d% d&e8          Ze G d' d(e6          Zf G d) d*e'jg                  Zh G d+ d,ei          Zj G d- d.ei          Zk G d/ d0ej          Zl G d1 d2e^          Zm G d3 d4e^          Zn G d5 d6e^          Zo G d7 d8e^          Zp G d9 d:          Zq G d; d<eq          Zrd!eHd"eDeEd                  f         deHd"eDeEd                  f         fd=Zs G d> d?          Zt G d@ dAet          Zu G dB dCet          Zv G dD dEet          Zw G dF dG          Zx	 	 	 d_dHeWdIeVdJeCeVeRf         dKeDeS         dLeDeHg eyf                  dMeDeS         deRfdNZz ej{        dO          Z|dJeRdeSfdPZ}	 	 	 d`dHeWdIeVdJeCdeVeRf         dReydLeDeHg eyf                  dSeDeS         deDeR         fdTZ~dHeCeVeRf         dIeVdJeRdReydLeHg eyf         deDeR         fdUZdJeRdeFeSeReReReRf         fdVZdHeWdIeVdJeRdReydLeHg eyf         deDeR         fdWZdJeCeVeRf         deDeS         fdXZdHeCeVeRf         dYeCeVeRf         deRfdZZdHeCeVeRf         d[eRdeRfd\Zd]eVdeafd^ZdS )aa4  ``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())

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                       e Zd ZdS )_ArgDefaultMarkerN)__name__
__module____qualname__     K/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/tornado/web.pyr2   r2      s        Dr7   r2   c                   $    e Zd ZU dZdZeedf         ed<   i Z e	j
                    Z ej        d          ZdZdZdZdZdd	d
ej        deddf fdZddZeZ	 edeeef         fd            ZdededdfdZeZeZeZeZ eZ!eZ"eZ#de$e%d                  fdZ&ddZ'ddZ(ddZ)ddZ*dde+de$e         ddfdZ,de+fdZ-dede.ddfdZ/dede.ddfdZ0deddfdZ1 ej        d           Z2de.defd!Z3e4dded#ed$e5defd%            Z6e4e7d"fded#e8d$e5defd&            Z6e4	 dded#dd$e5de$e         fd'            Z6e7d"fded#e9dee8f         d$e5de$e         fd(Z6dded$e5de:e         fd)Z;e4dded#ed$e5defd*            Z<e4e7d"fded#e8d$e5defd+            Z<e4	 dded#dd$e5de$e         fd,            Z<e7d"fded#e9dee8f         d$e5de$e         fd-Z<dded$e5de:e         fd.Z=e4dded#ed$e5defd/            Z>e4e7d"fded#e8d$e5defd0            Z>e4	 dded#dd$e5de$e         fd1            Z>e7d"fded#e9dee8f         d$e5de$e         fd2Z>dded$e5de:e         fd3Z?	 dded#e9dee8f         d4eee:e@         f         d$e5de$e         f
d5ZA	 dded4eee:e@         f         d$e5de:e         fd6ZBdde@de$e         defd7ZCedeeeDjE        jF        f         fd8            ZEe4ded#edefd9            ZGe4dded#dde$e         fd:            ZGdded#e$e         de$e         fd;ZG	 	 	 	 dddddd=dede9ee@f         d>e$e         d?e$e9eHeeIjI        f                  d@edAe$eH         dBe$e+         dCe5dDe5dEe$e         deddfdFZJdededdfdGZKdeddfdHZL	 	 ddede9ee@f         dAe$eH         dJe$e+         deddfdKZMeMZN	 ddede9ee@f         dJe$e+         de@fdLZO	 	 	 ddede$e         dNeHdOe$e+         de$e@         f
dPZPePZQ	 ddede$e         de$e+         fdQZReRZS	 ddRedSe5dTe$e+         ddfdUZTdVe9ee@eUf         ddfdWZVdXededdYfdZZWd[eXe         defd\ZYd]eXe@         de@fd^ZZd_eXe         defd`Z[daeXe@         de@fdbZ\dXedede@fdcZ]deeef         fddZ^deede_j`        fdfZaddge5ddYfdhZbddVe$e9ee@eUf                  ddYfdiZcdedje        fdjZfddkZgdde+deddfdmZhde+deddfdnZiedejjk        jl        fdo            Zkekjm        dejjk        jl        ddfdp            Zkde$ejjk        jl                 fdqZndd#edejjk        jl        fdsZoedefdt            Zpepjm        deddfdu            ZpdefdvZqdefdwZrde$e         fdxZsede@fdy            Ztdee$e+         e@eHf         fdzZud{edee$e+         e$e@         e$eH         f         fd|Zvdd}Zwdefd~Zx	 dd@ede$e5         dedefdZyddededdfdZzdededefdZ{de$e         fdZ|ddZ}de5fdZ~de:d         de@de@ddfdZdVe@de$e%d                  fdZddZdefdZdeddfdZddde$e         de$e         ddfdZdeded         dedef         fdZdedef         dedef         fdZddZ xZS )RequestHandleraF  Base 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OPTIONS.SUPPORTED_METHODSz[\x00-\x08\x0e-\x1f]FNapplicationApplicationrequestkwargsreturnc                     t                                                       | _        | _        d _        d _        d _        d  _        t           fd|j	        
                                D                        _        t           |j                   j        d<    j        d          j        d<                                      j        j        J  j        j                             j                     j        di | d S )NFTc              3   L   K   | ]\  }}|                     |          fV  d S N)
_ui_method).0nmselfs      r8   	<genexpr>z*RequestHandler.__init__.<locals>.<genexpr>   sI       
 
(,1Q""#
 
 
 
 
 
r7   _tt_modulesmodulesr6   )super__init__rC   rE   _headers_written	_finished_auto_finish_prepared_futurer   
ui_methodsitemsui_UIModuleNamespace
ui_modulesclear
connectionset_close_callbackon_connection_close
initialize)rO   rC   rE   rF   	__class__s   `   r8   rT   zRequestHandler.__init__   s    	& %  $ 
 
 
 
0;0F0L0L0N0N
 
 
 
 
 "4D+:P!Q!Q!W]3	

|&22222$	
 	
 	
 	!!&!!!!!r7   c                     d S rJ   r6   rO   s    r8   _initializezRequestHandler._initialize       r7   c                     | j         j        S )z@An alias for `self.application.settings <Application.settings>`.)rC   settingsre   s    r8   ri   zRequestHandler.settings  s     ((r7   argsc                      t          d          )N  )	HTTPErrorrO   rj   rF   s      r8   _unimplemented_methodz$RequestHandler._unimplemented_method  s    nnr7   c                     dS )aX  Called at the beginning of a request before  `get`/`post`/etc.

        Override this method to perform common initialization regardless
        of the request method. There is no guarantee that ``prepare`` will
        be called if an error occurs that is handled by the framework.

        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.
        Nr6   re   s    r8   preparezRequestHandler.prepare  s	     	r7   c                     dS )aI  Called after the end of a request.

        Override this method to perform cleanup, logging, etc. This method is primarily intended as
        a counterpart to `prepare`. However, there are a few error cases where ``on_finish`` may be
        called when ``prepare`` has not. (These are considered bugs and may be fixed in the future,
        but for now you may need to check to see if the initialization work done in ``prepare`` has
        occurred)

        ``on_finish`` may not produce any output, as it is called after the response has been sent
        to the client.
        Nr6   re   s    r8   	on_finishzRequestHandler.on_finish,  s	     	r7   c                    t          | j                  rn| j        j                                        sR| j        j                            t          j                               | j        j                                         dS dS dS )aF  Called 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_bodyrc   rE   _body_futuredoneset_exceptionr   StreamClosedError	exceptionre   s    r8   ra   z"RequestHandler.on_connection_close:  s     $DN33 	6<,1133 6)778R8T8TUUU)3355555	6 	66 6r7   c                    t          j        dt          j        z  dt          j        t          j                              d          | _        |                                  g | _        d| _	        t           j
        d         | _        dS )z1Resets all headers and content for this response.zTornadoServer/%sztext/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_reasonre   s    r8   r^   zRequestHandler.clearM  sx     ,,w> : 1$)++>> 
 
 	  """)#.r7   c                     dS )aB  Override 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.
        Nr6   re   s    r8   r   z"RequestHandler.set_default_headers[  s	     	r7   status_codereasonc                     || _         |t          j        |          | _        dS t          j                            |d          | _        dS )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)r   r   
native_strr   r   r   get)rO   r   r   s      r8   
set_statuszRequestHandler.set_statuse  sF     (!,V44DLLL#-11+yIIDLLLr7   c                     | j         S )z)Returns the status code for our response.)r   re   s    r8   
get_statuszRequestHandler.get_statusx  s      r7   namevaluec                 @    |                      |          | j        |<   dS )zSets 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   rO   r   r   s      r8   
set_headerzRequestHandler.set_header|  s$     #88??dr7   c                 b    | j                             ||                     |                     dS )zAdds 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   s      r8   
add_headerzRequestHandler.add_header  s0     	$ : :5 A ABBBBBr7   c                 ,    || j         v r
| j         |= dS dS )zClears 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   )rO   r   s     r8   clear_headerzRequestHandler.clear_header  s)     4=  d### ! r7   z[\x09\x20-\x7e\x80-\xff]*c                    t          |t                    r|}nt          |t                    r|                    d          }nit          |t          j                  rt          |          S t          |t          j                  rt          j        |          S t          d|z            t          j                            |          t          d|          |S )Nlatin1zUnsupported header value %rzUnsafe header value %r)
isinstancestrbytesdecodenumbersIntegraldatetimer   r   	TypeErrorr:   _VALID_HEADER_CHARS	fullmatch
ValueError)rO   r   retvals      r8   r   z$RequestHandler._convert_header_value  s    
 eS!! 	CFFu%% 
	C \\(++FFw/00 	Cu::x011 	C,U3339EABBB -77??G5v>>>r7   Tdefaultstripc                     d S rJ   r6   rO   r   r   r   s       r8   get_argumentzRequestHandler.get_argument      r7   c                     d S rJ   r6   r   s       r8   r   zRequestHandler.get_argument  	     	r7   c                     d S rJ   r6   r   s       r8   r   zRequestHandler.get_argument  r   r7   c                 F    |                      ||| j        j        |          S )ar  Returns 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_argumentrE   	argumentsr   s       r8   r   zRequestHandler.get_argument  s#      !!$1GOOOr7   c                 r    t          |t                    sJ |                     || j        j        |          S )zReturns 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_argumentsrE   r   rO   r   r   s      r8   get_argumentszRequestHandler.get_arguments  s7     %&&&&&""4)?GGGr7   c                     d S rJ   r6   r   s       r8   get_body_argumentz RequestHandler.get_body_argument  r   r7   c                     d S rJ   r6   r   s       r8   r   z RequestHandler.get_body_argument  r   r7   c                     d S rJ   r6   r   s       r8   r   z RequestHandler.get_body_argument  r   r7   c                 F    |                      ||| j        j        |          S )aj  Returns 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   rE   body_argumentsr   s       r8   r   z RequestHandler.get_body_argument  s#    " !!$1LeTTTr7   c                 D    |                      || j        j        |          S )zReturns a list of the body arguments with the given name.

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

        .. versionadded:: 3.2
        )r   rE   r   r   s      r8   get_body_argumentsz!RequestHandler.get_body_arguments  s!     ""4)DeLLLr7   c                     d S rJ   r6   r   s       r8   get_query_argumentz!RequestHandler.get_query_argument  r   r7   c                     d S rJ   r6   r   s       r8   r   z!RequestHandler.get_query_argument  r   r7   c                     d S rJ   r6   r   s       r8   r   z!RequestHandler.get_query_argument  r   r7   c                 F    |                      ||| j        j        |          S )ar  Returns 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   rE   query_argumentsr   s       r8   r   z!RequestHandler.get_query_argument  s#    " !!$1MuUUUr7   c                 D    |                      || j        j        |          S )zReturns a list of the query arguments with the given name.

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

        .. versionadded:: 3.2
        )r   rE   r   r   s      r8   get_query_argumentsz"RequestHandler.get_query_arguments2  s!     ""4)EuMMMr7   sourcec                     |                      |||          }|s&t          |t                    rt          |          |S |d         S )N)r   )r   r   r2   MissingArgumentError)rO   r   r   r   r   rj   s         r8   r   zRequestHandler._get_argument;  sU     ""4u"== 	'#455 1*4000NBxr7   c                 *   g }|                     |g           D ]y}|                     ||          }t          |t                    r t          j                            d|          }|r|                                }|                    |           z|S )Nr    )	r   decode_argumentr   r   r:   _remove_control_chars_regexsubr   append)rO   r   r   r   valuesvss          r8   r   zRequestHandler._get_argumentsI  s     D"%% 	 	A$$QT$22A!\** K #>BB3JJ GGIIMM!r7   c           
          	 t          |          S # t          $ r/ t          dd                    |pd|dd                             w xY w)a  Decodes 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).
          zInvalid unicode in {}: {!r}urlN(   )r   UnicodeDecodeErrorrm   format)rO   r   r   s      r8   r   zRequestHandler.decode_argumentX  sc    	E??"! 	 	 	299$-%sPRsTT  	s	    9A
c                     | j         j        S )zRAn alias for
        `self.request.cookies <.httputil.HTTPServerRequest.cookies>`.)rE   cookiesre   s    r8   r   zRequestHandler.cookiesl  s     |##r7   c                     d S rJ   r6   rO   r   r   s      r8   
get_cookiezRequestHandler.get_cookier  r   r7   c                     d S rJ   r6   r   s      r8   r   zRequestHandler.get_cookiev  r   r7   c                 h    | j         j        %|| j         j        v r| j         j        |         j        S |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.
        )rE   r   r   r   s      r8   r   zRequestHandler.get_cookiez  s6     <+8L0L0L<'-33r7   /)max_agehttponlysecuresamesitedomainexpirespathexpires_daysr   r   r   r   c                V   t          j        |          }t          j        |          }t          j        d||z             rt	          d|d|          t          | d          s#t          j                                        | _	        || j	        v r| j	        |= || j	        |<   | j	        |         }|r||d<   |F|sDt          j
                            t          j        j                  t          j        |          z   }|rt          j        |          |d<   |r||d	<   |rt#          |          |d
<   |rd|d<   |	rd|d<   |
r|
|d<   |r^|                                D ]
\  }}|||<   t'          j        dt+          |                                           dt.                     dS dS )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]zInvalid cookie z: _new_cookier   Ndaysr   r   zmax-ageTr   r   r   z$Deprecated arguments to set_cookie: z (should be lowercase))r   r   researchr   hasattrhttpr   SimpleCookier   r   nowtimezoneutc	timedeltar   r   r   rZ   warningswarnsetkeysDeprecationWarning)rO   r   r   r   r   r   r   r   r   r   r   rF   morselkr   s                  r8   
set_cookiezRequestHandler.set_cookie  s   J  &&!%((9^TE\22 	DBtBBBBCCCt]++ 	))++  4### &!&!$' 	&%F8#G#'++H,=,ABBXEW!F F F G  	C ( 9' B BF9 	"!F6N 	- #GF9 	& "&F: 	$#F8 	*!)F: 
	   1q		M(s6;;==7I7I ( ( ("    
	 
	r7   c                     dD ]}||v rt          d| d          t          j                            t          j        j                  t          j        d          z
  } | j        |fd|d| dS )	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 ''im  r    )r   r   N)r   r   r   r   r   r   r  )rO   r   rF   excluded_argr   s        r8   clear_cookiezRequestHandler.clear_cookie  s    $ 3 	 	Lv%%Y,YYY   & #''(9(=>>ASB
 B
 B
 
 	BBBB6BBBBBr7   c                 @    | j         j        D ]} | j        |fi | dS )ac  Attempt 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)rE   r   r  )rO   rF   r   s      r8   clear_all_cookiesz RequestHandler.clear_all_cookies  s@    8 L( 	. 	.DDd--f----	. 	.r7      r   c                 T     | j         ||                     |||          fd|i| dS )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.
        )r   r   N)r  create_signed_value)rO   r   r   r   r   rF   s         r8   set_signed_cookiez RequestHandler.set_signed_cookie  sY    L 	$$T5'$BB	
 	
 &	
 		
 	
 	
 	
 	
r7   c                 (   |                      dd           | j        j        d         }d}t          |t                    r@| j        j                            d          t          d          | j        j        d         }t          |||||          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)r   r  )require_settingrC   ri   r   dictr   	Exceptionr  )rO   r   r   r   secretr  s         r8   r  z"RequestHandler.create_signed_valueD  s     	_.>???!*?;fd## 	C(,,];;C WXXX*3MBK"D%k
 
 
 	
r7      max_age_daysmin_versionc                     |                      dd           ||                     |          }t          | j        j        d         ||||          S )a  Returns 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_valuerC   ri   )rO   r   r   r  r  s        r8   get_signed_cookiez RequestHandler.get_signed_cookie^  sb    8 	_.>???=OOD))E"%o6%#
 
 
 	
r7   c                     |                      dd           ||                     |          }|dS t          |          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   s      r8   get_signed_cookie_key_versionz,RequestHandler.get_signed_cookie_key_version  sI     	_.>???=OOD))E=4(///r7   r   	permanentstatusc                 (   | j         rt          d          ||rdnd}n&t          |t                    rd|cxk    rdk    sn J |                     |           |                     dt          |                     |                                  dS )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)rU   r  r   intr   r   r   finish)rO   r   r$  r%  s       r8   redirectzRequestHandler.redirect  s       	OMNNN>%.SS3FFfc**Csf/C/C/C/C/C/C/C/C/C/C
DII...r7   chunkc                    | j         rt          d          t          |t          t          t
          f          s+d}t          |t                    r|dz  }t          |          t          |t
                    r*t          j	        |          }| 
                    dd           t          |          }| j                            |           dS )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
        zCannot 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.writer}   zapplication/json; charset=UTF-8N)rV   RuntimeErrorr   r   r   r  listr   r   json_encoder   r   r   r   )rO   r+  messages      r8   writezRequestHandler.write  s      > 	@>???%%t!<== 	%MG%&& f G$$$eT"" 	O&u--EOON,MNNNU!!%(((((r7   template_namezFuture[None]c                    | j         rt          d           | j        |fi |}g }g }g }g }g }g }	t          | di                                           D ]}
|
                                }|r"|                    t          |                     |
                                }|rTt          |t          t          f          r#|                    t          |                     n|                    |           |
                                }|r"|                    t          |                     |
                                }|rTt          |t          t          f          r#|                    t          |                     n|                    |           |
                                }|r"|                    t          |                     |
                                }|r"|	                    t          |                     |rR|                     |          }|                    d          }|d|         t          |          z   dz   ||d         z   }|rE|                     |          }|                    d          }|d|         |z   dz   ||d         z   }|rR|                     |          }|                    d          }|d|         t          |          z   dz   ||d         z   }|rE|                     |          }|                    d          }|d|         |z   dz   ||d         z   }|rC|                    d          }|d|         d                    |          z   dz   ||d         z   }|	rC|                    d          }|d|         d                    |	          z   dz   ||d         z   }|                     |          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``.
        zCannot render() after finish()_active_moduless   </body>N   
s   </head>r7   )rV   r-  render_stringgetattrr   embedded_javascriptr   r   javascript_filesr   r   r   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)  )rO   r2  rF   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_bytess                        r8   renderzRequestHandler.render  s    > 	A?@@@!t!-::6:: 		
d$5r::AACC 	4 	4F3355J 2Z 0 0111//11I /i,)>?? /OOHY$7$78888OOI...,,..J 3  j!1!1222((**I 0i,)>?? 0$$Xi%8%89999$$Y///((**I 3!!$y//222((**I 4""4	??333 	@&&x00B;;z**D;b)E1DK?D 	@++H55H;;z**D;)E1DK?D 	A((33C::j))D;c*U2T$%%[@D 	A--i88I::j))D;*U2T$%%[@D 	L::j))D;*!5!55=TUUKD 	M::j))D;+!6!66>deeLD{{4   r7   rH  c                    g }t                      }|D ]T}t          |          s|                     |          }||vr*|                    |           |                    |           Ud                    d |D                       S )zDefault 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
  c              3   J   K   | ]}d t          j        |          z   dz   V  dS )z<script src="z"" type="text/javascript"></script>Nr   xhtml_escaperL   ps     r8   rP   z2RequestHandler.render_linked_js.<locals>.<genexpr>.  sS       
 
  !!$$%23
 
 
 
 
 
r7   r  is_absolute
static_urlr   r   rE  )rO   rH  pathsunique_pathsr   s        r8   r?  zRequestHandler.render_linked_js  s     uu 	' 	'Dt$$ -t,,<''T"""  &&&ww 
 
 	
 
 
 
 
 	
r7   rG  c                 8    dd                     |          z   dz   S )zDefault 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[
r5  s   
//]]>
</script>rE  )rO   rG  s     r8   rA  zRequestHandler.render_embed_js5  s(     >jj""##$	
r7   r<  c                    g }t                      }|D ]T}t          |          s|                     |          }||vr*|                    |           |                    |           Ud                    d |D                       S )zDefault 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
  c              3   J   K   | ]}d t          j        |          z   dz   V  dS )z<link href="z$" type="text/css" rel="stylesheet"/>NrZ  r\  s     r8   rP   z3RequestHandler.render_linked_css.<locals>.<genexpr>Q  sR       
 
  V0333 71 1
 
 
 
 
 
r7   r^  )rO   r<  ra  rb  r   s        r8   rB  z RequestHandler.render_linked_cssA  s     uu 	' 	'Dt$$ -t,,<''T"""  &&&ww 
 
 
 
 
 
 
 	
r7   rI  c                 8    dd                     |          z   dz   S )zDefault 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">
r5  s	   
</style>rd  )rO   rI  s     r8   rD  zRequestHandler.render_embed_cssW  s      ,ejj.C.CCmSSr7   c                    |                                  }|st          j        d          }|j        j        }|j        j        |k    r%|j        |j        }|j        j        |k    r|j        |j        j        J t          j                            |j        j                  }t          j
        5  |t          j        vr%|                     |          }|t          j        |<   nt          j        |         }ddd           n# 1 swxY w Y   |                    |          }|                                 }|                    |            |j        di |S )zGenerate 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.
        r   Nr6   )get_template_pathsys	_getframef_codeco_filenamef_backosr   dirnamer:   _template_loader_lock_template_loaderscreate_template_loaderloadget_template_namespaceupdategenerate)	rO   r2  rF   template_pathframeweb_fileloadert	namespaces	            r8   r6  zRequestHandler.render_string_  s    ..00 	FM!$$E|/H,*h665<;S ,*h665<;S<+777GOOEL,DEEM1 	I 	IN$DDD44]CCBH0??'9-H	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I 	I KK&&//11	   qz&&I&&&s   /ADDDc                     t          | | j        | j        | j        | j        j        | j        j        | j        | j        | j        	  	        }|	                    | j
                   |S )aB  Returns 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`.
        )	handlerrE   current_userr   _pgettextr`  xsrf_form_htmlreverse_url)r  rE   r  r   	translater  r`  r  r  rv  r[   )rO   r}  s     r8   ru  z%RequestHandler.get_template_namespacey  sj     L*;k#[).(

 

 

	 	!!!r7   rx  c                     | j         j        }d|v r|d         S i }d|v r|d         |d<   d|v r|d         |d<   t          j        |fi |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)rC   ri   r   Loader)rO   rx  ri   rF   s       r8   rs  z%RequestHandler.create_template_loader  sz     #,((-..8## $,L#9F<  H,,#+,A#BF< }77777r7   include_footersc                 :   | j         j        J d                    | j                  }g | _        | j        sd| _        | j        D ]6}|J |                    | j        | j        ||          \  | _        | _        }7| j         j	        dk    rd}t          | d          rE| j                                        D ]+}|                     d|                    d                     ,t          j        d| j        | j                  }| j         j                            || j        |          S | j        D ]}|                    ||          }| j         j	        dk    r| j         j                            |          S t+                      }|                    d           |S )zFlushes 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.
        Nr7   Tr<   r   z
Set-Cookier
  )rE   r_   rE  r   rU   _transformstransform_first_chunkr   r   methodr   r   r   r   OutputStringr   ResponseStartLiner   write_headerstransform_chunkr1  r   
set_result)rO   r  r+  	transformcookie
start_linefutures          r8   flushzRequestHandler.flush  s    |&222+,,$ #	$(D!!-  	(((
 33%t}e_ 	%ME
 |"f,,
 t]++ M".5577 M MFOOL&2E2Ed2K2KLLLL!3B8I4<XXJ<*88DM5   "- J J	!11%II|"f,,|.44U;;;!!$'''r7   c                    | j         rt          d          ||                     |           | j        s| j        dk    r[| j        j        dv rMd| j        vrD|                                  | 	                                rg | _
        |                     d           | j        dv sd| j        cxk    rdk     r1n n.| j
        rJ d	| j        z              |                                  n=d
| j        vr4t          d | j
        D                       }|                     d
|           | j        j        J | j        j                            d           |                     d          }| j        j                                         |                                  d| _         |                                  |                                  |S )aD  Finishes 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``.
        zfinish() called twiceNr   r;   r<   Etag0  )   r  d   zCannot send body with %sContent-Lengthc              3   4   K   | ]}t          |          V  d S rJ   )len)rL   parts     r8   rP   z(RequestHandler.finish.<locals>.<genexpr>  s(      $N$N4SYY$N$N$N$N$N$Nr7   T)r  )rV   r-  r1  rU   r   rE   r  r   set_etag_headercheck_etag_headerr   r   _clear_representation_headerssumr   r_   r`   r  r)  _logrs   _break_cycles)rO   r+  content_lengthr  s       r8   r)  zRequestHandler.finish  s    > 	86777JJu $ 	B!S((L'?::$-//$$&&&))++ ))+D&OOC((( J..3$:K3Q3Q3Q3Qc3Q3Q3Q3Q3Q-  .1BB   224444!66!$$N$N4;M$N$N$N!N!N 0.AAA|&222
 	224888D11&&(((		r7   c                 L    d| _         | j        j                                        S )aN  Take 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)rV   rE   r_   detachre   s    r8   r  zRequestHandler.detach  s"     |&--///r7   c                     d | _         d S rJ   )r[   re   s    r8   r  zRequestHandler._break_cycles  s     r7     c                 V   | j         rYt          j        d           | j        s<	 |                                  n&# t
          $ r t          j        dd           Y nw xY wdS |                                  |                    d          }d|v r1|d         d         }t          |t                    r|j
        r|j
        }|                     ||	           	  | j        |fi | n&# t
          $ r t          j        d
d           Y nw xY w| j        s|                                  dS dS )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   r  r/   )r   z!Uncaught exception in write_error)rU   r   errorrV   r)  r  r^   r   r   rm   r   r   write_errorr   )rO   r   rF   r   rz   s        r8   
send_errorzRequestHandler.send_error$  sv      	MLMMM> U
UKKMMMM  U U UM"DtTTTTTTUF

H%%z*1-I)Y// *I4D *")F333	ND[33F3333 	N 	N 	NM=MMMMMM	N~ 	KKMMMMM	 	s!   9  AAC& & D	D	c                 2   | j                             d          r\d|v rX|                     dd           t          j        |d          D ]}|                     |           |                                  dS |                     d|| j        dz             dS )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_tracebackr  r}   
text/plainzS<html><title>%(code)d: %(message)s</title><body>%(code)d: %(message)s</body></html>)coder0  N)ri   r   r   	tracebackformat_exceptionr1  r)  r   )rO   r   rF   lines       r8   r  zRequestHandler.write_errorJ  s     =.// 	J&4H4HOONL999!2F:4FG ! !

4    KKMMMMMKK<&4<@@A    r7   c                     t          | d          s@|                                 }||| _        n"|                                 | _        | j        sJ | j        S )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.
        _locale)r   get_user_localer  get_browser_locale)rO   locs     r8   r   zRequestHandler.localec  s^     tY'' 	$&&((C"#6688|###|r7   c                     || _         d S rJ   )r  rO   r   s     r8   r   zRequestHandler.localex  s    r7   c                     dS )a  Override 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")``
        Nr6   re   s    r8   r  zRequestHandler.get_user_locale|  s	     tr7   en_USc                    d| j         j        v rJ| j         j        d                             d          }g }|D ]}|                                                    d          }t	          |          dk    r|d                                                             d          r^	 t          |d                                         dd                   }|dk     rt                      n# t          t          f$ r d	}Y nw xY wd
}|dk    r|	                    |d         |f           |r2|
                    d d           d |D             }t          j        | S t          j        |          S )zDetermines the user's locale from ``Accept-Language`` header.

        See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
        zAccept-Language,;r/   zq=r0   Nr   g        g      ?c                     | d         S )Nr/   r6   )pairs    r8   <lambda>z3RequestHandler.get_browser_locale.<locals>.<lambda>  s
    d1g r7   T)keyreversec                     g | ]
}|d          S )r   r6   )rL   r  s     r8   
<listcomp>z5RequestHandler.get_browser_locale.<locals>.<listcomp>  s    333CQ333r7   )rE   headerssplitr   r  
startswithfloatr   r   r   sortr   r   )rO   r   	languageslocaleslanguagepartsscorecodess           r8   r  z!RequestHandler.get_browser_locale  sz   
  444,->?EEcJJIG% 6 6 ((..s33u::>>eAhnn&6&6&A&A$&G&G>$ %eAhnn&6&6qrr&: ; ; 199",,,. %&	2 $ $ $ #$  E199NNE!He#4555 *!5!5tDDD337333z5))z'"""s   #AC''C=<C=c                 b    t          | d          s|                                 | _        | j        S )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  re   s    r8   r  zRequestHandler.current_user  s4    @ t_-- 	9!%!6!6!8!8D!!r7   c                     || _         d S rJ   )r  r  s     r8   r  zRequestHandler.current_user  s    "r7   c                     dS )zrOverride to determine the current user from, e.g., a cookie.

        This method may not be a coroutine.
        Nr6   re   s    r8   r  zRequestHandler.get_current_user  s	    
 tr7   c                 R    |                      dd           | j        j        d         S )zOverride to customize the login URL based on the request.

        By default, we use the ``login_url`` application setting.
        	login_urlz@tornado.web.authenticated)r  rC   ri   re   s    r8   get_login_urlzRequestHandler.get_login_url  s,    
 	[*FGGG(55r7   c                 @    | j         j                            d          S )zOverride 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.
        rx  )rC   ri   r   re   s    r8   ri  z RequestHandler.get_template_path  s     (,,_===r7   c                    t          | d          sQ|                                 \  }}}| j                            dd          }| j                            di           }|dk    rt	          j        |          | _        n|dk    rt          j        d          }d	                    dt	          j        |          t	          j        t          ||                    t          t          t          |                              g          | _        nt          d	|          |?| j        r	d|vrd|d<   | j                            dd          } | j        || j        fi | | j        S )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_versionr0   xsrf_cookie_kwargsr/         |   2zunknown xsrf cookie version %dNr   r  xsrf_cookie_name_xsrf)r   _get_raw_xsrf_tokenri   r   binasciib2a_hexr  ro  urandomrE  r   r   r   r(  r   r  r  )rO   r   token	timestampoutput_versioncookie_kwargsmaskcookie_names           r8   
xsrf_tokenzRequestHandler.xsrf_token  sp   B t]++ 	P(,(@(@(B(B%GUI!]../DaHHN M--.BBGGM""#+#3E#:#:  1$$z!}}#'99 (.. (u)E)EFFSY0011	$ $   !!A>RRR$ 7})L)L46M.1"m//0BGLLT-=OOOOOr7   c                 N   t          | d          s| j                            dd          }|                     |          }|r|                     |          \  }}}nd\  }}}|)d}t          j        d          }t          j                    }|J |J |||f| _        | j        S )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   ri   r   r   _decode_xsrf_tokenro  r  r   r  )rO   r  r  r   r  r  s         r8   r  z"RequestHandler._get_raw_xsrf_token  s     t.// 	?-++,>HHK__[11F =,0,C,CF,K,K)		,<)	}
2 IKK	$$$((($+UI#>D ##r7   r  c                    	 t                               t          |                    }|rt          |                    d                    }|dk    r~|                    d          \  }}}}t          j        t          |                    }t          |t          j        t          |                              }	t          |          }
||	|
fS t          d          d}	 t          j        t          |                    }	n+# t          j
        t          f$ r t          |          }	Y nw xY wt          t          j                              }
||	|
fS # t          $ r t          j        dd           Y dS w xY w)	z_Convert a cookie string into a the tuple form returned by
        _get_raw_xsrf_token.
        r/   r0   |zUnknown xsrf cookie versionz(Uncaught exception in _decode_xsrf_tokenTr  r  )_signed_value_version_rematchr   r(  groupr  r  a2b_hexr   r  Errorr   r   r   debug)rO   r  rN   r   r  mask_strmasked_tokentimestamp_strr  r  r  s              r8   r  z!RequestHandler._decode_xsrf_token5  sr   	$(..tF||<<A 3aggajj//a<<?E||C?P?P<Ax}#+DNN;;D+D(2B4CUCU2V2VWWE #M 2 2I"E944 $$ABBB)$,T&\\::EE 	2 ) ) ) LLEEE)  	,,		22 	$ 	$ 	$MDtTTTT###	$s<   CE E #!D E %D-*E ,D--'E  E98E9c                    |                      dd          p=| j        j                            d          p| j        j                            d          }|st	          dd          |                     |          \  }}}|                                 \  }}}|st	          dd          t          j        t          |          t          |                    st	          dd          dS )	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  NzX-XsrftokenzX-Csrftoken  z"'_xsrf' argument missing from POSTz#'_xsrf' argument has invalid formatz(XSRF cookie does not match POST argument)
r   rE   r  r   rm   r  r  hmaccompare_digestr   )rO   input_tokenr  r  expected_tokens        r8   check_xsrf_cookiez RequestHandler.check_xsrf_cookieY  s    2 gt,, 7|#''667|#''66 	
  	GC!EFFF--k::5!#7799>1 	HC!FGGG"4;;^0D0DEE 	MC!KLLL	M 	Mr7   c                 @    dt          j        | j                  z   dz   S )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"/>)r   r[  r  re   s    r8   r  zRequestHandler.xsrf_form_html  s)     8!$/223	
r7   include_hostc                    |                      dd           | j                            dt                    j        }|t          | dd          }|r| j        j        dz   | j        j        z   }nd}| || j        |fi |z   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_pathr`  static_handler_classNr  Fz://r
  )	r  ri   r   StaticFileHandlermake_static_urlr7  rE   protocolhost)rO   r   r  rF   get_urlbases         r8   r`  zRequestHandler.static_url  s    . 	]L999-##"$5
 

 	 "4??L 	<(504<3DDDDDggdmT<<V<<<<r7   this featurefeaturec                 n    | j         j                            |          st          d|d|          dS )z<Raises an exception if the given app setting is not defined.zYou must define the 'z%' setting in your application to use N)rC   ri   r   r  )rO   r   r  s      r8   r  zRequestHandler.require_setting  sL    (,,T22 	)+/44:  	 	r7   c                 (     | j         j        |g|R  S )z$Alias for `Application.reverse_url`.)rC   r  )rO   r   rj   s      r8   r  zRequestHandler.reverse_url  s     +t+D848888r7   c                     t          j                    }| j        D ]}|                    |           d|                                z  S )a  Computes 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.
        z"%s")hashlibsha1r   rv  	hexdigest)rO   hasherr  s      r8   compute_etagzRequestHandler.compute_etag  sM     & 	  	 DMM$((****r7   c                 b    |                                  }||                     d|           dS dS )zSets 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.
        Nr  )r#  r   )rO   etags     r8   r  zRequestHandler.set_etag_header  s=       ""OOFD))))) r7   c           	      j   t          | j                            dd                    }t          j        dt          | j        j                            dd                              }|r|sdS d}|d         dk    rd}n3d	t          d
t          fd}|D ]} ||           ||          k    rd} n|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.
        r  r
  s   \*|(?:W/)?"[^"]*"If-None-MatchFr      *TxrG   c                 D    |                      d          r
| dd          n| S )Ns   W/r0   r  )r)  s    r8   valz-RequestHandler.check_etag_header.<locals>.val  s%     !U 3 3:quu:r7   )r   r   r   r   findallrE   r  r   )rO   computed_etagetagsr   r,  r%  s         r8   r  z RequestHandler.check_etag_header  s    " T]..vr::;; 
!4(<(@(@RT(U(U#V#V
 
  	E 	58tEE;u ; ; ; ; ;   3t99M 2 222 EE 3 r7   
transformsOutputTransformc                 .   K   | _         	  j        j         j        vrt	          d          t           j                  sF	  j                                         n+# t          j	        $ r}t	          dd|z            |d}~ww xY w fd|D              _
         fd|                                D              _         j        j        dvr3 j        j                            d          r                                                                   }|| d{V } j        t'           j        d            j        rdS t           j                  r*	  j        j         d{V  n# t,          j        $ r Y dS w xY wt1            j        j                                                  } | j
        i  j        }|| d{V } j        r j        s                                  dS dS dS # t8          $ r}	                      |           n&# t8          $ r t=          j        d	d
           Y nw xY wd}n# d}w xY w j        9 j                                         s& j        !                    d           Y d}~dS Y d}~dS Y d}~dS d}~ww xY w)z7Executes this request with the given output transforms.rl   r   zInvalid body: %sNc                 :    g | ]}                     |          S r6   r   )rL   argrO   s     r8   r  z+RequestHandler._execute.<locals>.<listcomp>  s'    HHHCd22377HHHr7   c                 F    i | ]\  }}|                     ||           S )r   r4  )rL   r  r   rO   s      r8   
<dictcomp>z+RequestHandler._execute.<locals>.<dictcomp>  s?          7=14'''22     r7   )r;   r<   rA   xsrf_cookieszException in exception handlerTr  )"r  rE   r  rB   rm   ru   rc   _parse_bodyr   HTTPInputError	path_argsrZ   path_kwargsrC   ri   r   r  rq   rX   r   rV   rv   r   ry   r7  lowerrW   r)  r  _handle_request_exceptionr   r  rw   r  )rO   r0  rj   rF   eresultr  s   `      r8   _executezRequestHandler._execute  ss      &>	7|"$*@@@nn$ ,DN;; HHL,,..... H H H#C);a)?@@aGH IHHH4HHHDN       AG     D
 |" +   "+//??	
 &&(((\\^^F!%$0 343H$OOO~ '77 
,3333333331   FF T4<#6#<#<#>#>??FVT^@t/?@@F!%       	7 	7 	7..q1111 O O O>NNNNNNO $09N9S9S9U9U0 %00666666666	 100000000000	7s   6G2 A G2 B,B  BB=G2 G2 E, +G2 ,E?;G2 >E??A-G2 2
J=HH< H63H<5H66H<9J<I  =JJc                     t                      )zImplement this method to handle streamed request data.

        Requires the `.stream_request_body` decorator.

        May be a coroutine for flow control.
        NotImplementedError)rO   r+  s     r8   data_receivedzRequestHandler.data_receivedI  s     "###r7   c                 :    | j                             |            dS )zLogs 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)rC   log_requestre   s    r8   r  zRequestHandler._logR  s!     	$$T*****r7   c                 l    d                     | j        j        | j        j        | j        j                  S )Nz
{} {} ({}))r   rE   r  uri	remote_ipre   s    r8   _request_summaryzRequestHandler._request_summary[  s2    ""LLL"
 
 	
r7   r?  c                    t          |t                    r| j        s | j        |j          d S 	  | j        t          j                      n&# t          $ r t          j
        dd           Y nw xY w| j        rd S t          |t                    r/|                     |j        t          j                               d S |                     dt          j                               d S )NzError in exception loggerTr  r  )r   FinishrV   r)  rj   log_exceptionrj  r  r  r   r  rm   r  r   )rO   r?  s     r8   r>  z(RequestHandler._handle_request_exceptionb  s    a   	> %QV$$F	FD/// 	F 	F 	F M5EEEEEE	F > 	 Fa## 	:OOAMCLNNOCCCCCOOC#,..O99999s   A  A.-A.typzOptional[Type[BaseException]]tbc                 (   t          |t                    rJ|                                }|r2d}|j        |                                 |g}t          j        |g|R   dS dS t          j        d|                                 | j	        |||f           dS )aK  Override 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: %szUncaught exception %s
%rr  N)
r   rm   get_messager   rK  r   warningr   r  rE   )rO   rO  r   rP  log_messager   rj   s          r8   rN  zRequestHandler.log_exceptionx  s     eY'' 	++--K /$)4+@+@+B+BKP......./ /
 M+%%''ub)	     r7   rL  UIModulec                 *     dt           f fd}|S )NrG   c                      t          d          si _        j        vr           j        <    j                 j        | i |}t          |          S )Nr4  )r   r4  rW  r   )rj   rF   renderedrL  r   rO   s      r8   rW  z)RequestHandler._ui_module.<locals>.render  sn    4!233 *')$4///-3VD\\$T*8t+D18$I&IIHH%%%r7   )r   )rO   r   rL  rW  s   ``` r8   
_ui_modulezRequestHandler._ui_module  s;    	&s 	& 	& 	& 	& 	& 	& 	& 	& r7   r  c                       fdS )Nc                       g| R i |S rJ   r6   )rj   rF   r  rO   s     r8   r  z+RequestHandler._ui_method.<locals>.<lambda>  s!    vvd'DT'D'D'DV'D'D r7   r6   )rO   r  s   ``r8   rK   zRequestHandler._ui_method  s    DDDDDDr7   c                 B    g d}|D ]}|                      |           d S )N)Content-EncodingzContent-Languager}   )r   )rO   r  hs      r8   r  z,RequestHandler._clear_representation_headers  s@     KJJ 	! 	!Aa    	! 	!r7   rG   NrJ   T)NNr   N)r  N)Nr  N)FN)F)r  )r  )r  )r3   r4   r5   __doc__rB   r$   r   __annotations__rr  	threadingLockrq  r   compiler   _stream_request_bodyr  r;  r<  r   HTTPServerRequestr    rT   rf   rb   propertyr   ri   ro   headr   postdeletepatchputoptionsr"   r#   rq   rs   ra   r^   r   r(  r   r   _HeaderTypesr   r   r   r   r   r,   r   r   _ARG_DEFAULTr2   r!   r%   r   r   r   r   r   r   r   r   r   r   r   Morselr   r  r   r  r  r  r  set_secure_cookier  r   get_secure_cookier#  get_secure_cookie_key_versionr*  r  r1  rW  r'   r?  rA  rB  rD  r6  ru  r   
BaseLoaderrs  r  r)  r   IOStreamr  r  r  r  r   r   Localesetterr  r  r  r  r  ri  r  r  r  r  r  r`  r  r  r#  r  r  rA  rE  r  rK  BaseExceptionr>  r-   rN  r)   r&   rY  rK   r  __classcell__rc   s   @r8   r:   r:      s        	 	*uS#X    *IN,,","*-D"E"E  KIK""" +" 	"
 
" " " " " "@    J& )$sCx. ) ) ) X)3 # $     !D
C D"F!E
C#G)D/2    "   6 6 6 6&/ / / /   J Jc J8C= JD J J J J&!C ! ! ! !@s @< @D @ @ @ @Cs C< CD C C C C$ $ $ $ $ $ %"*%ABB< C    0   s 4 3    X 6BRV "3KO	   X
 6: "&/3	#   X 8D	P PP tS"334P 	P
 
#P P P P$H H# Hd Hd3i H H H H  c C  PS    X 6BRV "3KO	   X
 6: "&/3	#   X 8D	U UU tS"334U 	U
 
#U U U U&M Ms M4 M49 M M M M  s S  QT    X 6BRV "3KO	   X
 6: "&/3	#   X 8D	V VV tS"334V 	V
 
#V V V V&N N ND NDI N N N N   tS"334 S$u+%&	
  
#    HL !%c4;&6!7@D	c    U (3- 3    ( $c4<#667 $ $ $ X$
 s S S    X  s T Xc]    X s Xc] hsm    " !%DH(,Q "&"&Q Q QQ S%Z Q 	Q
 %uh.? ?@AQ Q uoQ #Q Q Q 3-Q Q 
Q Q Q QfC C C C C C C8.# .$ . . . .F )+!%+
 +
+
 S%Z +
 uo	+

 #+
 +
 
+
 +
 +
 +
Z * MQ
 

 %c5j 1
<DSM
	
 
 
 
:  $ %)%
 %
%
 }%
 	%

 c]%
 
%%
 %
 %
 %
N * 150 00 (0	#0 0 0 0, %B! JN #'9A#	   ()5eT!12 )t ) ) ) )@I!C I!3 I!> I! I! I! I!V
# 
3 
 
 
 
.

 

E 

 

 

 


8C= 
S 
 
 
 
,T(5/ Te T T T T'3 '# '% ' ' ' '4S#X    .8C 8H<O 8 8 8 8*0 0T 0n 0 0 0 0d7 7HU3t+;%<= 7 7 7 7 7r0) 0 0 0 0   
$ $c $3 $4 $ $ $ $Ls c d    2 -    X( ]GN1 d    ]'.*?!@    # ## #GN<Q # # # #6 !"c !" !" !" X!"F ## #$ # # # ##    6s 6 6 6 6>8C= > > > > 7 E 7  7  7  X7 r$U8C=%+F%G $ $ $ $6"$"$	x}huox>	?"$ "$ "$ "$H$M $M $M $ML
 
 
 
 
( 9=$= $=$='/~$=HK$=	$= $= $= $=L C # 4    9 9C 9C 9 9 9 9+hsm + + + +	* 	* 	* 	*&4 & & & &PC701C7:?C7KPC7	C7 C7 C7 C7J$5 $Xio-F $ $ $ $+ + + +
# 
 
 
 
:= :T : : : :,, & ]#	
 
   :	s 	D,< 	#s(AS 	 	 	 	E#s(!3 Ec8J E E E E! ! ! ! ! ! ! !r7   r:   _RequestHandlerType)boundclsrG   c                 ^    t          | t                    st          d|           d| _        | S )a  Apply 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
issubclassr:   r   rf  r~  s    r8   stream_request_bodyr    s5    * c>** LEsKKK#CJr7   c                 Z    t          | t                    st          d|           | j        S )Nr  r  r  s    r8   ru   ru     s/    c>** LEsKKK##r7   r  .c                      t          j                   dt          dt          t          d                  f fd            }|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.
    rO   rG   Nc                 F   | j         j                            d          rv| j         j        dv rY| j         j                            d          }|r7| j         j        r|d| j         j        z   z  }|                     |d           d S nt          d           | g|R i |S Nr   r  ?Tr$    )rE   r   endswithr  rstripqueryr*  rm   rO   rj   rF   rI  r  s       r8   wrapperzremoveslash.<locals>.wrapper  s     <%%c** 		%|"o55l'..s33  |) 8sT\%777MM#M6664	   nn$vd,T,,,V,,,r7   	functoolswrapsr:   r"   r#   r  r  s   ` r8   removeslashr    sX     _V--	)D/	"- - - - - - Nr7   c                      t          j                   dt          dt          t          d                  f fd            }|S )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.
    rO   rG   Nc                     | j         j                            d          sc| j         j        dv rF| j         j        dz   }| j         j        r|d| j         j        z   z  }|                     |d           d S t          d           | g|R i |S r  )rE   r   r  r  r  r*  rm   r  s       r8   r  zaddslash.<locals>.wrapper  s     | ))#.. 	!|"o55l'#-<% 43!333CcT222tC.. vd,T,,,V,,,r7   r  r  s   ` r8   addslashr    sX     _V--	)D/	"- - - - - - Nr7   c            	            e Zd ZdZ	 ddddee         ddf fdZdedef fd	Zd
e	de
j        de	dee
j                 f fdZ xZS )_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.
    NrC   rD   rulesrG   c                     t          |t                    sJ || _        t                                          |           d S rJ   )r   rD   rC   rS   rT   )rO   rC   r  rc   s      r8   rT   z_ApplicationRouter.__init__  sA     +{33333&r7   rulec                     t                                          |          }t          |j        t          t
          f          rt          | j        |j                  |_        |S rJ   )rS   process_ruler   targetr.  tupler  rC   )rO   r  rc   s     r8   r  z_ApplicationRouter.process_rule  sT    ww##D))dkD%=11 	, $+ DK r7   r  rE   target_paramsc                     t          |          r)t          |t                    r | j        j        ||fi |S  t                      j        ||fi |S rJ   )r   r  r:   rC   get_handler_delegaterS   get_target_delegate)rO   r  rE   r  rc   s       r8   r  z&_ApplicationRouter.get_target_delegate&  ss     6?? 	z&.AA 	84#8 #0   +uww*67LLmLLLr7   rJ   )r3   r4   r5   ra  r"   r   rT   r   r  r    r   rg  HTTPMessageDelegater  rz  r{  s   @r8   r  r  
  s          HL   ( 19)1D 	            $      MM$,$>MQTM	(.	/M M M M M M M M M Mr7   r  c                   <   e Zd ZdZ	 	 	 d+dee         dee         deeed                           de	ddf
d	Z
	 d,ej        ej        j        dd
ddedee         dej        dedee         dede	defdZdededdfdZded         ddfdZde	ddfdZde	ddfdZdej        deed                  fdZdej        de	ddfd Z	 	 	 d+dej        d!ee         d"eeee	f                  d#eee                   d$eeee f                  ddfd%Z!d&ed'e	defd(Z"d)eddfd*Z#dS )-rD   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_hostr0  r1  ri   rG   c                 <   |Qg | _         |                    d          s|                    d          r| j                             t                     n|| _         || _        || _        t          t          t          d| _	        i | _
        |                     |                    di                      |                     |                    di                      | j                            d          r| j        d         }t          |pg           }|                    dd          }|                    d	t                    }|                    d
i           }||d<   t          j        |          dz   ddfD ]}	|                    d|	||f           | j                            d          rl| j                            dd           | j                            dd           | j                            dd           | j                            dd           t'          | |          | _        t'          | t+          t-                      | j                  g          | _        | j                            d          rddlm}
 |
                                 d S d S )Ncompress_responsegzip)linkifyr  Templater]   rY   r  static_url_prefix/static/r  static_handler_argsr   z(.*)z/(favicon\.ico)z/(robots\.txt)r   r  
autoreloadTcompiled_template_cacheFstatic_hash_cacher  )r  )r0  r   r   GZipContentEncodingr  ri   _linkify_xsrf_form_htmlTemplateModuler]   rY   _load_ui_modules_load_ui_methodsr.  r  r   r   insert
setdefaultr  wildcard_routerr   r   default_routerr   r  start)rO   r  r  r0  ri   r   r  r  r  patternr  s              r8   rT   zApplication.__init__  s     DO||/00 <HLL4H4H <&&':;;;(DO( -&
 

 hll<<<===hll<<<====]++ 	Y=/DHN++H (-@* M M#+<<&(9$ $  #+,,/Db"I"I*.'	+,,w6"! Y Y
 G-ACV#WXXXX=W%% 	>M$$\4888M$$%>FFFM$$%8%@@@M$$%6===1$AA04
d&:;;<
 

 =\** 	******	 	r7   F)familybacklogflags
reuse_portportaddressr  r  r  r  rF   c                V    t          | fi |}|                    ||||||           |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``.
        )r  r  r  r  r  )r
   listen)	rO   r  r  r  r  r  r  rF   servers	            r8   r  zApplication.listen  sN    B D++F++! 	 	
 	
 	
 r7   host_patternhost_handlersc                    t          |          }t          |t          | |                    }| j        j                            d|           | j        2| j                            t          | |j
                  |fg           dS dS )zAppends 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)r   r   r  r  r  r  r  r  	add_rulesr   r  )rO   r  r  host_matcherr  s        r8   add_handlerszApplication.add_handlers  s     #<00L"4T="I"IJJ!((T222( **$T<+DEE}UV     )(r7   transform_classc                 :    | j                             |           d S rJ   )r0  r   )rO   r  s     r8   add_transformzApplication.add_transform  s    /////r7   methodsc                    t          t          j                  r0|                     fdt	                    D                        d S t          t
                    rD ]}|                     |           d S                                 D ]X\  }}|                    d          s>t          |d          r.|d         	                                |d         k    r
|| j
        |<   Yd S )Nc                 2    i | ]}|t          |          S r6   r7  )rL   rM   r  s     r8   r7  z0Application._load_ui_methods.<locals>.<dictcomp>  %    "P"P"Pa1ggq&9&9"P"P"Pr7   r  __call__r   )r   types
ModuleTyper  dirr.  rZ   r  r   r=  rY   )rO   r  rN   r   fns    `   r8   r  zApplication._load_ui_methods  s   gu/00 	/!!"P"P"P"P3w<<"P"P"PQQQQQ&& 
	/ ) )%%a(((() ) $MMOO / /b,,/J/// Q4722,.DOD)/ /r7   rR   c                    t          t          j                  r0|                     fdt	                    D                        d S t          t
                    rD ]}|                     |           d S t          t                    sJ                                 D ]5\  }}	 t          |t                    r
|| j
        |<   &# t          $ r Y 2w xY wd S )Nc                 2    i | ]}|t          |          S r6   r  )rL   rM   rR   s     r8   r7  z0Application._load_ui_modules.<locals>.<dictcomp>	  r  r7   )r   r  r  r  r  r.  r  rZ   r  rU  r]   r   )rO   rR   rN   r   r~  s    `   r8   r  zApplication._load_ui_modules
	  s   gu/00 	!!"P"P"P"P3w<<"P"P"PQQQQQ&& 
	 ) )%%a(((() ) gt,,,,,$]]__  	c!#x00 403-    D	 s   .C
CCrE   c                 T    |                      |          }|                                S rJ   )find_handlerexecute)rO   rE   
dispatchers      r8   r  zApplication.__call__	  s)     &&w//
!!###r7   _HandlerDelegatec                 @   | j                             |          }|t          d|          S | j                            d          r;|                     || j        d         | j                            di                     S |                     |t          ddi          S )Nr  default_handler_classdefault_handler_argsr   r  )r  r  r+   ri   r   r  ErrorHandler)rO   rE   rF   routes       r8   r  zApplication.find_handler 	  s     #0099*E222=455 	,,56!!"8"==   ((,PS@TUUUr7   target_classtarget_kwargsr;  r<  c                 *    t          | |||||          S )ae  Returns `~.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  )rO   rE   r  r  r;  r<  s         r8   r  z Application.get_handler_delegate0	  s#    $  '<	;
 
 	
r7   r   rj   c                 T     | j         j        |g|R  }||S t          d|z            )a3  Returns 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  r  KeyError)rO   r   rj   reversed_urls       r8   r  zApplication.reverse_urlF	  sA     7t*6tCdCCC#3d:;;;r7   r  c                    d| j         v r | j         d         |           dS |                                dk     rt          j        }n1|                                dk     rt          j        }nt          j        }d|j                                        z  } |d|                                |                                |           dS )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   r  g     @@z%d %s %.2fms)	ri   r   r   inforS  r  rE   request_timerK  )rO   r  
log_methodr  s       r8   rG  zApplication.log_requestU	  s     T]**)DM.)'222F#%%#JJ!!C''#+JJ#)J < < > >>
  $$&&		
 	
 	
 	
 	
r7   r  rJ   )$r3   r4   r5   ra  r"   r   r   r%   r)   r    rT   socket	AF_UNSPECr   netutil_DEFAULT_BACKLOGr(  AddressFamilyr   r
   r  r  r  r  r  r   rg  r#   r  r  r:   r   r   r  r  rG  r6   r7   r8   rD   rD   1  s       P Ph )-&*>B	6 69%6 sm6 T$'8"9:;	6
 6 
6 6 6 6v "&*
 (.'77# * * ** #*
 $* * }* * * 
* * * *X Y 4     0T2C-D 0 0 0 0 0/ / / / / /     $1$	)D/	"$ $ $ $V1V=@V	V V V V( 37+/26
 
+
 >*
  S#X/	

 DK(
 d3:./
 

 
 
 
,< <C <C < < < <
> 
d 
 
 
 
 
 
r7   rD   c                   N   e Zd Zdedej        dee         dee	e
ef                  deee                  dee	e
ef                  ddfd	Zd
eej        ej        f         dej        deed                  fdZdedeed                  fdZddZddZdeed                  fdZdS )r  rC   rE   handler_classhandler_kwargsr;  r<  rG   Nc                     || _         |j        | _        || _        || _        |pi | _        |pg | _        |pi | _        g | _        t          | j                  | _	        d S rJ   )
rC   r_   rE   r  r  r;  r<  chunksru   r  )rO   rC   rE   r  r  r;  r<  s          r8   rT   z_HandlerDelegate.__init__p	  sj     '!,*,2"b&,"#;D<N#O#O   r7   r  r  c                 l    | j         r,t                      | j        _        |                                 S d S rJ   )r  r   rE   rv   r  )rO   r  r  s      r8   headers_receivedz!_HandlerDelegate.headers_received	  s0    
 # 	"(.DL%<<>>!tr7   datac                 |    | j         r| j                            |          S | j                            |           d S rJ   )r  r  rE  r  r   )rO   r   s     r8   rE  z_HandlerDelegate.data_received	  s>    # 	<--d333Kt$$$4r7   c                     | j         rt          | j        j        d            d S d                    | j                  | j        _        |                                  d S )Nr7   )r  r   rE   rv   rE  r  bodyr  re   s    r8   r)  z_HandlerDelegate.finish	  sS    # 	.t|/H$OOOOO !$ 5 5DLLLNNNNNr7   c                 X    | j         r| j                                         d S d | _        d S rJ   )r  r  ra   r  re   s    r8   ra   z$_HandlerDelegate.on_connection_close	  s2    # 	L,,.....DKKKr7   c                      j         j                            dd          sZt          j        5  t          j                                        D ]}|                                 	 d d d            n# 1 swxY w Y    j         j                            dd          s9 j         j                            dt                    }|                                   j	         j          j
        fi  j         _         fd j         j        D             } j        rt                       j        _        t#          j          j        j        |g j        R i  j                  }|                    d             j        j        S )Nr  Tr  r  c                 0    g | ]} |j                   S r6   )rE   )rL   r|  rO   s     r8   r  z,_HandlerDelegate.execute.<locals>.<listcomp>	  s#    KKK!aaooKKKr7   c                 *    |                                  S rJ   )r@  )fs    r8   r  z*_HandlerDelegate.execute.<locals>.<lambda>	  s    

 r7   )rC   ri   r   r:   rq  rr  r   resetr  r  rE   r  r  r0  r  r   rX   r	   convert_yieldedrA  r;  r<  add_done_callback)rO   r{  r  r0  futs   `    r8   r  z_HandlerDelegate.execute	  s    (,,-FMM 	#5 # #,>EEGG # #FLLNNNN## # # # # # # # # # # # # # # (,,-@$GG 	)#'#3#<#@#@&(9$ $  !&&((()t)dl
 
.2.A
 
 LKKKt/?/JKKK
# 	5,2HHDL) !!DL!*Rt~RRRAQRR
 
 	22333 |,,s   6A11A58A5r_  )r3   r4   r5   rD   r   rg  r)   r:   r"   r   r   r    r%   r   rT   r!   RequestStartLiner  r   r#   r  rE  r)  ra   r  r6   r7   r8   r  r  o	  sf       P P +P N+	P
 !c3h0P DK(P d3:./P 
P P P P&(3X5OOP % 
)D/	"	   % HYt_,E          #-)D/2 #- #- #- #- #- #-r7   r  c                       e Zd ZdZ	 	 ddedee         dededdf
d	Ze	dee         fd
            Z
dee         fdZdefdZdS )rm   a  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.
    r  Nr   rT  rj   rF   rG   c                 f    || _         || _        || _        |                    dd           | _        d S )Nr   )r   _log_messagerj   r   r   )rO   r   rT  rj   rF   s        r8   rT   zHTTPError.__init__	  s4     ''	jj400r7   c                 b    | j         r"| j        s| j                             dd          S | j         S )zF
        A backwards compatible way of accessing log_message.
        %z%%)r  rj   replacere   s    r8   rT  zHTTPError.log_message	  s:    
  	8TY 	8$,,S$777  r7   c                 J    | j         r| j        r| j         | j        z  S | j         S rJ   )r  rj   re   s    r8   rR  zHTTPError.get_message	  s/     	1 	1$ty00  r7   c                     d| j         | j        p$t          j                            | j         d          fz  }|                                 }|r|dz   |z   dz   S |S )NzHTTP %d: %sr   z ())r   r   r   r   r   rR  )rO   r0  rT  s      r8   __str__zHTTPError.__str__	  sk    KN8-11$2BINN#
 
 &&(( 	T>K/#55Nr7   )r  N)r3   r4   r5   ra  r(  r"   r   r    rT   rh  rT  rR  r  r6   r7   r8   rm   rm   	  s         0 %)
1 
1
1 c]
1 	
1
 
1 

1 
1 
1 
1 !Xc] ! ! ! X!!Xc] ! ! ! !
	 	 	 	 	 	 	r7   rm   c                       e Zd ZdZdS )rM  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)r3   r4   r5   ra  r6   r7   r8   rM  rM  
  s         0 	Dr7   rM  c                   ,     e Zd ZdZdeddf fdZ xZS )r   zException 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_namerG   Nc                 `    t                                          dd|z             || _        d S )Nr   zMissing argument %s)rS   rT   r  )rO   r  rc   s     r8   rT   zMissingArgumentError.__init__+
  s.    3h>??? r7   )r3   r4   r5   ra  r   rT   rz  r{  s   @r8   r   r   "
  sU         ! ! ! ! ! ! ! ! ! ! ! !r7   r   c                   2    e Zd ZdZdeddfdZddZddZdS )	r  zBGenerates an error response with ``status_code`` for all requests.r   rG   Nc                 0    |                      |           d S rJ   )r   )rO   r   s     r8   rb   zErrorHandler.initialize3
  s    $$$$$r7   c                 *    t          | j                  rJ   )rm   r   re   s    r8   rq   zErrorHandler.prepare6
  s    )***r7   c                     d S rJ   r6   re   s    r8   r  zErrorHandler.check_xsrf_cookie9
  r   r7   r_  )r3   r4   r5   ra  r(  rb   rq   r  r6   r7   r8   r  r  0
  sd        LL%c %d % % % %+ + + +     r7   r  c                   <    e Zd ZdZddededdfdZded	eddfd
ZdS )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$  rG   Nc                 "    || _         || _        d S rJ   )_url
_permanent)rO   r   r$  s      r8   rb   zRedirectHandler.initializea
  s    	#r7   rj   rF   c                      | j         j        |i |}| j        j        r>t	          j        |t          t	          j        | j        j                                      }|                     || j	                   d S )Nr  )
r#  r   rE   r   r   
url_concatr.  	qs_to_qslr*  r$  )rO   rj   rF   to_urls       r8   r   zRedirectHandler.gete
  sx    !!42622<' 	(X'(DEEFF F 	f88888r7   r`  )	r3   r4   r5   ra  r   r   rb   r    r   r6   r7   r8   r!  r!  @
  sv         @$ $c $d $d $ $ $ $9 9 9 9 9 9 9 9 9r7   r!  c                      e Zd ZdZdZi Z ej                    Zd)de	de
e	         ddfdZed*d            Zde	ded         fd	Zd+de	deddfdZde
e	         fdZd*dZdefdZede	de	de	fd            Zde	de	de
e	         fdZe	 d,de	de
e         de
e         deeddf         fd            Zede	de	fd            Zdej        fdZdefdZde
e j                  fdZ!de	fdZ"de	ddfdZ#de	de
e j                  de	defd Z$e	 d+d!e%e	e&f         de	d"ede	fd#            Z'd$e	de	fd%Z(ed!e%e	e&f         de	de
e	         fd&            Z)ed'e	de
e	         fd(            Z*dS )-r  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_filenamerG   c                 "    || _         || _        d S rJ   )rootr*  )rO   r   r*  s      r8   rb   zStaticFileHandler.initialize
  s    	 0r7   c                 T    | j         5  i | _        d d d            d S # 1 swxY w Y   d S rJ   )_lock_static_hashesr  s    r8   r	  zStaticFileHandler.reset
  sv    Y 	$ 	$!#C	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$s   !!c                 0    |                      |d          S )NF)include_body)r   rO   r   s     r8   ri  zStaticFileHandler.head
  s    xx5x111r7   Tr1  c                 H  K   |                      |          | _        ~|                     | j        | j                  }|                     | j        |          | _        | j        d S |                                 | _        |                                  | 	                                r| 
                    d           d S d }| j        j                            d          }|rt          j        |          }|                                 }|r|\  }}||dk     r||z  }|dk     rd}|||k    s|||k    s|dk    rF| 
                    d           |                     dd           |                     dd|            d S |||k    r|}||p||pdz
  k    r?| 
                    d	           |                     dt          j        |||                     nd x}}||||z
  }	n||}	n
|||z
  }	n|}	|                     d
|	           |r|                     | j        ||          }
t)          |
t*                    r|
g}
|
D ]I}	 |                     |           |                                  d {V  3# t0          j        $ r Y  d S w xY wd S | j        j        dk    sJ d S )Nr  Ranger   i  r}   r  zContent-Rangezbytes */   r  r<   )parse_url_pathr   get_absolute_pathr,  validate_absolute_pathabsolute_pathget_modified_timemodifiedset_headersshould_return_304r   rE   r  r   r   _parse_request_rangeget_content_sizer   _get_content_rangeget_contentr   r   r1  r  r   ry   r  )rO   r   r1  r9  request_rangerange_headersizer  endr  contentr+  s               r8   r   zStaticFileHandler.get
  s2     ''--	..ty$)DD!88MRR%F..00!!## 	OOC   F|+//88 	H %9,GGM$$&& "	&JE3 UQYY199E!d]]s5C<< $$$===1BD1B1BCCC3:: 
 t
333$$$#X%@T%R%R   EC 5[NN_ NN!E\NN!N(.999 	1&&t'95#FFG'5)) $")   JJu%%%**,,&&&&&&&&1   FFF	  <&&000000s   /I77J
Jc                 \    | j         J |                     | j                   }|sdS d| dS )a  Sets 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
        N")r9  _get_cached_version)rO   version_hashs     r8   r#  zStaticFileHandler.compute_etag  sG     !---//0BCC 	4"<""""r7   c                 t   |                      dd           |                                  | j        |                      d| j                   |                                 }|r|                      d|           |                     | j        | j        |          }|dk    r~|                      dt          j                            t          j        j	                  t          j
        |          z              |                      d	d
t          |          z              |                     | j                   dS )z]Sets the content and caching headers on the response.

        .. versionadded:: 3.1
        zAccept-Rangesr   NzLast-Modifiedr}   r   Expires)secondszCache-Controlzmax-age=)r   r  r;  get_content_typeget_cache_timer   r   r   r   r   r   r   set_extra_headers)rO   content_type
cache_times      r8   r<  zStaticFileHandler.set_headers&  s   
 	111=$OOOT];;;,,.. 	:OONL999((DM<PP
>>OO!%%h&7&;<<$Z8889  
 OOOZ#j//-IJJJty)))))r7   c                    | j         j                            d          r|                                 S | j         j                            d          }|t	 t          j                            |          }n# t          $ r Y dS w xY w|j        %|	                    t          j        j                  }| j        J || j        k    rdS dS )zgReturns True if the headers indicate that we should return 304.

        .. versionadded:: 3.1
        r'  zIf-Modified-SinceNF)tzinfoT)rE   r  r   r  emailutilsparsedate_to_datetimer  rT  r  r   r   r   r;  )rO   	ims_valueif_sinces      r8   r=  z#StaticFileHandler.should_return_304@  s     <##O44 	,))+++ L(,,-@AA	  ;<<YGG   uu&#++83D3H+II=,,,4=((tus   A6 6
BBr,  c                     t           j                            t           j                            ||                    }|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
        )ro  r   abspathrE  )r~  r,  r   r[  s       r8   r7  z#StaticFileHandler.get_absolute_pathY  s,     '//"',,tT":":;;r7   r9  c                 r   t           j                            |          }|                    t           j        j                  s|t           j        j        z  }|t           j        j        z                       |          st          dd| j                  t           j                            |          r| j        | j	        j                            d          sU| j	        j                            d          rt          dd          | 
                    | j	        j        dz   d           dS t           j                            || j                  }t           j                            |          st          d	          t           j                            |          st          dd
| 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  r  z%s is not a file)ro  r   r[  r  sepr  rm   isdirr*  rE   r*  rE  existsisfile)rO   r,  r9  s      r8   r8  z(StaticFileHandler.validate_absolute_pathj  sz   0 wt$$}}RW[)) 	  BGKD +77== 	RC!EtyQQQ7=='' 	OD,A,M <$--c22 <$//55  $L   dl/#5FFFtGLL8MNNMw~~m,, 	!C.. w~~m,, 	@C!3TY???r7   r[  r  rE  c              #   4  K   t          |d          5 }||                    |           |||pdz
  }nd}	 d}|||k     r|}|                    |          }|r||t          |          z  }|V  n||dk    sJ 	 ddd           dS U# 1 swxY w Y   dS )aZ  Retrieve 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
        rbNr   Ti   )openseekreadr  )r~  r[  r  rE  file	remaining
chunk_sizer+  s           r8   rA  zStaticFileHandler.get_content  s     $ '4   	D 		%   5:A.		 	&
(Y-C-C!*J		*--  ,!SZZ/	KKKK ,(A~~~~'	 	 	 	 	 	 	 		 	 	 	 	 	 	 	 	 	s   A,BBBBc                    |                      |          }t          j                    }t          |t                    r|                    |           n|D ]}|                    |           |                                S )zReturns 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
        )rA  r  sha512r   r   rv  r!  )r~  r[  r   r"  r+  s        r8   get_content_versionz%StaticFileHandler.get_content_version  s     w''!!dE"" 	%MM$ % %e$$$$!!!r7   c                 ~    | j         J t          | d          st          j        | j                   | _        | j        S )N_stat_result)r9  r   ro  statrm  re   s    r8   _statzStaticFileHandler._stat  sA    !---t^,, 	< "(: ; ;D  r7   c                 8    |                                  }|j        S )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.
        )ro  st_size)rO   stat_results     r8   r?  z"StaticFileHandler.get_content_size  s     jjll""r7   c                     |                                  }t          j                            t          |j                  t          j        j                  }|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.
        )ro  r   fromtimestampr(  st_mtimer   r   )rO   rr  r;  s      r8   r:  z#StaticFileHandler.get_modified_time  sH     jjll $22$%%x'8'<
 
 r7   c                 p    | j         J t          j        | j                   \  }}|dk    rdS |dS ||S dS )zhReturns the ``Content-Type`` header to be used for this request.

        .. versionadded:: 3.1
        Nr  zapplication/gzipzapplication/octet-stream)r9  	mimetypes
guess_type)rO   	mime_typeencodings      r8   rN  z"StaticFileHandler.get_content_type  s^    
 !---'243EFF	8v%% !--" .-r7   c                     dS )z1For subclass to add extra headers to the responseNr6   r2  s     r8   rP  z#StaticFileHandler.set_extra_headers!  r   r7   r;  ry  c                 0    d| j         j        v r| j        ndS )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   )rE   r   CACHE_MAX_AGE)rO   r   r;  ry  s       r8   rO  z StaticFileHandler.get_cache_time%  s!     &)DL,B%B%Bt!!Ir7   ri   include_versionc                 ~    |                     dd          |z   }|s|S |                     ||          }|s|S | d| S )a  Constructs 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``.

        r  r  z?v=)r   get_version)r~  ri   r   r~  r   rJ  s         r8   r  z!StaticFileHandler.make_static_url4  s^    , ll.
;;dB 	Jx66 	J((,(((r7   url_pathc                 z    t           j        j        dk    r%|                    dt           j        j                  }|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   )ro  r   r]  r  )rO   r  s     r8   r6  z StaticFileHandler.parse_url_pathT  s1     7;#''RW[99Hr7   c                 d    |                      |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  )r7  rI  )r~  ri   r   abs_paths       r8   r  zStaticFileHandler.get_versiona  s2     ((-)@$GG&&x000r7   r  c                 .   | j         5  | j        }||vrD	 |                     |          ||<   n*# t          $ r t	          j        d|           d ||<   Y nw xY w|                    |          }|r|cd d d            S 	 d d d            n# 1 swxY w Y   d S )NzCould not open static file %r)r.  r/  rk  r  r   r  r   )r~  r  hasheshshs       r8   rI  z%StaticFileHandler._get_cached_versionr  s"   Y 
	 
	'Fv%%,'*'>'>x'H'HF8$$  , , ,M"A8LLL'+F8$$$, **X&&C 
	 
	 
	 
	 
	 
	 
	 
	
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 ts1   B
.B
$AB
AB

BBrJ   r_  r`  )NN)+r3   r4   r5   ra  r}  r/  rc  rd  r.  r   r"   rb   classmethodr	  r#   ri  r   r   r#  r<  r=  r7  r8  r(  r(   r   rA  rk  ro  rr  ro  r?  r   r:  rN  rP  rO  r   r    r  r6  r  rI  r6   r7   r8   r  r  p
  s       @ @D %MNINE1 1s 1hsm 1t 1 1 1 1 $ $ $ [$2 24 2 2 2 2Q1 Q1c Q1 Q1 Q1 Q1 Q1 Q1f#hsm # # # #* * * *44    2 S      [ 93 9s 9xPS} 9 9 9 9v MQ$ $$"*3-$=Ec]$	5$$	%$ $ $ [$L "# "# " " " [""!r~ ! ! ! !## # # # #8H,=#>    4.# . . . .*c d    JJ#+H,=#>JKNJ	J J J J JN) )CH~)-0)CG)	) ) ) [)>s s     14S> 1 1# 1 1 1 [1  3 8C=    [  r7   r  c                   F    e Zd ZdZdeej        gdf         ddfdZddZdS )FallbackHandleraN  A `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)),
        ])
    fallbackNrG   c                     || _         d S rJ   )r  )rO   r  s     r8   rb   zFallbackHandler.initialize  s     !r7   c                 p    |                      | j                   d| _        |                                  d S )NT)r  rE   rV   rs   re   s    r8   rq   zFallbackHandler.prepare  s3    dl###r7   r_  )	r3   r4   r5   ra  r&   r   rg  rb   rq   r6   r7   r8   r  r    sf          ! ("<!=t!CD!	! ! ! !
     r7   r  c                       e Zd ZdZdej        ddfdZdedej        de	d	e
deeej        e	f         f
d
Zde	d	e
de	fdZdS )r1  zA 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.
    rE   rG   Nc                     d S rJ   r6   rO   rE   s     r8   rT   zOutputTransform.__init__  rg   r7   r   r  r+  	finishingc                     |||fS rJ   r6   )rO   r   r  r+  r  s        r8   r  z%OutputTransform.transform_first_chunk  s     GU**r7   c                     |S rJ   r6   rO   r+  r  s      r8   r  zOutputTransform.transform_chunk  s    r7   )r3   r4   r5   ra  r   rg  rT   r(  r   r   r   r$   r  r  r6   r7   r8   r1  r1    s          : t    ++ %+ 	+
 + 
sH(%/	0+ + + +U t       r7   r1  c                       e Zd ZdZh dZdZdZdej        ddfdZ	d	e
defd
Zdedej        dededeeej        ef         f
dZdededefdZdS )r  aI  Applies 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).
    >   image/svg+xmlapplication/xmlapplication/jsonapplication/atom+xmlapplication/xhtml+xmlapplication/javascriptapplication/x-javascript   i   rE   rG   Nc                 J    d|j                             dd          v | _        d S )Nr  Accept-Encodingr
  )r  r   	_gzippingr  s     r8   rT   zGZipContentEncoding.__init__  s%    7?#6#67H"#M#MMr7   ctypec                 >    |                     d          p|| j        v S )Nztext/)r  CONTENT_TYPES)rO   r  s     r8   _compressible_typez&GZipContentEncoding._compressible_type  s#    ((GET5G,GGr7   r   r  r+  r  c                 @   d|v r|dxx         dz  cc<   nd|d<   | j         rut          |                    dd                                        d          d         }|                     |          o| pt          |          | j        k    od|v| _         | j         r}d	|d<   t                      | _        t          j
        d
| j        | j                  | _        |                     ||          }d|v r%|r t          t          |                    |d<   n|d= |||fS )NVaryz, Accept-Encodingr  r}   r
  r  r   r]  r  w)modefileobjcompresslevelr  )r  r   r   r  r  r  
MIN_LENGTHr   _gzip_valuer  GzipFile
GZIP_LEVEL
_gzip_filer  r   )rO   r   r  r+  r  r  s         r8   r  z)GZipContentEncoding.transform_first_chunk  sM    WFOOO22OOOO/GFO> 	W[[<<==CCCHHKE''.. 8"]Cc%jjDO&C8'w6 N
 > 	2*0G&'&yyD"m$"2$/  DO ((	::E7**
  203CJJG,-- 01GU**r7   c                 L   | j         r| j                            |           |r| j                                         n| j                                         | j                                        }| j                            d           | j                            d           |S )Nr   )	r  r  r1  closer  r  getvaluetruncaterd  r  s      r8   r  z#GZipContentEncoding.transform_chunk  s    > 	%O!!%((( (%%''''%%'''$--//E%%a(((!!!$$$r7   )r3   r4   r5   ra  r  r  r  r   rg  rT   r   r   r  r(  r   r   r$   r  r  r6   r7   r8   r  r    s          M J JN : Nt N N N NH H H H H H#+#+ %#+ 	#+
 #+ 
sH(%/	0#+ #+ #+ #+J
U 
t 
 
 
 
 
 
 
r7   r  c                      t          j                   dt          dt          t          d                  f fd            }|S )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.
    rO   rG   Nc                    | j         s| j        j        dv r|                                 }d|vr{t          j                            |          j        r| j                                        }n| j        j	        J | j        j	        }|dt          t          |                    z   z  }|                     |           d S t          d           | g|R i |S )Nr  r  )nextr	  )r  rE   r  r  urllibparseurlsplitschemefull_urlrI  r   r  r*  rm   )rO   rj   rF   r   next_urlr  s        r8   r  zauthenticated.<locals>.wrapper  s       	!|"o55((**c>>|,,S118 4#'<#8#8#:#:#|/;;;#'<#334X+>+>+>!?!???Cc"""tC.. vd,T,,,V,,,r7   r  r  s   ` r8   authenticatedr    sX     _V--	)D/	"- - - - - -& Nr7   c                      e Zd ZdZdeddfdZedefd            Zdedede	e
ef         fd	Zdee
         fd
Zdeee
                  fdZdee
         fdZdeee
                  fdZdee
         fdZdee
         fdZde
dedefdZdS )rU  a2  A 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.
    r  rG   Nc                 \    || _         |j        | _        |j        | _        |j        | _        d S rJ   )r  rE   r[   r   )rO   r  s     r8   rT   zUIModule.__init__>  s(    *nr7   c                     | j         j        S rJ   )r  r  re   s    r8   r  zUIModule.current_userD  s    |((r7   rj   rF   c                     t                      )z6Override in subclasses to return this module's output.rC  rn   s      r8   rW  zUIModule.renderH  s    !###r7   c                     dS )zJOverride to return a JavaScript string
        to be embedded in the page.Nr6   re   s    r8   r8  zUIModule.embedded_javascriptL  	     tr7   c                     dS )zOverride 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.
        Nr6   re   s    r8   r9  zUIModule.javascript_filesQ  	     tr7   c                     dS )zJOverride to return a CSS string
        that will be embedded in the page.Nr6   re   s    r8   r;  zUIModule.embedded_cssY  r  r7   c                     dS )zOverride 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.
        Nr6   re   s    r8   r<  zUIModule.css_files^  r  r7   c                     dS )z[Override to return an HTML string that will be put in the <head/>
        element.
        Nr6   re   s    r8   r=  zUIModule.html_headf  	     tr7   c                     dS )zfOverride to return an HTML string that will be put at the end of
        the <body/> element.
        Nr6   re   s    r8   r>  zUIModule.html_bodyl  r  r7   r   c                 (     | j         j        |fi |S )z.Renders a template and returns it as a string.)r  r6  )rO   r   rF   s      r8   r6  zUIModule.render_stringr  s    )t|)$99&999r7   )r3   r4   r5   ra  r:   rT   rh  r    r  r!   r   r   rW  r"   r8  r'   r9  r;  r<  r=  r>  r6  r6   r7   r8   rU  rU  4  s        % %4 % % % % )c ) ) ) X)$C $3 $5e3D $ $ $ $Xc]    
(8C="9    hsm    
8HSM2    8C=    8C=    :# : : : : : : : :r7   rU  c                   "    e Zd ZdededefdZdS )r  textrF   rG   c                 &    t          j        |fi |S rJ   )r   r  )rO   r  rF   s      r8   rW  z_linkify.renderx  s    ~d--f---r7   N)r3   r4   r5   r   r    rW  r6   r7   r8   r  r  w  s=        .3 .# .# . . . . . .r7   r  c                       e Zd ZdefdZdS )r  rG   c                 4    | j                                         S rJ   )r  r  re   s    r8   rW  z_xsrf_form_html.render}  s    |**,,,r7   N)r3   r4   r5   r   rW  r6   r7   r8   r  r  |  s/        - - - - - - -r7   r  c                        e Zd ZdZdeddf fdZdededefdZ	d	ede
e         fd
ZdefdZde
e         fdZdefdZde
e         fdZdefdZdefdZ xZS )r  a  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.
    r  rG   Nc                 f    t                                          |           g | _        i | _        d S rJ   )rS   rT   _resource_list_resource_dict)rO   r  rc   s     r8   rT   zTemplateModule.__init__  s1    !!!  r7   r   rF   c                 B     dt           f fd}  j        fd|i|S )NrG   c                      j         vr%j                            |            | j         <   n j                  | k    rt          d          dS )NzCset_resources called with different resources for the same templater
  )r  r  r   r   )rF   r   rO   s    r8   set_resourcesz,TemplateModule.render.<locals>.set_resources  si    4...#**6222,2#D))&t,66$:   2r7   r  )r   r6  )rO   r   rF   r  s   ``  r8   rW  zTemplateModule.render  sP    
	s 
	 
	 
	 
	 
	 
	 
	 "t!$NNmNvNNNr7   r  c                 *    fd| j         D             S )Nc              3   0   K   | ]}|v |         V  d S rJ   r6   )rL   rr  s     r8   rP   z0TemplateModule._get_resources.<locals>.<genexpr>  s+      @@1saxx#xxxx@@r7   )r  rO   r  s    `r8   _get_resourceszTemplateModule._get_resources  s     @@@@ 3@@@@r7   c                 R    d                     |                     d                    S )N
r8  rE  r  re   s    r8   r8  z"TemplateModule.embedded_javascript  s#    yy,,-BCCDDDr7   c                     g }|                      d          D ]I}t          |t          t          f          r|                    |           4|                    |           J|S )Nr9  r  r   r   r   r   r:  rO   r@  r  s      r8   r9  zTemplateModule.javascript_files  sk    $$%788 	! 	!A!lE233 !a    a    r7   c                 R    d                     |                     d                    S )Nr  r;  r  re   s    r8   r;  zTemplateModule.embedded_css  s"    yy,,^<<===r7   c                     g }|                      d          D ]I}t          |t          t          f          r|                    |           4|                    |           J|S )Nr<  r  r  s      r8   r<  zTemplateModule.css_files  sj    $$[11 	! 	!A!lE233 !a    a    r7   c                 R    d                     |                     d                    S )Nr
  r=  r  re   s    r8   r=  zTemplateModule.html_head  "    wwt**;77888r7   c                 R    d                     |                     d                    S )Nr
  r>  r  re   s    r8   r>  zTemplateModule.html_body  r  r7   )r3   r4   r5   ra  r:   rT   r   r    r   rW  r'   r  r8  r9  r;  r<  r=  r>  rz  r{  s   @r8   r  r    s`        ! !4 ! ! ! ! ! !O3 O# O% O O O OA# A(3- A A A AES E E E E(3-    >c > > > >8C=    93 9 9 9 993 9 9 9 9 9 9 9 9r7   r  c                       e Zd ZdZdedeeee         f         ddfdZ	dede
def         fd	Zdede
def         fd
ZdS )r\   zALazy namespace which creates UIModule proxies bound to a handler.r  r]   rG   Nc                 "    || _         || _        d S rJ   )r  r]   )rO   r  r]   s      r8   rT   z_UIModuleNamespace.__init__  s     $r7   r  .c                 N    | j                             || j        |                   S rJ   )r  rY  r]   r  s     r8   __getitem__z_UIModuleNamespace.__getitem__  s!    |&&sDOC,@AAAr7   c                 p    	 | |         S # t           $ r!}t          t          |                    d }~ww xY wrJ   )r  AttributeErrorr   )rO   r  r?  s      r8   __getattr__z_UIModuleNamespace.__getattr__  sD    	)9 	) 	) 	) Q(((	)s   
 
505)r3   r4   r5   ra  r:   r   r   r)   rU  rT   r&   r  r  r6   r7   r8   r\   r\     s        KK%%%37T(^8K3L%	% % % %Bs BxS'9 B B B B)s )xS'9 ) ) ) ) ) )r7   r\   r  r   r   r   clockr  c           	         |t           }|t          j        }t          t          t	           |                                          }t          j        t          |                    }|dk    rCt          | t                    rJ t          | |||          }d
                    |||g          }|S |dk    rdt          t          t          f         dt          fd}d
                    d |t          |pd                     ||           ||           ||          d	g          }	t          | t                    r$|
J d
            |dk    s
J d            | |         } t          | |	          }|	|z   S t          d|z            )Nr/   r  r0   r   rG   c                 `    t          dt          |           z            t          |           z   S )Nz%d:)r   r  )r   s    r8   format_fieldz)create_signed_value.<locals>.format_field  s%    A''$q''11r7   r  r   r7   z2Key version must be set when sign key dict is usedz2Version must be at least 2 for key version supportzUnsupported version %d)DEFAULT_SIGNED_VALUE_VERSIONr   r   r   r(  base64	b64encoder   r  _create_signature_v1rE  r!   r   _create_signature_v2r   )
r  r   r   r   r  r  r  	signaturer  to_signs
             r8   r  r    s    .}	SUUWW&&''IT%[[))E!||fd+++++(uiHH			5)Y788	A	2E#u*- 	2% 	2 	2 	2 	2 ))S!12233Y''T""U##	
 	
 fd## 	)''C (''a<<<!U<<<K(F(99	""1G;<<<r7   s   ^([1-9][0-9]*)\|(.*)$c                     t                               |           }|d}n>	 t          |                    d                    }|dk    rd}n# t          $ r d}Y nw xY w|S )Nr/   i  )r  r   r(  r  r   )r   rN   r   s      r8   _get_versionr    sw     	!&&u--Ay	!''!**ooG}}  	 	 	GGG	Ns   *A AAr  r  r  c                 J   |t           j         }|t          }|dk    rt          d|z            |sd S t          |          }t	          |          }||k     rd S |dk    r*t          | t                    rJ t          | ||||          S |dk    rt          | ||||          S d S )Nr0   zUnsupported min_version %dr/   )	r    DEFAULT_SIGNED_VALUE_MIN_VERSIONr   r   r  r   r  _decode_signed_value_v1_decode_signed_value_v2)r  r   r   r  r  r  r   s          r8   r  r  5  s     }	6Q5CDDD tKKE5!!Gt!||fd+++++&vtUL%PPP	A&vtUL%PPPtr7   c                    t          |                              d          }t          |          dk    rd S t          | ||d         |d                   }t	          j        |d         |          st          j        d|           d S t          |d                   }| |            |dz  z
  k     rt          j        d|           d S | |            d	z   k    rt          j        d
|           d S |d         	                    d          rt          j        d|           d S 	 t          j        |d                   S # t          $ r Y d S w xY w)Nr     r   r/   r0   zInvalid cookie signature %rQ zExpired cookie %ri( z1Cookie timestamp in future; possible tampering %r   0zTampered cookie %r)r   r  r  r  r
  r  r   rS  r(  r  r  	b64decoder  )r  r   r   r  r  r  r  r  s           r8   r  r  T  s]    KKd##E
5zzQt$VT58U1XFFIuQx33 5u===tE!HI5577\E1111+U333t5577Z''' 	KUSSStQx4   ,e444ta)))   tts   #D= =
E
Ec                     dt           dt          t           t           f         fd}| dd          } ||          \  }} ||          \  }} ||          \  }} ||          \  }}t          |          ||||fS )Nr   rG   c                     |                      d          \  }}}t          |          }|d |         }|||dz            dk    rt          d          ||dz   d          }||fS )N   :r/   r  zmalformed v2 signed value field)	partitionr(  r   )r   lengthr  restrM   field_values         r8   _consume_fieldz)_decode_fields_v2.<locals>._consume_fieldx  su    ++d++4KK2A2h AE	?d"">???AEGG}D  r7   r0   )r   r$   r(  )r   r  r
  r  r  
name_fieldvalue_field
passed_sigs           r8   _decode_fields_v2r  w  s    	!% 	!E%,$7 	! 	! 	! 	! 9D&t,,K$nT**OIt%~d++J,nT22K{Y
KKKr7   c                    	 t          |          \  }}}}}	n# t          $ r Y d S w xY w|d t          |	                    }
t          | t                    r	 | |         } n# t
          $ r Y d S w xY wt          | |
          }t          j        |	|          sd S |t          |          k    rd S t          |          }| |            |dz  z
  k     rd S 	 t          j        |          S # t          $ r Y d S w xY w)Nr  )r  r   r  r   r  r  r  r
  r  r   r(  r  r  r  )r  r   r   r  r  r  timestamp_bytesr  r  r  signed_stringexpected_sigr  s                r8   r  r    sP   	 e$$	
J   tt,S__,,-M&$ 	K(FF 	 	 	44	 (>>Lz<88 tT$ZZtO$$I5577\E1111t,,,   tts0    
&&A   
A.-A.C' '
C54C5c                     t          |           } t          |           }|dk     rd S 	 t          |           \  }}}}}n# t          $ r Y d S w xY w|S )Nr0   )r   r  r  r   )r   r   r  r  s       r8   r"  r"    sq    KKE5!!G{{t"3E":":Q1aa   tt s   > 
AAr  c                     t          j        t          |           t          j                  }|D ]$}|                    t          |                     %t          |                                          S N)	digestmod)r
  newr   r  r   rv  r!  )r  r  hashr  s       r8   r  r    s`    8DLLGL999D    DJJ  !!!r7   r   c                     t          j        t          |           t          j                  }|                    t          |                     t          |                                          S r  )r
  r  r   r  sha256rv  r!  )r  r   r  s      r8   r  r    sN    8DLLGN;;;DKKQ  !!!r7   r   c                 :     t           fddD                       S )Nc              3   B   K   | ]}                     |          V  d S rJ   r+  )rL   r)  r   s     r8   rP   zis_absolute.<locals>.<genexpr>  s/      DDatq!!DDDDDDr7   )r   zhttp:zhttps:)any)r   s   `r8   r_  r_    s'    DDDD+CDDDDDDr7   r  )r  NN)ra  r  r  r   email.utilsrU  r  r  r  r
  http.cookiesr   inspectr   ior   rw  r   os.pathro  r   r  rj  rc  r   r   r   r  r  urllib.parser  r   tornado.concurrentr   r   r   r	   tornado.httpserverr
   r   r   r   tornado.logr   r   r   r   tornado.escaper   r   tornado.routingr   r   r   r   r   r   r   r   tornado.utilr   r   r   r   typingr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   TYPE_CHECKINGr.   r   r(  r   ro  r   _CookieSecretTypes"MIN_SUPPORTED_SIGNED_VALUE_VERSION"MAX_SUPPORTED_SIGNED_VALUE_VERSIONr  r  r2   rp  r:   r|  r  r   ru   r  r  r  rD   r  r  r  rm   rM  r   r  r!  r  r  r1  r  r  rU  r  r  r  r\   r  r  re  r  r  r  r  r  r  r"  r  r  r_  r6   r7   r8   <module>r1     s   ) )V                                     				  



                 " " " " " " I I I I I I I I             ) ) ) ) ) )                   4 4 4 4 4 4 4 4 4 4       ) ) ) ) ) ) ) )	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 C B B B B B B B B B                                        	 
 UL#w/?ARRS3tCH~tCJ7GGH  &' " &' "  !  $%  	 	 	 	 	 	 	 	 ! ""x! x! x! x! x! x! x! x!v7 g3>JJJ T"56 4@S;T    6$$~"6 $4 $ $ $ $S(9T?334c8IdO,,-   :S(9T?334c8IdO,,-   6$M $M $M $M $M- $M $M $MN{
 {
 {
 {
 {
" {
 {
 {
|	W- W- W- W- W-x3 W- W- W-t: : : : :	 : : :z	 	 	 	 	Y 	 	 	8! ! ! ! !9 ! ! !    >    -9 -9 -9 -9 -9n -9 -9 -9`O O O O O O O Od    n   8       0V V V V V/ V V Vr"S(9T?334"c8IdO,,-" " " "J@: @: @: @: @: @: @: @:F. . . . .x . . .
- - - - -h - - -
D9 D9 D9 D9 D9X D9 D9 D9N) ) ) ) ) ) ) ). "+/!%;= ;=;=
;= e;= c]	;=
 HRY'(;= #;= ;= ;= ;= ;=@ &2:&?@@  #    6 +/!% 
 sE!" 	
 HRY'( # e_   > #u* 
    	 
 BI  e_       FLU LuS%u-L'M L L L L(%%
% % 	%
 BI% e_% % % %P
U3:%6 
8C= 
 
 
 
"sEz!2 "E#u*<M "RW " " " ""sEz!2 "u " " " " "Ec Ed E E E E E Er7   