
    hG                    J   S r SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSK	r	SSK
rSSKJr  SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSK J!r!J"r"  SSKJ#r#  SSKJ$r$  SS	K%J&r&  SS
KJ'r'  SSKJ(r(  SSKJ)r)  SSK*J+r+J,r,J-r-  SSKJ.r.  SSK/J0r0J1r1  SSK2J3r3J4r4J5r5J6r6J7r7J8r8J9r9J:r:  SSK;J<r<J=r=J>r>  \9r?SSK@JArAJBrBJCrCJDrDJErEJFrFJGrGJHrHJIrIJJrJJKrKJLrLJMrMJNrN  SSKJOrO  SSK@r@\@R                  (       a  SSK@JQrQ  \C\R\=\S\R                  \R                  4   rU\C\V\R\A\S\V4   \A\S\R4   4   rWSrX SrY SrZ Sr[  " S S5      r\\\" 5       r] " S S5      r^\L" S\^S9r_S\K\_   S\K\_   4S jr`S\K\^   S\a4S  jrbS!\HS"\D\ES      4   S\HS"\D\ES      4   4S# jrcS!\HS"\D\ES      4   S\HS"\D\ES      4   4S$ jrd " S% S&\85      re " S' S(\65      rf " S) S*\'R                  5      rh " S+ S,\i5      rj " S- S.\i5      rk " S/ S0\j5      rl " S1 S2\^5      rm " S3 S4\^5      rn " S5 S6\^5      ro " S7 S8\^5      rp " S9 S:5      rq " S; S<\q5      rrS!\HS"\D\ES      4   S\HS"\D\ES      4   4S= jrs " S> S?5      rt " S@ SA\t5      ru " SB SC\t5      rv " SD SE\t5      rw " SF SG5      rx   S^SH\WSI\VSJ\C\V\R4   SK\D\S   SL\D\H/ \y4      SM\D\S   S\R4SN jjrz\R                  " SO5      r|SJ\RS\S4SP jr}   S_SH\WSI\VSJ\CS\V\R4   SQ\ySL\D\H/ \y4      SR\D\S   S\D\R   4SS jjr~SH\C\V\R4   SI\VSJ\RSQ\ySL\H/ \y4   S\D\R   4ST jrSJ\RS\F\S\R\R\R\R4   4SU jrSH\WSI\VSJ\RSQ\ySL\H/ \y4   S\D\R   4SV jrSJ\C\V\R4   S\D\S   4SW jrSH\C\V\R4   SX\C\V\R4   S\R4SY jrSH\C\V\R4   SZ\RS\R4S[ jrS\\VS\a4S] jrg)`a4  ``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                       \ rS rSrSrg)_ArgDefaultMarker    N)__name__
__module____qualname____firstlineno____static_attributes__r4       ^C:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\tornado/web.pyr2   r2      s    r:   r2   c                     ^  \ rS rSr% SrSr\\S4   \S'   0 r	\
R                  " 5       r\R                  " S5      rSrSrSrSrS	S
S\R*                  S\SS4U 4S jjrSS jr\r \S\\\4   4S j5       rS\S\SS4S jr\r\r\r \r!\r"\r#\r$S\%\&S      4S jr'SS jr(SS jr)SS jr*SS jr+SS\,S\%\   SS4S jjr-S\,4S jr.S\S\/SS4S jr0S\S\/SS4S jr1S\SS4S  jr2\R                  " S!5      r3S\/S\4S" jr4\5SS\S$\S%\6S\4S& jj5       r7\5\8S#4S\S$\9S%\6S\4S' jj5       r7\5 SS\S$SS%\6S\%\   4S( jj5       r7\8S#4S\S$\:S\\94   S%\6S\%\   4S) jjr7SS\S%\6S\;\   4S* jjr<\5SS\S$\S%\6S\4S+ jj5       r=\5\8S#4S\S$\9S%\6S\4S, jj5       r=\5 SS\S$SS%\6S\%\   4S- jj5       r=\8S#4S\S$\:S\\94   S%\6S\%\   4S. jjr=SS\S%\6S\;\   4S/ jjr>\5SS\S$\S%\6S\4S0 jj5       r?\5\8S#4S\S$\9S%\6S\4S1 jj5       r?\5 SS\S$SS%\6S\%\   4S2 jj5       r?\8S#4S\S$\:S\\94   S%\6S\%\   4S3 jjr?SS\S%\6S\;\   4S4 jjr@ SS\S$\:S\\94   S5\\\;\A   4   S%\6S\%\   4
S6 jjrB SS\S5\\\;\A   4   S%\6S\;\   4S7 jjrCSS\AS\%\   S\4S8 jjrD\S\\\ER                  R                  4   4S9 j5       rF\5S\S$\S\4S: j5       rH\5SS\S$SS\%\   4S; jj5       rHSS\S$\%\   S\%\   4S< jjrH    SSSSSS=.S\S\:\\A4   S>\%\   S?\%\:\I\\JR                  4      S@\SA\%\I   SB\%\,   SC\6SD\6SE\%\   S\SS4SF jjjrKS\S\SS4SG jrLS\SS4SH jrM  SS\S\:\\A4   SA\%\I   SI\%\,   S\SS4SJ jjrN\NrO SS\S\:\\A4   SI\%\,   S\A4SK jjrP   SS\S\%\   SL\ISM\%\,   S\%\A   4
SN jjrQ\QrR SS\S\%\   S\%\,   4SO jjrS\SrT SSP\SQ\6SR\%\,   SS4SS jjrUST\:\\A\V4   SS4SU jrWSV\S\SSW4SX jrXSY\Y\   S\4SZ jrZS[\Y\A   S\A4S\ jr[S]\Y\   S\4S^ jr\S_\Y\A   S\A4S` jr]SV\S\S\A4Sa jr^S\\\4   4Sb jr_Sc\S\`R                  4Sd jrbSSe\6SSW4Sf jjrcSST\%\:\\A\V4      SSW4Sg jjrdS\eR                  4Sh jrgSSi jrhSS\,S\SS4Sj jjriS\,S\SS4Sk jrj\S\kR                  R                  4Sl j5       rl\lR                  S\kR                  R                  SS4Sm j5       rlS\%\kR                  R                     4Sn jroSS$\S\kR                  R                  4So jjrp\S\4Sp j5       rq\qR                  S\SS4Sq j5       rqS\4Sr jrrS\4Ss jrsS\%\   4St jrt\S\A4Su j5       ruS\\%\,   \A\I4   4Sv jrvSw\S\\%\,   \%\A   \%\I   4   4Sx jrwSSy jrxS\4Sz jry SS@\S{\%\6   S\S\4S| jjrzSS\S}\SS4S~ jjr{S\S\S\4S jr|S\%\   4S jr}SS jr~S\64S jrS\;S   S\AS\ASS4S jrST\AS\%\&S      4S jrSS jrS\4S jrS\SS4S jrSSS\%\   S\%\   SS4S jrS\S\S   S\S\4   4S jrS\S\4   S\S\4   4S jrSS jrSrU =r$ )RequestHandler   a.  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T ]  5         UT l        UT l        ST l        ST l        ST l        S T l        [        U 4S jUR                  R                  5        5       5      T l        [        T UR                  5      T R                  S'   T R                  S   T R                  S'   T R                  5         T R                  R                  c   eT R                  R                  R!                  T R"                  5        T R$                  " S0 UD6  g )NFTc              3   N   >#    U  H  u  pUTR                  U5      4v   M     g 7fN)
_ui_method).0nmselfs      r;   	<genexpr>*RequestHandler.__init__.<locals>.<genexpr>   s%      
0NQ"#0Ns   "%_tt_modulesmodulesr4   )super__init__rG   rI   _headers_written	_finished_auto_finish_prepared_futurer   
ui_methodsitemsui_UIModuleNamespace
ui_modulesclear
connectionset_close_callbackon_connection_close
initialize)rS   rG   rI   rJ   	__class__s   `   r;   rY   RequestHandler.__init__   s     	& %  $ 
0;0F0F0L0L0N
 
 "4D+:P:P!Q!WW]3	

||&&22222$$	
 	!&!r:   c                     g rN   r4   rS   s    r;   _initializeRequestHandler._initialize       r:   c                 .    U R                   R                  $ )z@An alias for `self.application.settings <Application.settings>`.)rG   settingsrk   s    r;   rp   RequestHandler.settings  s     (((r:   argsc                     [        S5      e)N  )	HTTPErrorrS   rr   rJ   s      r;   _unimplemented_method$RequestHandler._unimplemented_method  s    nr:   c                     g)a  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.
Nr4   rk   s    r;   prepareRequestHandler.prepare  s     	r:   c                     g)a	  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.
Nr4   rk   s    r;   	on_finishRequestHandler.on_finish,  s     	r:   c                 F   [        U R                  5      (       a  U R                  R                  R	                  5       (       d]  U R                  R                  R                  [        R                  " 5       5        U R                  R                  R                  5         ggg)a  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_bodyrh   rI   _body_futuredoneset_exceptionr   StreamClosedError	exceptionrk   s    r;   rf   "RequestHandler.on_connection_close:  sm     $DNN33<<,,1133))778R8R8TU))335 4 4r:   c                    [         R                  " S[        R                  -  S[         R                  " [
        R
                  " 5       5      S.5      U l        U R                  5         / U l        SU l	        [         R                  S   U l        g)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_reasonrk   s    r;   rc   RequestHandler.clearM  sl     ,,,w> : 11$))+>
 	  "))#.r:   c                     g)a  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.
Nr4   rk   s    r;   r   "RequestHandler.set_default_headers[  s     	r:   status_codereasonc                     Xl         Ub  [        R                  " U5      U l        g[        R
                  R                  US5      U l        g)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)rS   r   r   s      r;   
set_statusRequestHandler.set_statuse  s<     (!,,V4DL#--11+yIDLr:   c                     U R                   $ )z)Returns the status code for our response.)r   rk   s    r;   
get_statusRequestHandler.get_statusx  s       r:   namevaluec                 @    U R                  U5      U R                  U'   g)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   rS   r   r   s      r;   
set_headerRequestHandler.set_header|  s     #88?dr:   c                 X    U R                   R                  XR                  U5      5        g)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      r;   
add_headerRequestHandler.add_header  s!     	$ : :5 ABr:   c                 >    XR                   ;   a  U R                   U	 gg)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   )rS   r   s     r;   clear_headerRequestHandler.clear_header  s     == d# !r:   z[\x09\x20-\x7e\x80-\xff]*c                    [        U[        5      (       a  UnO[        U[        5      (       a  UR                  S5      nOm[        U[        R
                  5      (       a  [        U5      $ [        U[        R                  5      (       a  [        R                  " U5      $ [        SU-  5      e[        R                  R                  U5      c  [        SU5      eU$ )Nlatin1zUnsupported header value %rzUnsafe header value %r)
isinstancestrbytesdecodenumbersIntegraldatetimer   r   	TypeErrorr=   _VALID_HEADER_CHARS	fullmatch
ValueError)rS   r   retvals      r;   r   $RequestHandler._convert_header_value  s    
 eS!!Fu%% \\(+Fw//00u:x0011,,U339EABB --77?G5v>>r:   Tdefaultstripc                     g rN   r4   rS   r   r   r   s       r;   get_argumentRequestHandler.get_argument      r:   c                     g rN   r4   r   s       r;   r   r          	r:   c                     g rN   r4   r   s       r;   r   r     r   r:   c                 P    U R                  XU R                  R                  U5      $ )aB  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_argumentrI   	argumentsr   s       r;   r   r     s#      !!$1G1GOOr:   c                 |    [        U[        5      (       d   eU R                  XR                  R                  U5      $ )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_argumentsrI   r   rS   r   r   s      r;   get_argumentsRequestHandler.get_arguments  s4     %&&&&""4)?)?GGr:   c                     g rN   r4   r   s       r;   get_body_argument RequestHandler.get_body_argument  r   r:   c                     g rN   r4   r   s       r;   r   r     r   r:   c                     g rN   r4   r   s       r;   r   r     r   r:   c                 P    U R                  XU R                  R                  U5      $ )a2  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   rI   body_argumentsr   s       r;   r   r     s#    " !!$1L1LeTTr:   c                 N    U R                  XR                  R                  U5      $ )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   rI   r   r   s      r;   get_body_arguments!RequestHandler.get_body_arguments  s!     ""4)D)DeLLr:   c                     g rN   r4   r   s       r;   get_query_argument!RequestHandler.get_query_argument  r   r:   c                     g rN   r4   r   s       r;   r   r     r   r:   c                     g rN   r4   r   s       r;   r   r     r   r:   c                 P    U R                  XU R                  R                  U5      $ )a:  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   rI   query_argumentsr   s       r;   r   r     s#    " !!$1M1MuUUr:   c                 N    U R                  XR                  R                  U5      $ )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   rI   r   r   s      r;   get_query_arguments"RequestHandler.get_query_arguments2  s!     ""4)E)EuMMr:   sourcec                 ~    U R                  XUS9nU(       d"  [        U[        5      (       a  [        U5      eU$ US   $ )N)r   )r   r   r2   MissingArgumentError)rS   r   r   r   r   rr   s         r;   r   RequestHandler._get_argument;  sC     ""4u"='#455*400NBxr:   c                    / nUR                  U/ 5       Ho  nU R                  XQS9n[        U[        5      (       a   [        R
                  R                  SU5      nU(       a  UR                  5       nUR                  U5        Mq     U$ )Nr    )	r   decode_argumentr   r   r=   _remove_control_chars_regexsubr   append)rS   r   r   r   valuesvss          r;   r   RequestHandler._get_argumentsI  sy     D"%A$$Q$2A!\** #>>BB3JGGIMM! & r:   c           
           [        U5      $ ! [         a)    [        SSR                  U=(       d    SUSS 5      5      ef = f)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   UnicodeDecodeErrorru   format)rS   r   r   s      r;   r   RequestHandler.decode_argumentX  sK    	E?"! 	299$-%sPRT 	s	   
 3A c                 .    U R                   R                  $ )zJAn alias for
`self.request.cookies <.httputil.HTTPServerRequest.cookies>`.)rI   cookiesrk   s    r;   r  RequestHandler.cookiesl  s     ||###r:   c                     g rN   r4   rS   r   r   s      r;   
get_cookieRequestHandler.get_cookier  r   r:   c                     g rN   r4   r  s      r;   r  r  v  r   r:   c                     U R                   R                  b<  XR                   R                  ;   a#  U R                   R                  U   R                  $ U$ )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.
)rI   r  r   r  s      r;   r  r  z  sC     <<+8L8L0L<<''-333r:   )max_agehttponlysecuresamesitedomainexpirespathexpires_daysr	  r
  r  r  c                   [         R                  " U5      n[         R                  " U5      n[        R                  " SX-   5      (       a  [	        SU< SU< 35      e[        U S5      (       d#  [        R                  R                  5       U l	        XR                  ;   a  U R                  U	 X R                  U'   U R                  U   nU(       a  X<S'   UbS  U(       dL  [        R                  R                  [        R                  R                  5      [        R                  " US9-   nU(       a  [        R                   " U5      US'   U(       a  X\S	'   U(       a  [#        U5      US
'   U(       a  SUS'   U	(       a  SUS'   U
(       a  XS'   U(       aT  UR%                  5        H	  u  pXU'   M     [&        R(                  " S[+        UR-                  5       5       S3[.        5        gg)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   r_   warningswarnsetkeysDeprecationWarning)rS   r   r   r  r  r  r  r	  r
  r  r  rJ   morselkr   s                  r;   
set_cookieRequestHandler.set_cookie  s   J   &!!%(99^T\22thb	BCCt]++))+  ###  &!&!!$'%8#G''++H,=,=,A,ABXEWEW!F G  ( 9 9' BF9!6N #GF9 "&F:#F8!): q	 'MM6s6;;=7I6J K( (" r:   c                    S H  nX2;   d  M
  [        SU S35      e   [        R                  R                  [        R                  R                  5      [        R
                  " SS9-
  nU R                  " U4SUS.UD6  g)	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%  )rS   r   rJ   excluded_argr  s        r;   clear_cookieRequestHandler.clear_cookie  s    $ 3L%I,WXY  3
 ##''(9(9(=(=>ASASB
 
 	BBB6Br:   c                 d    U R                   R                   H  nU R                  " U40 UD6  M     g)a  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)rI   r  r+  )rS   rJ   r   s      r;   clear_all_cookies RequestHandler.clear_all_cookies  s+    8 LL((Dd-f- )r:   r   c           	      L    U R                   " UU R                  XUS94SU0UD6  g)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)rS   r   r   r  r   rJ   s         r;   set_signed_cookie RequestHandler.set_signed_cookie  s;    L 	$$T'$B	
 &	
 		
r:   c                 0   U R                  SS5        U R                  R                  S   nSn[        U[        5      (       aJ  U R                  R                  R                  S5      c  [        S5      eU R                  R                  S   n[        XAX#US9$ )ak  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   r7  )require_settingrG   rp   r   dictr   	Exceptionr1  )rS   r   r   r   secretr7  s         r;   r1  "RequestHandler.create_signed_valueD  s     	_.>?!!**?;fd##((,,];C WXX**33MBK"%k
 	
r:   max_age_daysmin_versionc                     U R                  SS5        Uc  U R                  U5      n[        U R                  R                  S   UUUUS9$ )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.

r5  r6  )r=  r>  )r8  r  decode_signed_valuerG   rp   )rS   r   r   r=  r>  s        r;   get_signed_cookie RequestHandler.get_signed_cookie^  sU    8 	_.>?=OOD)E"%%o6%#
 	
r:   c                 l    U R                  SS5        Uc  U R                  U5      nUc  g[        U5      $ )aF  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.

r5  r6  N)r8  r  get_signature_key_versionr   s      r;   get_signed_cookie_key_version,RequestHandler.get_signed_cookie_key_version  s;     	_.>?=OOD)E=(//r:   r   	permanentstatusc                     U R                   (       a  [        S5      eUc  U(       a  SOSnO'[        U[        5      (       a  SUs=::  a  S::  d   e   eU R	                  U5        U R                  S[        U5      5        U R                  5         g)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)rZ   r:  r   intr   r   r   finish)rS   r   rG  rH  s       r;   redirectRequestHandler.redirect  sv       MNN>%S3Ffc**sf/C/CCC/CCC
DI.r:   chunkc                    U R                   (       a  [        S5      e[        U[        [        [
        45      (       d'  Sn[        U[        5      (       a  US-  n[        U5      e[        U[
        5      (       a(  [        R                  " U5      nU R                  SS5        [        U5      nU R                  R                  U5        g)av  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)r[   RuntimeErrorr   r   r   r9  listr   r   json_encoder   r   r   r   )rS   rO  messages      r;   writeRequestHandler.write  s      >>>??%%t!<==MG%&&f G$$eT""&&u-EOON,MNU!!%(r:   template_namezFuture[None]c                    U R                   (       a  [        S5      eU R                  " U40 UD6n/ n/ n/ n/ n/ n/ n	[        U S0 5      R	                  5        GH  n
U
R                  5       nU(       a  UR                  [        U5      5        U
R                  5       nU(       aG  [        U[        [        45      (       a  UR                  [        U5      5        OUR                  U5        U
R                  5       nU(       a  UR                  [        U5      5        U
R                  5       nU(       aG  [        U[        [        45      (       a  UR                  [        U5      5        OUR                  U5        U
R!                  5       nU(       a  UR                  [        U5      5        U
R#                  5       nU(       d  GMm  U	R                  [        U5      5        GM     U(       a<  U R%                  U5      nUR'                  S5      nUSU [        U5      -   S-   UUS -   nU(       a3  U R)                  U5      nUR'                  S5      nUSU U-   S-   UUS -   nU(       a<  U R+                  U5      nUR-                  S5      nUSU [        U5      -   S-   UUS -   nU(       a3  U R/                  U5      nUR-                  S5      nUSU U-   S-   UUS -   nU(       a1  UR-                  S5      nUSU SR1                  U5      -   S-   UUS -   nU	(       a1  UR-                  S5      nUSU SR1                  U	5      -   S-   UUS -   nU R3                  U5      $ )aQ  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>r:   )r[   rQ  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joinrL  )rS   rW  rJ   htmljs_embedjs_files	css_embedra  
html_headshtml_bodiesmodule
embed_part	file_part	head_part	body_partjsslocjs_bytescsshloc	css_bytess                        r;   renderRequestHandler.render  s    >>?@@!!-:6: 		
d$5r:AACF335JZ 01//1Ii,)>??OOHY$78OOI.,,.J  j!12((*Ii,)>??$$Xi%89$$Y/((*I!!$y/2((*Iy""4	?31 D4 &&x0B;;z*D;b)E1DK?D++H5H;;z*D;)E1DK?D((3C::j)D;c*U2T$%[@D--i8I::j)D;*U2T$%[@D::j)D;*!55=TUKD::j)D;+!66>deLD{{4  r:   rm  c                     / n[        5       nU HM  n[        U5      (       d  U R                  U5      nXC;  d  M+  UR                  U5        UR	                  U5        MO     SR                  S U 5       5      $ )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   Z   #    U  H!  nS [         R                  " U5      -   S-   v   M#     g7f)z<script src="z"" type="text/javascript"></script>Nr   xhtml_escaperP   ps     r;   rT   2RequestHandler.render_linked_js.<locals>.<genexpr>.  s6      
  !!!$%23    )+r   is_absolute
static_urlr   r   rj  )rS   rm  pathsunique_pathsr  s        r;   rd  RequestHandler.render_linked_js  su     uDt$$t,'T"  &  ww 
 	
 
 	
r:   rl  c                 0    SSR                  U5      -   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[
rZ  s   
//]]>
</script>rj  )rS   rl  s     r;   rf  RequestHandler.render_embed_js5  s%     >jj"##$	
r:   ra  c                     / n[        5       nU HM  n[        U5      (       d  U R                  U5      nXC;  d  M+  UR                  U5        UR	                  U5        MO     SR                  S U 5       5      $ )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   Z   #    U  H!  nS [         R                  " U5      -   S-   v   M#     g7f)z<link href="z$" type="text/css" rel="stylesheet"/>Nr  r  s     r;   rT   3RequestHandler.render_linked_css.<locals>.<genexpr>Q  s3      
  V0033 71 1r  r  )rS   ra  r  r  r  s        r;   rg   RequestHandler.render_linked_cssA  su     uDt$$t,'T"  &  ww 
 
 
 	
r:   rn  c                 0    SSR                  U5      -   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">
rZ  s	   
</style>r  )rS   rn  s     r;   ri  RequestHandler.render_embed_cssW  s     ,ejj.CCmSSr:   c                 L   U R                  5       nU(       d  [        R                  " S5      nUR                  R                  nUR                  R                  U:X  aB  UR
                  b5  UR
                  nUR                  R                  U:X  a  UR
                  b  M5  UR                  R                  c   e[        R                  R                  UR                  R                  5      n[        R                     U[        R                  ;  a%  U R                  U5      nU[        R                  U'   O[        R                  U   nSSS5        WR                  U5      nU R                  5       nUR                  U5        UR                   " S0 UD6$ ! , (       d  f       NR= f)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   Nr4   )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)	rS   rW  rJ   template_pathframeweb_fileloadert	namespaces	            r;   r[  RequestHandler.render_string_  s8    ..0MM!$E||//H,,**h65<<;S ,,**h65<<;S<<++777GGOOELL,D,DEM11N$D$DD44]CBH00?'99-H 2 KK&//1	 zz&I&& 21s   <AF
F#c                 &   [        U U R                  U R                  U R                  U R                  R                  U R                  R
                  U R                  U R                  U R                  S9	nUR                  U R                  5        U$ )a  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`.
)	handlerrI   current_userr   _pgettextr  xsrf_form_htmlreverse_url)r9  rI   r  r   	translater  r  r  r  r  r`   )rS   r  s     r;   r  %RequestHandler.get_template_namespacey  su     LL**;;kk##[[))..((

	 	!r:   r  c                     U R                   R                  nSU;   a  US   $ 0 nSU;   a  US   US'   SU;   a  US   US'   [        R                  " U40 UD6$ )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)rG   rp   r   Loader)rS   r  rp   rJ   s       r;   r  %RequestHandler.create_template_loader  ss     ##,,(-..8# $,L#9F<  H,#+,A#BF< }777r:   include_footersc                    U R                   R                  c   eSR                  U R                  5      n/ U l        U R                  (       Gd  SU l        U R
                   H=  nUc   eUR                  U R                  U R                  X!5      u  U l        U l        nM?     U R                   R                  S:X  a  Sn[        U S5      (       aB  U R                  R                  5        H$  nU R                  SUR                  S5      5        M&     [        R                   " SU R                  U R"                  5      nU R                   R                  R%                  XPR                  U5      $ U R
                   H  nUR'                  X!5      nM     U R                   R                  S:w  a%  U R                   R                  R)                  U5      $ [+        5       nUR-                  S5        U$ )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.
Nr:   Tr@   r  z
Set-Cookier)  )rI   rd   rj  r   rZ   _transformstransform_first_chunkr   r   methodr  r  r   r   OutputStringr   ResponseStartLiner   write_headerstransform_chunkrU  r   
set_result)rS   r  rO  	transformcookie
start_linefutures          r;   flushRequestHandler.flush  s    ||&&222++,$$$$(D!!--	(((
 33%%t}}e	%M . ||""f,
 t]++"..557FOOL&2E2Ed2KL 8 "33B8I8I4<<XJ<<**88MM5  "--	!11%I . ||""f,||..44U;;!!$'r:   c                    U R                   (       a  [        S5      eUb  U R                  U5        U R                  (       Gd  U R                  S:X  ag  U R
                  R                  S;   aM  SU R                  ;  a=  U R                  5         U R                  5       (       a  / U l
        U R                  S5        U R                  S;   d  SU R                  s=::  a  S:  a9  O  O6U R                  (       a   S	U R                  -  5       eU R                  5         O>S
U R                  ;  a.  [        S U R                   5       5      nU R                  S
U5        U R
                  R                  c   eU R
                  R                  R!                  S5        U R#                  SS9nU R
                  R                  R%                  5         U R'                  5         SU l         U R)                  5         U R+                  5         U$ )a  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   8   #    U  H  n[        U5      v   M     g 7frN   )len)rP   parts     r;   rT   (RequestHandler.finish.<locals>.<genexpr>  s     $N;M4SYY;Ms   T)r  )r[   rQ  rU  rZ   r   rI   r  r   set_etag_headercheck_etag_headerr   r   _clear_representation_headerssumr   rd   re   r  rL  _logr}   _break_cycles)rS   rO  content_lengthr  s       r;   rL  RequestHandler.finish  s    >>677JJu $$$!!S(LL''?:$--/$$&))++)+D&OOC(  J.3$:K:K3Qc3Q-- .1B1BB- 224!6!$$N4;M;M$N!N 0.A||&&222
 	2248D1&&(		r:   c                 X    SU l         U R                  R                  R                  5       $ )a  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)r[   rI   rd   detachrk   s    r;   r  RequestHandler.detach  s$     ||&&--//r:   c                     S U l         g rN   )r`   rk   s    r;   r  RequestHandler._break_cycles  s     r:   c                 z   U R                   (       a:  [        R                  " S5        U R                  (       d   U R	                  5         ggU R                  5         UR                  S5      nSU;   a:  US   S   n[        U[        5      (       a  UR                  (       a  UR                  nU R                  XS	9   U R                  " U40 UD6  U R                  (       d  U R	                  5         gg! [
         a    [        R                  " SSS9   gf = f! [
         a    [        R                  " S
SS9   Nif = f)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)rZ   r   errorr[   rL  r:  rc   r   r   ru   r   r   write_errorr   )rS   r   rJ   r   r   s        r;   
send_errorRequestHandler.send_error$  s      MMLM>>
UKKM 

H%z*1-I)Y//I4D4D"))3	N[3F3 ~~KKM  ! UMM"DtTU  	NMM=M	Ns#   C3 =D 3DDD:9D:c                 2   U R                   R                  S5      (       aW  SU;   aQ  U R                  SS5        [        R                  " US   6  H  nU R                  U5        M     U R                  5         gU R                  SXR                  S.-  5        g)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>)coderT  N)rp   r   r   	tracebackformat_exceptionrU  rL  r   )rS   r   rJ   lines       r;   r  RequestHandler.write_errorJ  s     ==.//J&4HOONL9!22F:4FG

4  HKKMKK<&<<@Ar:   c                     [        U S5      (       dM  U R                  5       nUb  Xl        U R                  $ U R                  5       U l        U R                  (       d   eU R                  $ )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)rS   locs     r;   r   RequestHandler.localec  s]     tY''&&(C" ||  $668||#|||r:   c                     Xl         g rN   )r  rS   r   s     r;   r   r  x  s    r:   c                     g)zOverride 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")``
Nr4   rk   s    r;   r  RequestHandler.get_user_locale|  s     r:   c                    SU R                   R                  ;   Ga  U R                   R                  S   R                  S5      n/ nU H  nUR                  5       R                  S5      n[	        U5      S:  aX  US   R                  5       R                  S5      (       a1   [        US   R                  5       SS 5      nUS:  a
  [        5       eOS
nUS:  d  M  UR                  US   U45        M     U(       a8  UR                  S SS9  U Vs/ s H  owS   PM	     nn[        R                  " U6 $ [        R                  " U5      $ ! [        [        4 a    S	n Nf = fs  snf )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                     U S   $ )Nr/   r4   )pairs    r;   <lambda>3RequestHandler.get_browser_locale.<locals>.<lambda>  s    d1gr:   T)keyreverse)rI   headerssplitr   r  
startswithfloatr   r   r   sortr   r   )	rS   r   	languageslocaleslanguagepartsscorer  codess	            r;   r  !RequestHandler.get_browser_locale  sC   
  4 44,,->?EEcJIG% (..s3u:>eAhnn&6&A&A$&G&G$ %eAhnn&6qr&: ; 19",,. %
  E19NNE!He#45 & !5tD+237CQ73zz5))zz'"" '	2 $ #$ 4s   !/E
E"
EEc                 f    [        U S5      (       d  U R                  5       U l        U R                  $ )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  rk   s    r;   r  RequestHandler.current_user  s/    @ t_--!%!6!6!8D!!!r:   c                     Xl         g rN   )r  r  s     r;   r  r    s    "r:   c                     g)zbOverride to determine the current user from, e.g., a cookie.

This method may not be a coroutine.
Nr4   rk   s    r;   r  RequestHandler.get_current_user  s    
 r:   c                 X    U R                  SS5        U R                  R                  S   $ )zuOverride to customize the login URL based on the request.

By default, we use the ``login_url`` application setting.
	login_urlz@tornado.web.authenticated)r8  rG   rp   rk   s    r;   get_login_urlRequestHandler.get_login_url  s,    
 	[*FG((55r:   c                 L    U R                   R                  R                  S5      $ )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.
r  )rG   rp   r   rk   s    r;   r   RequestHandler.get_template_path  s!     ((,,_==r:   c                    [        U S5      (       GdT  U R                  5       u  pnU R                  R                  SS5      nU R                  R                  S0 5      nUS:X  a  [        R
                  " U5      U l        OUS:X  a}  [        R                  " S5      nSR                  S[        R
                  " U5      [        R
                  " [        Xb5      5      [        [        [        U5      5      5      /5      U l        O[        S	U5      eUcU  U R                  (       a  S
U;  a  SUS
'   U R                  R                  SS5      nU R                   " XpR                  40 UD6  U R                  $ )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 %dr     xsrf_cookie_name_xsrf)r  _get_raw_xsrf_tokenrp   r   binasciib2a_hexr   r  urandomrj  r   r   r   rK  r   r  r%  )rS   r   token	timestampoutput_versioncookie_kwargsmaskcookie_names           r;   
xsrf_tokenRequestHandler.xsrf_token  s7   B t]++(,(@(@(B%GI!]]../DaHN MM--.BBGM"#+#3#3E#: 1$zz!}#'99 ((. (()EFSY01	$  !!A>RR$$})L46M.1"mm//0BGL-=-=OOr:   c                 ^   [        U S5      (       d  U R                  R                  SS5      nU R                  U5      nU(       a  U R	                  U5      u  p4nOSu  p4nUc-  Sn[
        R                  " S5      n[        R                  " 5       nUc   eUc   eX4U4U l        U R                  $ )an  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  rp   r   r  _decode_xsrf_tokenr  r,  r   r6  )rS   r2  r  r   r-  r.  s         r;   r)  "RequestHandler._get_raw_xsrf_token  s     t.//--++,>HK__[1F,0,C,CF,K)	,<)	}

2 IIK	$$$((($+I#>D ###r:   r  c                     [         R                  [        U5      5      nU(       a  [        UR	                  S5      5      nUS:X  ak  UR                  S5      u  pEpg[        R                  " [        U5      5      n[        U[        R                  " [        U5      5      5      n	[        U5      n
X9U
4$ [        S5      eSn [        R                  " [        U5      5      n	[        [        R                  " 5       5      n
X9U
4$ ! [        R                  [        4 a    [        U5      n	 NIf = f! [         a    [        R                  " SSS9   gf = f)	zOConvert 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  r7  )_signed_value_version_rematchr   rK  groupr  r*  a2b_hexr   r:  Errorr   r   r   debug)rS   r  rR   r   r  mask_strmasked_tokentimestamp_strr1  r-  r.  s              r;   r9  !RequestHandler._decode_xsrf_token5  s   	$(..tF|<Aaggaj/a<?E||C?P<A#++DN;D+D(2B2B4CU2VWE #M 2I"944 $$ABB)$,,T&\:E  		,		22	 !	2 ) LE)
  	$MMDtT#	$s<   B/D, 2D,  D !D, %D)&D, (D))D, ,EEc                    U R                  SS5      =(       dQ    U R                  R                  R                  S5      =(       d%    U R                  R                  R                  S5      nU(       d  [	        SS5      eU R                  U5      u  p#nU R                  5       u  p$nU(       d  [	        SS5      e[        R                  " [        U5      [        U5      5      (       d  [	        SS5      eg)	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   rI   r  r   ru   r9  r)  hmaccompare_digestr   )rS   input_tokenr  r-  expected_tokens        r;   check_xsrf_cookie RequestHandler.check_xsrf_cookieY  s    2 gt, 7||##''67||##''6 	
 C!EFF--k:!#7791C!FGG""4;^0DEEC!KLL Fr:   c                 N    S[         R                  " U R                  5      -   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  r3  rk   s    r;   r  RequestHandler.xsrf_form_html  s+     8!!$//23	
r:   include_hostc                 :   U R                  SS5        U R                  R                  S[        5      R                  nUc  [        U SS5      nU(       a1  U R                  R                  S-   U R                  R                  -   nOSnXT" U R                  U40 UD6-   $ )aJ  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_classrQ  Fz://r)  )	r8  rp   r   StaticFileHandlermake_static_urlr\  rI   protocolhost)rS   r  rQ  rJ   get_urlbases         r;   r  RequestHandler.static_url  s    . 	]L9--##"$5

/ 	 "4?L<<((504<<3D3DDDDgdmmT<V<<<r:   featurec                 ~    U R                   R                  R                  U5      (       d  [        SU< SU< 35      eg)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)rG   rp   r   r:  )rS   r   r\  s      r;   r8  RequestHandler.require_setting  s;    ((,,T22+/:  3r:   c                 <    U R                   R                  " U/UQ76 $ )z$Alias for `Application.reverse_url`.)rG   r  )rS   r   rr   s      r;   r  RequestHandler.reverse_url  s    ++D8488r:   c                     [         R                  " 5       nU R                   H  nUR                  U5        M     SUR	                  5       -  $ )zComputes 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   r  	hexdigest)rS   hasherr  s      r;   compute_etagRequestHandler.compute_etag  s?     &&DMM$ '((***r:   c                 P    U R                  5       nUb  U R                  SU5        gg)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  )rf  r   )rS   etags     r;   r  RequestHandler.set_etag_header  s+       "OOFD) r:   c           	      v   [        U R                  R                  SS5      5      n[        R                  " S[        U R
                  R                  R                  SS5      5      5      nU(       a  U(       d  gSnUS   S:X  a  SnU$ S	[        S
[        4S jnU H  nU" U5      U" U5      :X  d  M  Sn  U$    U$ )aD  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xrK   c                 <    U R                  S5      (       a  U SS  $ U $ )Ns   W/r0   r  )rn  s    r;   val-RequestHandler.check_etag_header.<locals>.val  s!     !U 3 3qu::r:   )r   r   r   r  findallrI   r  r   )rS   computed_etagetagsr>  rq  ri  s         r;   r   RequestHandler.check_etag_header  s    " T]]..vr:; 

!4(<(<(@(@RT(U#V
 E8tE ;u ; ; t9M 22 E	  r:   
transformsOutputTransformc           
      r  #    Xl          U R                  R                  U R                  ;  a  [	        S5      e[        U R                  5      (       d   U R                  R                  5         U Vs/ s H  oPR                  U5      PM     snU l        UR                  5        VVs0 s H  u  pgX`R                  XvS9_M     snnU l        U R                  R                  S;  a:  U R                  R                  R!                  S5      (       a  U R#                  5         U R%                  5       nUb
  UI Sh  vN nU R&                  b  [)        U R&                  S5        U R*                  (       a  g[        U R                  5      (       a   U R                  R,                  I Sh  vN   [3        X R                  R                  R5                  5       5      n	U	" U R                  0 U R                  D6nUb
  UI Sh  vN nU R6                  (       a#  U R*                  (       d  U R9                  5         ggg! [        R                   a  n[	        SSU-  5      UeSnAff = fs  snf s  snnf  GN5 N! [.        R0                   a     gf = f N! [:         a  n U R=                  U5        O%! [:         a    [>        R@                  " SS	S
9   Of = fSnO! Snf = fU R&                  bD  U R&                  RC                  5       (       d   U R&                  RE                  S5         SnAg SnAg SnAgSnAff = f7f)z7Executes this request with the given output transforms.rt   r   zInvalid body: %sNr   )r?   r@   rE   xsrf_cookieszException in exception handlerTr  )#r  rI   r  rF   ru   r   rh   _parse_bodyr   HTTPInputErrorr   	path_argsr_   path_kwargsrG   rp   r   rM  rz   r]   r   r[   r   r   r   r\  lowerr\   rL  r:  _handle_request_exceptionr   r  r   r  )
rS   rw  rr   rJ   eargr$  r   resultr  s
             r;   _executeRequestHandler._execute  s     &>	7||""$*@*@@n$ ,DNN;;HLL,,. DHH4C22374HDNAG AOv'''22 D
 ||"" +  ""++//??&&(\\^F!%$$0 343H3H$O~~'77
,,3333 T<<#6#6#<#<#>?FT^^@t/?/?@F!%   *8 Q  .. H#C);a)?@aGH I  & 411  &  	7..q1 O>NO $$09N9N9S9S9U9U %%0066	 :V0	7s   L7A	J H5 .J 2I!J 'I&A5J 7I,88J 0L71J I1 %I/&I1 *AJ ;J<6J 2L75I	IIJ /I1 1JJ L7JJ 
L4J*)K*K	KKKL/KA
L/ L7/L44L7c                     [        5       e)zImplement this method to handle streamed request data.

Requires the `.stream_request_body` decorator.

May be a coroutine for flow control.
NotImplementedError)rS   rO  s     r;   data_receivedRequestHandler.data_receivedI  s     "##r:   c                 :    U R                   R                  U 5        g)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)rG   log_requestrk   s    r;   r  RequestHandler._logR  s     	$$T*r:   c                     SR                  U R                  R                  U R                  R                  U R                  R                  5      $ )Nz
{} {} ({}))r   rI   r  uri	remote_iprk   s    r;   _request_summaryRequestHandler._request_summary[  s<    ""LLLLLL""
 	
r:   r  c                    [        U[        5      (       a+  U R                  (       d  U R                  " UR                  6   g  U R
                  " [        R                  " 5       6   U R                  (       a  g [        U[        5      (       a.  U R                  UR                  [        R                  " 5       S9  g U R                  S[        R                  " 5       S9  g ! [         a    [        R                  " SSS9   Nf = f)NzError in exception loggerTr    )r   Finishr[   rL  rr   log_exceptionr  r  r:  r   r  ru   r  r   )rS   r  s     r;   r  (RequestHandler._handle_request_exceptionb  s    a  >>QVV$	F/
 >> a##OOAMMCLLNOCOOC#,,.O9  	F MM5E	Fs   "C C?>C?typzOptional[Type[BaseException]]tbc                 .   [        U[        5      (       aO  UR                  5       nU(       a7  SnUR                  U R	                  5       U/n[
        R                  " U/UQ76   gg[        R                  " SU R	                  5       U R                  XU4S9  g)a  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   ru   get_messager   r  r   warningr   r  rI   )rS   r  r   r  log_messager   rr   s          r;   r  RequestHandler.log_exceptionx  s     eY''++-K$))4+@+@+BKP.. 
 MM+%%'b)	r:   rq  UIModulec                 ,   ^ ^^ S[         4UUU 4S jjnU$ )NrK   c                     > [        TS5      (       d  0 Tl        TTR                  ;  a  T" T5      TR                  T'   TR                  T   R                  " U 0 UD6n[        U5      $ )NrY  )r  rY  r|  r   )rr   rJ   renderedrq  r   rS   s      r;   r|  )RequestHandler._ui_module.<locals>.render  sf    4!233')$4///-3D\$$T*++D188$I&IHH%%r:   )r   )rS   r   rq  r|  s   ``` r;   
_ui_moduleRequestHandler._ui_module  s    	&s 	& 	& r:   r  c                    ^ ^ UU 4S j$ )Nc                     > T" T/U Q70 UD6$ rN   r4   )rr   rJ   r  rS   s     r;   r  +RequestHandler._ui_method.<locals>.<lambda>  s    vd'DT'DV'Dr:   r4   )rS   r  s   ``r;   rO   RequestHandler._ui_method  s	    DDr:   c                 @    / SQnU H  nU R                  U5        M     g )N)Content-EncodingzContent-Languager   )r   )rS   r  hs      r;   r  ,RequestHandler._clear_representation_headers  s"     KAa  r:   )rY  r\   r  r[   r   rZ   r  r  r]   r6  r   r   r  r   r   rG   r}  r~  rI   r`   rK   NrN   T)NN/N)r&  N)N   N)FN)F)r  )en_US)zthis feature)r5   r6   r7   r8   __doc__rF   r$   r   __annotations__r  	threadingLockr  r  compiler   _stream_request_bodyr  r}  r~  r   HTTPServerRequestr    rY   rl   rg   propertyr   rp   rw   headr   postdeletepatchputoptionsr"   r#   rz   r}   rf   rc   r   rK  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.  r2  set_secure_cookier1  rA  get_secure_cookierE  get_secure_cookie_key_versionrM  r9  rU  r|  r'   rd  rf  rg  ri  r[  r  r   
BaseLoaderr  r  rL  r   IOStreamr  r  r  r  r   r   Localesetterr  r  r  r  r  r  r3  r)  r9  rM  r  r  r8  r  rf  r  r  r  r  r  r  BaseExceptionr  r-   r  r)   r&   r  rO   r  r9   __classcell__rh   s   @r;   r=   r=      s   	*uS#X  %NN,"$**-D"E  KIK""" ++" 	"
 
"@ J& )$sCx. ) )3 # $  !D
C D"F!E
C#G)D/2 "6&/Jc J8C= JD J&!C !@s @< @D @Cs C< CD C$ $ $ **%AB< C 0  s 4 3   6BRV"3KO	 
 6:"&/3	#  8D	PP tS"334P 	P
 
#P$H# Hd Hd3i H c C  PS   6BRV"3KO	 
 6:"&/3	#  8D	UU tS"334U 	U
 
#U&Ms M4 M49 M s S  QT   6BRV"3KO	 
 6:"&/3	#  8D	VV tS"334V 	V
 
#V&N ND NDI N  tS"334 S$u+%&	
  
# HL!%c4;&6!7@D	cU (3- 3 ( $c4<<#6#667 $ $
 s S S   s T Xc]  s Xc] hsm " !%DH(,Q "&"&QQ S%Z Q 	Q
 %uh.?.? ?@AQ Q uoQ #Q Q Q 3-Q Q 
QfC C C C8.# .$ .F )+!%+
+
 S%Z +
 uo	+

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

 c]%
 
%%
N * 1500 (0	#0, %B! JN#'9A#	()5eT!12 )t )@I!C I!3 I!> I!V
# 
3 
.

 

E 


8C= 
S 
,T(5/ Te T'3 '# '% '4S#X .8C 8H<O<O 8*0T 0n 0d7HU3t+;%<= 7 7r0)) 0
$c $3 $4 $Ls c d 2 --  ( ]]GNN11 d  '..*?*?!@ ## #GNN<Q<Q #6 !"c !" !"F ## #$ # ## 6s 6>8C= > 7 E 7  7 r$U8C=%+F%G $6"$"$	x}huox>	?"$H$ML
 
( 9=$=$='/~$=HK$=	$=LC # 4 9 9C 9C 9+hsm +	*&4 &PC701C7:?C7KPC7	C7J$5 $Xio-F $+
# 
:= :T :,, & ]#	
 
:	s 	D,< 	#s(AS 	E#s(!3 Ec8J E! !r:   r=   _RequestHandlerType)boundclsrK   c                 V    [        U [        5      (       d  [        SU 5      eSU l        U $ )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   r  r  s    r;   stream_request_bodyr    s,    * c>**EsKK#CJr:   c                 \    [        U [        5      (       d  [        SU 5      eU R                  $ )Nr  r  r  s    r;   r   r     s)    c>**EsKK###r:   r  .c                 v   ^  [         R                  " T 5      S[        S[        [        S      4U 4S jj5       nU$ )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.
rS   rK   Nc                   > U R                   R                  R                  S5      (       a  U R                   R                  S;   au  U R                   R                  R	                  S5      nU(       aH  U R                   R
                  (       a  USU R                   R
                  -   -  nU R                  USS9  g O[        S5      eT" U /UQ70 UD6$ Nr  r  ?TrG    )rI   r  endswithr  rstripqueryrM  ru   rS   rr   rJ   r  r  s       r;   wrapperremoveslash.<locals>.wrapper  s     <<%%c**||""o5ll''..s3||))sT\\%7%777MM#M6	   n$d,T,V,,r:   	functoolswrapsr=   r"   r#   r  r  s   ` r;   removeslashr    s@     __V--	)D/	"- - Nr:   c                 v   ^  [         R                  " T 5      S[        S[        [        S      4U 4S jj5       nU$ )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.
rS   rK   Nc                 |  > U R                   R                  R                  S5      (       d  U R                   R                  S;   aa  U R                   R                  S-   nU R                   R                  (       a  USU R                   R                  -   -  nU R                  USS9  g [        S5      eT" U /UQ70 UD6$ r  )rI   r  r  r  r  rM  ru   r  s       r;   r  addslash.<locals>.wrapper  s     ||  ))#..||""o5ll''#-<<%%3!3!333CcT2C. d,T,V,,r:   r  r  s   ` r;   addslashr    s@     __V--	)D/	"- - Nr:   c            	          ^  \ rS rSrSr SSSS\\   SS4U 4S jjjrS	\S\4U 4S
 jjr	S\
S\R                  S\
S\\R                     4U 4S jjrSrU =r$ )_ApplicationRouteri
  a  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.
NrG   rH   rulesrK   c                 ^   > [        U[        5      (       d   eXl        [        TU ]  U5        g rN   )r   rH   rG   rX   rY   )rS   rG   r  rh   s      r;   rY   _ApplicationRouter.__init__  s+     +{3333&r:   rulec                    > [         TU ]  U5      n[        UR                  [        [
        45      (       a%  [        U R                  UR                  5      Ul        U$ rN   )rX   process_ruler   targetrR  tupler  rG   )rS   r  rh   s     r;   r  _ApplicationRouter.process_rule  sI    w#D)dkkD%=11,  $++DK r:   r  rI   target_paramsc                    > [        U5      (       a2  [        U[        5      (       a  U R                  R                  " X!40 UD6$ [
        TU ]  " X40 UD6$ rN   )r   r  r=   rG   get_handler_delegaterX   get_target_delegate)rS   r  rI   r  rh   s       r;   r  &_ApplicationRouter.get_target_delegate&  sU     6??z&.AA##88#0  w*6LmLLr:   )rG   rN   )r5   r6   r7   r8   r  r"   r   rY   r   r  r    r   r  HTTPMessageDelegater  r9   r  r  s   @r;   r  r  
  s     HL ( 19)1D 	    $ MM$,$>$>MQTM	(..	/M Mr:   r  c                   @   \ rS rSrSr   S-S\\   S\\   S\\\	S         S\
S	S4
S
 jjr S.\R                  \R                  R                   SSS.S\S\\   S\R$                  S\S\\   S\S\
S	\4S jjjrS\S\S	S4S jrS\	S   S	S4S jrS\
S	S4S jrS\
S	S4S jrS\R6                  S	\\S      4S jrS\R6                  S\
S	S 4S! jr   S-S\R6                  S"\	\   S#\\ \\
4      S$\\\!      S%\\ \\!4      S	S 4S& jjr"S'\S(\
S	\4S) jr#S*\S	S4S+ jr$S,r%g)/rH   i1  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_hostrw  rx  rp   rK   c                    UcS  / U l         UR                  S5      (       d  UR                  S5      (       a  U R                   R                  [        5        OX0l         X l        X@l        [        [        [        S.U l	        0 U l
        U R                  UR                  S0 5      5        U R                  UR                  S0 5      5        U R
                  R                  S5      (       a  U R
                  S   n[        U=(       d    / 5      nUR                  SS5      nUR                  S	[        5      nUR                  S
0 5      nXXS'   [        R                   " U5      S-   SS4 H  n	UR#                  SXU45        M     U R
                  R                  S5      (       ap  U R
                  R%                  SS5        U R
                  R%                  SS5        U R
                  R%                  SS5        U R
                  R%                  SS5        ['        X5      U l        ['        U [+        [-        5       U R(                  5      /5      U l        U R
                  R                  S5      (       a  SSKJn
  U
R5                  5         g g )Ncompress_responsegzip)linkifyr  Templaterb   r^   rS  static_url_prefix/static/rT  static_handler_argsr  z(.*)z/(favicon\.ico)z/(robots\.txt)r   rB  
autoreloadTcompiled_template_cacheFstatic_hash_cacher  )r	  )rw  r   r   GZipContentEncodingr   rp   _linkify_xsrf_form_htmlTemplateModulerb   r^   _load_ui_modules_load_ui_methodsrR  rU  r  r   insert
setdefaultr  wildcard_routerr   r   default_routerr   r	  start)rS   r  r   rw  rp   r  r  rT  r  patternr	  s              r;   rY   Application.__init__  s     DO||/00HLL4H4H&&':;(O( -&

 hll<<=hll<<===]++==/DHN+H (-@* M#+<<&(9$  #+,,/Db"I*.'		+,w6"!
 GCV#WX ==W%%MM$$\48MM$$%>FMM$$%8%@MM$$%6=1$A04
d&:&:;<

 ==\*** +r:   F)familybacklogflags
reuse_portportaddressr  r  r  r  rJ   c          	      F    [        U 40 UD6nUR                  UUUUUUS9  U$ )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)	rS   r  r  r  r  r  r  rJ   servers	            r;   r   Application.listen  s>    B D+F+! 	 	
 r:   host_patternhost_handlersc                    [        U5      n[        U[        X5      5      nU R                  R                  R                  SU5        U R                  b2  U R                  R                  [        XR                  5      U4/5        gg)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#  )rS   r#  r$  host_matcherr  s        r;   add_handlersApplication.add_handlers  sw     #<0L"4T"IJ!!((T2(  **$T+D+DE}UV )r:   transform_classc                 :    U R                   R                  U5        g rN   )rw  r   )rS   r*  s     r;   add_transformApplication.add_transform  s    /r:   methodsc           
         [        U[        R                  5      (       a5  U R                  [	        U5       Vs0 s H  o"[        X5      _M     sn5        g [        U[        5      (       a  U H  nU R                  U5        M     g UR                  5        HZ  u  pEUR                  S5      (       a  M  [        US5      (       d  M0  US   R                  5       US   :X  d  ML  XPR                  U'   M\     g s  snf )Nr  __call__r   )r   types
ModuleTyper  dirr\  rR  r_   r  r  r  r^   )rS   r.  rQ   rR   r   fns         r;   r  Application._load_ui_methods  s    gu//00!!3w<"P<agg&9#9<"PQ&&%%a(  $MMO,,J//Q472,.OOD) , #Qs   C4rW   c           
         [        U[        R                  5      (       a5  U R                  [	        U5       Vs0 s H  o"[        X5      _M     sn5        g [        U[        5      (       a  U H  nU R                  U5        M     g [        U[        5      (       d   eUR                  5        H+  u  pE [        U[        5      (       a  XPR                  U'   M+  M-     g s  snf ! [         a     MB  f = frN   )r   r1  r2  r  r3  r\  rR  r9  r_   r  r  rb   r   )rS   rW   rQ   rR   r   r  s         r;   r  Application._load_ui_modules
	  s    gu//00!!3w<"P<agg&9#9<"PQ&&%%a(  gt,,,,$]]_	!#x0003- 1 - #Q ! s   C2#C!!
C/.C/rI   c                 D    U R                  U5      nUR                  5       $ rN   )find_handlerexecute)rS   rI   
dispatchers      r;   r0  Application.__call__	  s#     &&w/
!!##r:   _HandlerDelegatec                 <   U R                   R                  U5      nUb  [        SU5      $ U R                  R	                  S5      (       a:  U R                  UU R                  S   U R                  R	                  S0 5      5      $ U R                  U[        SS05      $ )Nr=  default_handler_classdefault_handler_argsr   r  )r  r9  r+   rp   r   r  ErrorHandler)rS   rI   rJ   routes       r;   r9  Application.find_handler 	  s     ##009*E22==455,,56!!"8"=  ((,PS@TUUr:   target_classtarget_kwargsr}  r~  c                     [        XX#XE5      $ )a%  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=  )rS   rI   rD  rE  r}  r~  s         r;   r   Application.get_handler_delegate0	  s    $  <	
 	
r:   r   rr   c                 b    U R                   R                  " U/UQ76 nUb  U$ [        SU-  5      e)a  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.
z%s not found in named urls)r  r  KeyError)rS   r   rr   reversed_urls       r;   r  Application.reverse_urlF	  s<     **66tCdC#3d:;;r:   r  c                    SU R                   ;   a  U R                   S   " U5        gUR                  5       S:  a  [        R                  nO5UR                  5       S:  a  [        R                  nO[        R
                  nSUR                  R                  5       -  nU" SUR                  5       UR                  5       U5        g)zWrites 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)	rp   r   r   infor  r  rI   request_timer  )rS   r  
log_methodrO  s       r;   r  Application.log_requestU	  s     T]]*MM.)'2#%#J!C'#++J#))J < < >> $$&		
r:   )r   r  rp   rw  r^   rb   r  r7  rN   )&r5   r6   r7   r8   r  r"   r   r   r%   r)   r    rY   socket	AF_UNSPECr   netutil_DEFAULT_BACKLOGrK  AddressFamilyr   r
   r   r(  r,  r  r  r   r  r#   r0  r9  r=   r   r   r  r  r  r9   r4   r:   r;   rH   rH   1  s7   Ph )-&*>B	69%6 sm6 T$'8"9:;	6
 6 
6v "&*
 (.'7'777# ** #*
 $$* * }* * * 
*X Y 4  0T2C-D 0 0/ / /  $11$	)D/	"$V11V=@V	V( 37+/26
++
 >*
  S#X/	

 DK(
 d3:./
 

,< <C <C <
> 
d 
r:   rH   c                   4   \ rS rSrS\S\R                  S\\   S\	\
\\4      S\	\\      S\	\
\\4      SS	4S
 jrS\\R"                  \R$                  4   S\R&                  S\	\S	      4S jrS\S\	\S	      4S jrSS jrSS jrS\	\S	      4S jrSrg	)r=  io	  rG   rI   handler_classhandler_kwargsr}  r~  rK   Nc                     Xl         UR                  U l        X l        X0l        U=(       d    0 U l        U=(       d    / U l        U=(       d    0 U l        / U l        [        U R                  5      U l	        g rN   )
rG   rd   rI   rX  rY  r}  r~  chunksr   r  )rS   rG   rI   rX  rY  r}  r~  s          r;   rY   _HandlerDelegate.__init__p	  sa     '!,,*,2"b&,"#;D<N<N#O r:   r  r  c                 x    U R                   (       a)  [        5       U R                  l        U R	                  5       $ g rN   )r  r   rI   r   r:  )rS   r  r  s      r;   headers_received!_HandlerDelegate.headers_received	  s*    
 ##(.DLL%<<>!r:   datac                     U R                   (       a  U R                  R                  U5      $ U R                  R	                  U5        g rN   )r  r  r  r[  r   )rS   r`  s     r;   r  _HandlerDelegate.data_received	  s5    ##<<--d33KKt$r:   c                     U R                   (       a!  [        U R                  R                  S 5        g SR	                  U R
                  5      U R                  l        U R                  5         g )Nr:   )r  r   rI   r   rj  r[  bodyr:  rk   s    r;   rL  _HandlerDelegate.finish	  sC    ##.t||/H/H$O !$ 5DLLLLNr:   c                 j    U R                   (       a  U R                  R                  5         g S U l        g rN   )r  r  rf   r[  rk   s    r;   rf   $_HandlerDelegate.on_connection_close	  s"    ##LL,,.DKr:   c                    U R                   R                  R                  SS5      (       dN  [        R                     [        R
                  R                  5        H  nUR                  5         M     S S S 5        U R                   R                  R                  SS5      (       d:  U R                   R                  R                  S[        5      nUR                  5         U R                  " U R                   U R                  40 U R                  D6U l        U R                   R                   Vs/ s H  o3" U R                  5      PM     nnU R                  (       a  [        5       U R                  l        ["        R$                  " U R                  R&                  " U/U R(                  Q70 U R*                  D65      nUR-                  S 5        U R                  R                   $ ! , (       d  f       GNz= fs  snf )Nr
  Tr  rT  c                 "    U R                  5       $ rN   )r  )fs    r;   r  *_HandlerDelegate.execute.<locals>.<lambda>	  s
    
r:   )rG   rp   r   r=   r  r  r   resetrU  rX  rI   rY  r  rw  r  r   r]   r	   convert_yieldedr  r}  r~  add_done_callback)rS   r  rT  r  rw  futs         r;   r:  _HandlerDelegate.execute	  s    ((,,-FMM55,>>EEGFLLN H 6 ((,,-@$GG#'#3#3#<#<#@#@&(9$  !&&())dll
.2.A.A
 04/?/?/J/JK/J!ao/J
K##,2HDLL) !!LL!!*Rt~~RAQAQR
 	23 ||,,,= 65 Ls   6G%.G7%
G4)
rG   r[  rd   r  rX  rY  r}  r~  rI   r  r  )r5   r6   r7   r8   rH   r   r  r)   r=   r"   r   r   r    r%   r   rY   r!   RequestStartLiner  r   r#   r^  r  rL  rf   r:  r9   r4   r:   r;   r=  r=  o	  s   P P ++P N+	P
 !c3h0P DK(P d3:./P 
P&(33X5O5OOP %% 
)D/	"	% HYt_,E #-)D/2 #-r:   r=  c                       \ rS rSrSr  SS\S\\   S\S\SS4
S	 jjr	\
S\\   4S
 j5       rS\\   4S jrS\4S jrSrg)ru   i	  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.
Nr   r  rr   rJ   rK   c                 V    Xl         X l        X0l        UR                  SS 5      U l        g )Nr   )r   _log_messagerr   r   r   )rS   r   r  rr   rJ   s        r;   rY   HTTPError.__init__	  s'     ''	jj40r:   c                     U R                   (       a-  U R                  (       d  U R                   R                  SS5      $ U R                   $ )z6
A backwards compatible way of accessing log_message.
%z%%)rt  rr   replacerk   s    r;   r  HTTPError.log_message	  s8    
 TYY$$,,S$77   r:   c                     U R                   (       a*  U R                  (       a  U R                   U R                  -  $ U R                   $ rN   )rt  rr   rk   s    r;   r  HTTPError.get_message	  s2    $$tyy00   r:   c                     SU R                   U R                  =(       d*    [        R                  R	                  U R                   S5      4-  nU R                  5       nU(       a  US-   U-   S-   $ U$ )NzHTTP %d: %sr   z ())r   r   r   r   r   r  )rS   rT  r  s      r;   __str__HTTPError.__str__	  sk    KKN8--11$2B2BIN#
 
 &&(T>K/#55Nr:   )rt  rr   r   r   )r  N)r5   r6   r7   r8   r  rK  r"   r   r    rY   r  r  r  r~  r9   r4   r:   r;   ru   ru   	  s    0 %)
1
1 c]
1 	
1
 
1 

1 !Xc] ! !!Xc] !
	 	r:   ru   c                       \ rS rSrSrSrg)r  i
  ar  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`.
r4   N)r5   r6   r7   r8   r  r9   r4   r:   r;   r  r  
  s    0 	r:   r  c                   8   ^  \ rS rSrSrS\SS4U 4S jjrSrU =r$ )r   i"
  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_namerK   Nc                 8   > [         TU ]  SSU-  5        Xl        g )Nr   zMissing argument %s)rX   rY   r  )rS   r  rh   s     r;   rY   MissingArgumentError.__init__+
  s    3h>? r:   )r  )	r5   r6   r7   r8   r  r   rY   r9   r  r  s   @r;   r   r   "
  s     ! ! ! !r:   r   c                   >    \ rS rSrSrS\SS4S jrS
S jrS
S jrS	r	g)rA  i0
  zBGenerates an error response with ``status_code`` for all requests.r   rK   Nc                 &    U R                  U5        g rN   )r   )rS   r   s     r;   rg   ErrorHandler.initialize3
  s    $r:   c                 ,    [        U R                  5      erN   )ru   r   rk   s    r;   rz   ErrorHandler.prepare6
  s    ))**r:   c                     g rN   r4   rk   s    r;   rM  ErrorHandler.check_xsrf_cookie9
  r   r:   r4   r  )
r5   r6   r7   r8   r  rK  rg   rz   rM  r9   r4   r:   r;   rA  rA  0
  s"    L%c %d %+r:   rA  c                   H    \ rS rSrSrSS\S\SS4S jjrS\S	\SS4S
 jr	Sr
g)RedirectHandleri@
  a  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.
r   rG  rK   Nc                     Xl         X l        g rN   )_url
_permanent)rS   r   rG  s      r;   rg   RedirectHandler.initializea
  s    	#r:   rr   rJ   c                 4   U R                   R                  " U0 UD6nU R                  R                  (       aH  [        R
                  " U[        [        R                  " U R                  R                  5      5      5      nU R                  X0R                  S9  g )Nr  )
r  r   rI   r   r   
url_concatrR  	qs_to_qslrM  r  )rS   rr   rJ   to_urls       r;   r   RedirectHandler.gete
  sl    !!4262<<''((X''(D(DEFF 	f8r:   )r  r  r  )r5   r6   r7   r8   r  r   r   rg   r    r   r9   r4   r:   r;   r  r  @
  s<    @$c $d $d $9 9 9 9r:   r  c                      \ rS rSrSrSr0 r\R                  " 5       r	S*S\
S\\
   SS4S jjr\S+S	 j5       rS\
S\S   4S
 jrS,S\
S\SS4S jjrS\\
   4S jrS+S jrS\4S jr\S\
S\
S\
4S j5       rS\
S\
S\\
   4S jr\ S-S\
S\\   S\\   S\\SS4   4S jj5       r\S\
S\
4S j5       rS\R<                  4S jrS\4S jr S\\!RB                     4S jr"S\
4S jr#S\
SS4S jr$S\
S\\!RB                     S\
S\4S  jr%\ S,S!\&\
\'4   S\
S"\S\
4S# jj5       r(S$\
S\
4S% jr)\S!\&\
\'4   S\
S\\
   4S& j5       r*\S'\
S\\
   4S( j5       r+S)r,g).rU  ip
  a  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_filenamerK   c                     Xl         X l        g rN   )rootr  )rS   r  r  s      r;   rg   StaticFileHandler.initialize
  s    	 0r:   c                 ^    U R                      0 U l        S S S 5        g ! , (       d  f       g = frN   )_lock_static_hashesr  s    r;   rl  StaticFileHandler.reset
  s    YY!#C YYs   
,c                 "    U R                  USS9$ )NF)include_body)r   rS   r  s     r;   r  StaticFileHandler.head
  s    xx5x11r:   r  c                 l  #    U R                  U5      U l        AU R                  U R                  U R                  5      nU R	                  U R                  U5      U l        U R
                  c  g U R                  5       U l        U R                  5         U R                  5       (       a  U R                  S5        g S nU R                  R                  R                  S5      nU(       a  [        R                  " U5      nU R!                  5       nU(       a  Uu  pxUb  US:  a  Xv-  nUS:  a  SnUb  Xv:  d  Ub  Xx:  d  US:X  a9  U R                  S5        U R#                  SS5        U R#                  SSU 35        g Ub  X:  a  UnXh=(       d    UU=(       d    S-
  :w  a8  U R                  S	5        U R#                  S[        R$                  " XxU5      5        OS =pxUb  Ub  X-
  n	OUb  Un	O
Ub  Xg-
  n	OUn	U R#                  S
U	5        U(       ah  U R'                  U R
                  Xx5      n
[)        U
[*        5      (       a  U
/n
U
 H-  n U R-                  U5        U R/                  5       I S h  vN   M/     g U R                  R4                  S:X  d   eg  N&! [0        R2                   a       g f = f7f)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   rI   r  r   r   _parse_request_rangeget_content_sizer   _get_content_rangeget_contentr   r   rU  r  r   r   r  )rS   r  r  r  request_rangerange_headersizer  endr  contentrO  s               r;   r   StaticFileHandler.get
  st    ''-	..tyy$))D!88MR%..0!!##OOC ||++//8 %99,GM$$&&JE UQY19E!]s5< $=8D61BC3: 
 t
33$#X%@%@T%R E [N_ N!\N!N(.9&&t'9'95FG'5))") JJu%**,&& ! <<&&&000	 '11 s<   I	J4$J0J1J5"J4JJ1-J40J11J4c                 r    U R                   c   eU R                  U R                   5      nU(       d  gSU S3$ )zSets 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")r  _get_cached_version)rS   version_hashs     r;   rf  StaticFileHandler.compute_etag  sA     !!---//0B0BC<.""r:   c                 p   U R                  SS5        U R                  5         U R                  b  U R                  SU R                  5        U R                  5       nU(       a  U R                  SU5        U R	                  U R
                  U R                  U5      nUS:  az  U R                  S[        R                  R                  [        R                  R                  5      [        R                  " US9-   5        U R                  S	S
[        U5      -   5        U R                  U R
                  5        g)zMSets 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)rS   content_type
cache_times      r;   r  StaticFileHandler.set_headers&  s    
 	1==$OOOT]];,,.OONL9((DMM<P
>OO!!%%h&7&7&;&;<$$Z89
 OOOZ#j/-IJtyy)r:   c                    U R                   R                  R                  S5      (       a  U R                  5       $ U R                   R                  R                  S5      nUbs   [        R
                  R                  U5      nUR                  c'  UR                  [        R                  R                  S9nU R                  c   eX R                  :  a  gg! [         a     gf = f)zWReturns True if the headers indicate that we should return 304.

.. versionadded:: 3.1
rl  zIf-Modified-SinceF)tzinfoT)rI   r  r   r  emailutilsparsedate_to_datetimer:  r  rx  r   r  r  r  )rS   	ims_valueif_sinces      r;   r  #StaticFileHandler.should_return_304@  s     <<##O44))++ LL((,,-@A	  ;;<<YG &#++83D3D3H3H+I==,,,==(  s   $C 
C$#C$r  c                 ~    [         R                  R                  [         R                  R                  X5      5      nU$ )a  Returns the absolute location of ``path`` relative to ``root``.

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

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

.. versionadded:: 3.1
)r  r  abspathrj  )r  r  r  r  s       r;   r  #StaticFileHandler.get_absolute_pathY  s(     ''//"'',,t":;r:   r  c                    [         R                  R                  U5      nUR                  [         R                  R                  5      (       d  U[         R                  R                  -  nU[         R                  R                  -   R                  U5      (       d  [        SSU R                  5      e[         R                  R                  U5      (       a  U R                  b  U R                  R                  R                  S5      (       d^  U R                  R                  R                  S5      (       a  [        SS5      eU R                  U R                  R                  S-   SS9  g[         R                  R                  X R                  5      n[         R                  R                  U5      (       d  [        S	5      e[         R                  R                  U5      (       d  [        SS
U R                  5      eU$ )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
rH  z"%s is not in root static directoryNr  z//z-cannot redirect path with two initial slashesTr  r  z%s is not a file)r  r  r  r  sepr  ru   isdirr  rI   rM  rj  existsisfile)rS   r  r  s      r;   r  (StaticFileHandler.validate_absolute_pathj  sf   0 wwt$}}RWW[[)) BGGKKD +77==C!EtyyQQ77==''D,A,A,M <<$$--c22<<$$//55 $L  dll//#5FGGLL8M8MNMww~~m,,C. ww~~m,,C!3TYY??r:   r  r  r  c              #   8  #    [        US5       nUb  UR                  U5        Ub  X2=(       d    S-
  nOSn SnUb  XV:  a  UnUR                  U5      nU(       a  Ub  U[        U5      -  nUv   OUb  US:X  d   e SSS5        gMQ  ! , (       d  f       g= f7f)a
  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   i   )openseekreadr  )r  r  r  r  file	remaining
chunk_sizerO  s           r;   r  StaticFileHandler.get_content  s     $ '4 D 		% :A.	 	&
(Y-C!*J		*- ,!SZ/	K ,(A~-~' !   ! s#   BA/B	>	BB		
BBc                    U R                  U5      n[        R                  " 5       n[        U[        5      (       a!  UR                  U5        UR                  5       $ U H  nUR                  U5        M     UR                  5       $ )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
)r  rb  sha512r   r   r  rd  )r  r  r`  re  rO  s        r;   get_content_version%StaticFileHandler.get_content_version  so     w'!dE""MM$ !! e$ !!r:   c                     U R                   c   e[        U S5      (       d%  [        R                  " U R                   5      U l        U R                  $ )N_stat_result)r  r  r  statr  rk   s    r;   _statStaticFileHandler._stat  sD    !!---t^,, "(:(: ;D   r:   c                 :    U R                  5       nUR                  $ )zRetrieve the total size of the resource at the given path.

This method may be overridden by subclasses.

.. versionadded:: 3.1

.. versionchanged:: 4.0
   This method is now always called, instead of only when
   partial results are requested.
)r  st_size)rS   stat_results     r;   r  "StaticFileHandler.get_content_size  s     jjl"""r:   c                     U R                  5       n[        R                  R                  [        UR                  5      [        R
                  R                  5      nU$ )aH  Returns the time that ``self.absolute_path`` was last modified.

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

.. versionadded:: 3.1

.. versionchanged:: 6.4
   Now returns an aware datetime object instead of a naive one.
   Subclasses that override this method may return either kind.
)r  r   fromtimestamprK  st_mtimer  r  )rS   r  r  s      r;   r  #StaticFileHandler.get_modified_time  sJ     jjl $$22$$%x'8'8'<'<
 r:   c                     U R                   c   e[        R                  " U R                   5      u  pUS:X  a  gUb  gUb  U$ g)zXReturns the ``Content-Type`` header to be used for this request.

.. versionadded:: 3.1
r  zapplication/gzipzapplication/octet-stream)r  	mimetypes
guess_type)rS   	mime_typeencodings      r;   r  "StaticFileHandler.get_content_type  sV    
 !!---'2243E3EF	v% !-" .r:   c                     g)z1For subclass to add extra headers to the responseNr4   r  s     r;   r  #StaticFileHandler.set_extra_headers!  r   r:   r  r  c                 R    SU R                   R                  ;   a  U R                  $ S$ )aH  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   )rI   r   CACHE_MAX_AGE)rS   r  r  r  s       r;   r   StaticFileHandler.get_cache_time%  s&     &)DLL,B,B%Bt!!IIr:   rp   include_versionc                     UR                  SS5      U-   nU(       d  U$ U R                  X5      nU(       d  U$ U SU 3$ )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  rp   r  r  r   r  s         r;   rV  !StaticFileHandler.make_static_url4  sI    , ll.
;dBJx6Jc,((r:   url_pathc                     [         R                  R                  S:w  a*  UR                  S[         R                  R                  5      nU$ )zConverts a static URL path into a filesystem path.

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

This is the inverse of `make_static_url`.
r  )r  r  r  rx  )rS   r  s     r;   r   StaticFileHandler.parse_url_pathT  s3     77;;#''RWW[[9Hr:   c                 N    U R                  US   U5      nU R                  U5      $ )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.
rS  )r  r  )r  rp   r  abs_paths       r;   r  StaticFileHandler.get_versiona  s,     ((-)@$G&&x00r:   r  c                 8   U R                      U R                  nX;  a   U R                  U5      X!'   UR                  U5      nU(       a  UsS S S 5        $  S S S 5        g ! [         a    [        R
                  " SU5        S X!'    NTf = f! , (       d  f       g = f)NzCould not open static file %r)r  r  r  r:  r   r  r   )r  r  hasheshshs       r;   r  %StaticFileHandler._get_cached_versionr  s    YY''F%,'*'>'>x'HF$ **X&C Y    ! ,MM"A8L'+F$, Y s-   BA B %BBBB
B)r  r  r  r  r  r  rN   r  r  )NN)-r5   r6   r7   r8   r  r  r  r  r  r  r   r"   rg   classmethodrl  r#   r  r   r   rf  r  r  r  r  rK  r(   r   r  r  r  r  r  r  r   r  r  r  r  r   r    rV  r  r  r  r9   r4   r:   r;   rU  rU  p
  s   @D %MNNNE1s 1hsm 1t 1 $ $2 24 2Q1c Q1 Q1 Q1f#hsm #*44 2 S     93 9s 9xPS} 9v MQ$$"*3-$=Ec]$	5$$	%$ $L "# "# " ""!r~~ !## #8H,=,=#> 4.# .*c d JJ#+H,=,=#>JKNJ	J JN)CH~)-0)CG)	) )>s s  14S> 1 1# 1 1  3 8C=  r:   rU  c                   T    \ rS rSrSrS\\R                  /S4   SS4S jrS	S jr	Sr
g)
FallbackHandleri  a  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)),
    ])
fallbackNrK   c                     Xl         g rN   )r  )rS   r  s     r;   rg   FallbackHandler.initialize  s	     !r:   c                 h    U R                  U R                  5        SU l        U R                  5         g )NT)r  rI   r[   r}   rk   s    r;   rz   FallbackHandler.prepare  s#    dll#r:   )r[   r  r  )r5   r6   r7   r8   r  r&   r   r  rg   rz   r9   r4   r:   r;   r  r    s4     ! ("<"<!=t!CD!	!
r:   r  c                       \ rS rSrSrS\R                  SS4S jrS\S\R                  S	\
S
\S\\\R                  \
4   4
S jrS	\
S
\S\
4S jrSrg)rx  i  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.
rI   rK   Nc                     g rN   r4   rS   rI   s     r;   rY   OutputTransform.__init__  rn   r:   r   r  rO  	finishingc                 
    XU4$ rN   r4   )rS   r   r  rO  r  s        r;   r  %OutputTransform.transform_first_chunk  s     U**r:   c                     U$ rN   r4   rS   rO  r  s      r;   r  OutputTransform.transform_chunk  s    r:   r4   )r5   r6   r7   r8   r  r   r  rY   rK  r   r   r   r$   r  r  r9   r4   r:   r;   rx  rx    s     : : t ++ %%+ 	+
 + 
sH((%/	0+U t  r:   rx  c                       \ rS rSrSr1 SkrSrSrS\R                  SS4S	 jr
S
\S\4S jrS\S\R                  S\S\S\\\R                  \4   4
S jrS\S\S\4S jrSrg)r  i  a1  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   rI   rK   Nc                 L    SUR                   R                  SS5      ;   U l        g )Nr  Accept-Encodingr)  )r  r   	_gzippingr  s     r;   rY   GZipContentEncoding.__init__  s     7??#6#67H"#MMr:   ctypec                 N    UR                  S5      =(       d    XR                  ;   $ )Nztext/)r  CONTENT_TYPES)rS   r*  s     r;   _compressible_type&GZipContentEncoding._compressible_type  s!    (GE5G5G,GGr:   r   r  rO  r  c                 p   SU;   a  US==   S-  ss'   OSUS'   U R                   (       a|  [        UR                  SS5      5      R                  S5      S   nU R	                  U5      =(       a2    U(       + =(       d    [        U5      U R                  :  =(       a    SU;  U l         U R                   (       a|  S	US'   [        5       U l        [        R                  " S
U R                  U R                  S9U l        U R                  X45      nSU;   a"  U(       a  [        [        U5      5      US'   OUS	 XU4$ )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   )rS   r   r  rO  r  r*  s         r;   r  )GZipContentEncoding.transform_first_chunk  s    WFO22O/GFO>>W[[<=CCCHKE''. 8"]Cc%jDOO&C8'w6 N
 >>*0G&'&yD"mm$"2"2$//DO ((:E7*
 03CJG,- 01U**r:   c                 v   U R                   (       a  U R                  R                  U5        U(       a  U R                  R                  5         OU R                  R	                  5         U R
                  R                  5       nU R
                  R                  S5        U R
                  R                  S5        U$ )Nr   )	r(  r9  rU  closer  r6  getvaluetruncater  r  s      r;   r  #GZipContentEncoding.transform_chunk  s    >>OO!!%(%%'%%'$$--/E%%a(!!!$r:   )r9  r6  r(  )r5   r6   r7   r8   r  r,  r8  r5  r   r  rY   r   r   r-  rK  r   r   r$   r  r  r9   r4   r:   r;   r  r    s    M J JN : : Nt NH H H#+#+ %%#+ 	#+
 #+ 
sH((%/	0#+J
U 
t 
 
r:   r  c                 v   ^  [         R                  " T 5      S[        S[        [        S      4U 4S jj5       nU$ )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.
rS   rK   Nc                   > U R                   (       d  U R                  R                  S;   a  U R                  5       nSU;  a  [        R
                  R                  U5      R                  (       a  U R                  R                  5       nO/U R                  R                  c   eU R                  R                  nUS[        [        US95      -   -  nU R                  U5        g [        S5      eT" U /UQ70 UD6$ )Nr  r  )nextrH  )r  rI   r  r  urllibparseurlsplitschemefull_urlr  r   r9  rM  ru   )rS   rr   rJ   r   next_urlr  s        r;   r  authenticated.<locals>.wrapper  s       ||""o5((*c>||,,S188#'<<#8#8#:#||//;;;#'<<#3#334X+>!???Cc"C. d,T,V,,r:   r  r  s   ` r;   authenticatedrJ    s@     __V--	)D/	"- -& Nr:   c                       \ rS rSrSrS\SS4S jr\S\4S j5       r	S\S	\S\
\\4   4S
 jrS\\   4S jrS\\\      4S jrS\\   4S jrS\\\      4S jrS\\   4S jrS\\   4S jrS\S	\S\4S jrSrg)r  i4  a  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  rK   Nc                 v    Xl         UR                  U l        UR                  U l        UR                  U l        g rN   )r  rI   r`   r   )rS   r  s     r;   rY   UIModule.__init__>  s(    **nnr:   c                 .    U R                   R                  $ rN   )r  r  rk   s    r;   r  UIModule.current_userD  s    ||(((r:   rr   rJ   c                     [        5       e)z6Override in subclasses to return this module's output.r  rv   s      r;   r|  UIModule.renderH  s    !##r:   c                     g)zBOverride to return a JavaScript string
to be embedded in the page.Nr4   rk   s    r;   r]  UIModule.embedded_javascriptL       r:   c                     g)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.
Nr4   rk   s    r;   r^  UIModule.javascript_filesQ       r:   c                     g)zBOverride to return a CSS string
that will be embedded in the page.Nr4   rk   s    r;   r`  UIModule.embedded_cssY  rT  r:   c                     g)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.
Nr4   rk   s    r;   ra  UIModule.css_files^  rW  r:   c                     g)zKOverride to return an HTML string that will be put in the <head/>
element.
Nr4   rk   s    r;   rb  UIModule.html_headf       r:   c                     g)zVOverride to return an HTML string that will be put at the end of
the <body/> element.
Nr4   rk   s    r;   rc  UIModule.html_bodyl  r^  r:   r  c                 <    U R                   R                  " U40 UD6$ )z.Renders a template and returns it as a string.)r  r[  )rS   r  rJ   s      r;   r[  UIModule.render_stringr  s    ||))$9&99r:   )r  r   rI   r`   )r5   r6   r7   r8   r  r=   rY   r  r    r  r!   r   r   r|  r"   r]  r'   r^  r`  ra  rb  rc  r[  r9   r4   r:   r;   r  r  4  s    % %4 % )c ) )$C $3 $5e3D $Xc] 
(8C="9 hsm 
8HSM2 8C= 8C= :# : : :r:   r  c                   *    \ rS rSrS\S\S\4S jrSrg)r  iw  textrJ   rK   c                 0    [         R                  " U40 UD6$ rN   )r   r  )rS   rd  rJ   s      r;   r|  _linkify.renderx  s    ~~d-f--r:   r4   N)r5   r6   r7   r8   r   r    r|  r9   r4   r:   r;   r  r  w  s    .3 .# .# .r:   r  c                   "    \ rS rSrS\4S jrSrg)r  i|  rK   c                 6    U R                   R                  5       $ rN   )r  r  rk   s    r;   r|  _xsrf_form_html.render}  s    ||**,,r:   r4   N)r5   r6   r7   r8   r   r|  r9   r4   r:   r;   r  r  |  s    - -r:   r  c                      ^  \ rS rSrSrS\SS4U 4S jjrS\S\S\	4S	 jr
S
\S\\   4S jrS\4S jrS\\   4S jrS\4S jrS\\   4S jrS\4S jrS\4S jrSrU =r$ )r  i  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  rK   Nc                 @   > [         TU ]  U5        / U l        0 U l        g rN   )rX   rY   _resource_list_resource_dict)rS   r  rh   s     r;   rY   TemplateModule.__init__  s     !  r:   r  rJ   c                 N   ^ ^ S[         4UU 4S jjnT R                  " T4SU0UD6$ )NrK   c                     > TTR                   ;  a+  TR                  R                  U 5        U TR                   T'   gTR                   T   U :w  a  [        S5      eg)NzCset_resources called with different resources for the same templater)  )rm  rl  r   r   )rJ   r  rS   s    r;   set_resources,TemplateModule.render.<locals>.set_resources  sf    4...##**62,2##D)  &&t,6$:  r:   rq  )r   r[  )rS   r  rJ   rq  s   ``  r;   r|  TemplateModule.render  s1    
	s 
	 
	 !!$NmNvNNr:   r  c                 0   ^ U4S jU R                    5       $ )Nc              3   >   >#    U  H  nTU;   d  M  UT   v   M     g 7frN   r4   )rP   rr  s     r;   rT   0TemplateModule._get_resources.<locals>.<genexpr>  s     @ 31sax# 3s   
)rl  rS   r  s    `r;   _get_resourcesTemplateModule._get_resources  s    @ 3 3@@r:   c                 B    SR                  U R                  S5      5      $ )N
r]  rj  ry  rk   s    r;   r]  "TemplateModule.embedded_javascript  s    yy,,-BCDDr:   c                     / nU R                  S5       HB  n[        U[        [        45      (       a  UR	                  U5        M1  UR                  U5        MD     U$ )Nr^  ry  r   r   r   r   r_  rS   r  rj  s      r;   r^  TemplateModule.javascript_files  sN    $$%78A!lE233a a 	 9
 r:   c                 B    SR                  U R                  S5      5      $ )Nr|  r`  r}  rk   s    r;   r`  TemplateModule.embedded_css  s    yy,,^<==r:   c                     / nU R                  S5       HB  n[        U[        [        45      (       a  UR	                  U5        M1  UR                  U5        MD     U$ )Nra  r  r  s      r;   ra  TemplateModule.css_files  sM    $$[1A!lE233a a 	 2
 r:   c                 B    SR                  U R                  S5      5      $ )Nr)  rb  r}  rk   s    r;   rb  TemplateModule.html_head      wwt**;788r:   c                 B    SR                  U R                  S5      5      $ )Nr)  rc  r}  rk   s    r;   rc  TemplateModule.html_body  r  r:   )rm  rl  )r5   r6   r7   r8   r  r=   rY   r   r    r   r|  r'   ry  r]  r^  r`  ra  rb  rc  r9   r  r  s   @r;   r  r    s    ! !4 !O3 O# O% OA# A(3- AES E(3- >c >8C= 93 993 9 9r:   r  c                   v    \ rS rSrSrS\S\\\\	   4   SS4S jr
S\S\S	\4   4S
 jrS\S\S	\4   4S jrSrg)ra   i  zALazy namespace which creates UIModule proxies bound to a handler.r  rb   rK   Nc                     Xl         X l        g rN   r  rb   )rS   r  rb   s      r;   rY   _UIModuleNamespace.__init__  s     $r:   r  .c                 R    U R                   R                  XR                  U   5      $ rN   )r  r  rb   rx  s     r;   __getitem___UIModuleNamespace.__getitem__  s     ||&&sOOC,@AAr:   c                 X     X   $ ! [          a  n[        [        U5      5      eS nAff = frN   )rI  AttributeErrorr   )rS   r  r  s      r;   __getattr___UIModuleNamespace.__getattr__  s.    	)9 	) Q((	)s    
)$)r  )r5   r6   r7   r8   r  r=   r   r   r)   r  rY   r&   r  r  r9   r4   r:   r;   ra   ra     sk    K%%%37T(^8K3L%	%Bs BxS'9 B)s )xS'9 )r:   ra   r;  r   r   r   clockr7  c           	         Uc  [         nUc  [        R                  n[        [        [	        U" 5       5      5      5      n[
        R                  " [        U5      5      nUS:X  a8  [        U [        5      (       a   e[        XX&5      nSR                  X&U/5      nU$ US:X  a  S[        [        [        4   S[        4S jnSR                  SU" [        U=(       d    S5      5      U" U5      U" U5      U" U5      S	/5      n	[        U [        5      (       a  Uc   S
5       eUS:  d   S5       eX   n [        X	5      nX-   $ [        SU-  5      e)Nr/   r$  r0   r   rK   c                 H    [        S[        U 5      -  5      [        U 5      -   $ )Nz%d:)r   r  )r   s    r;   format_field)create_signed_value.<locals>.format_field  s    A'$q'11r:   r%  r   r:   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   rK  base64	b64encoder   r9  _create_signature_v1rj  r!   r   _create_signature_v2r   )
r;  r   r   r   r  r7  r.  	signaturer  to_signs
             r;   r1  r1    sP    .}		SUW&'IT%[)E!|fd++++(uH			5Y78	A	2E#u*- 	2% 	2 ))S!123Y'T"U#	
 fd##'DCD'a<U!UU<(F(9	""1G;<<r:   s   ^([1-9][0-9]*)\|(.*)$c                     [         R                  U 5      nUc  SnU$  [        UR                  S5      5      nUS:  a  SnU$ ! [         a    Sn U$ f = f)Nr/   i  )r=  r>  rK  r?  r   )r   rR   r   s      r;   _get_versionr    sk     	!&&u-Ay N	!''!*oG}  N  	GN	s   "A AAr=  r>  c                 &   Uc  [         R                   nUc  [        nUS:  a  [        SU-  5      eU(       d  g [        U5      n[	        U5      nXe:  a  g US:X  a$  [        U [        5      (       a   e[        XX#U5      $ US:X  a  [        XX#U5      $ g )Nr0   zUnsupported min_version %dr/   )	r    DEFAULT_SIGNED_VALUE_MIN_VERSIONr   r   r  r   r9  _decode_signed_value_v1_decode_signed_value_v2)r;  r   r   r=  r  r>  r   s          r;   r@  r@  5  s     }		6Q5CDDKE5!G!|fd++++&vU%PP	A&vU%PPr:   c                 V   [        U5      R                  S5      n[        U5      S:w  a  g [        XUS   US   5      n[        R
                  " US   U5      (       d  [        R                  " SU5        g [        US   5      nXt" 5       US-  -
  :  a  [        R                  " SU5        g Xt" 5       S	-   :  a  [        R                  " S
U5        g US   R                  S5      (       a  [        R                  " SU5        g  [        R                  " US   5      $ ! [         a     g f = f)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  rI  rJ  r   r  rK  r  r  	b64decoder:  )r;  r   r   r=  r  r  r  r.  s           r;   r  r  T  s    Kd#E
5zQ$V58U1XFIuQx335u=E!HI57\E111+U357Z'' 	KUSQx4  ,e4a)) s   D 
D('D(c                     S[         S[        [         [         4   4S jnU SS  nU" U5      u  p2U" U5      u  pBU" U5      u  pRU" U5      u  pg[        U5      XEXg4$ )Nr   rK   c                     U R                  S5      u  pn[        U5      nUS U nX4US-    S:w  a  [        S5      eX4S-   S  nXS4$ )N   :r/   r$  zmalformed v2 signed value field)	partitionrK  r   )r   lengthr  restrQ   field_values         r;   _consume_field)_decode_fields_v2.<locals>._consume_fieldx  s\    ++d+4K2Ah AE?d">??EG}  r:   r0   )r   r$   rK  )r   r  r  r7  r.  
name_fieldvalue_field
passed_sigs           r;   _decode_fields_v2r  w  sp    	!% 	!E%,$7 	! 9D&t,K$T*OI%d+J,T2K{YKKKr:   c                     [        U5      u  nnnnn	US [        U	5      *  n
[        U [        5      (       a   X   n [        X
5      n[        R                  " X5      (       d  g U[        U5      :w  a  g [        U5      nX" 5       US-  -
  :  a  g  [        R                  " U5      $ ! [         a     g f = f! [
         a     g f = f! [         a     g f = f)Nr  )r  r   r  r   r9  rI  r  rI  rJ  r   rK  r  r  r:  )r;  r   r   r=  r  r7  timestamp_bytesr  r  r  signed_stringexpected_sigr.  s                r;   r  r    s    	 e$	
 ,S_,-M&$	(F (>Lz88T$ZO$I57\E111,,)    		  s4   B& B6 C &
B32B36
CC
CCc                     [        U 5      n [        U 5      nUS:  a  g  [        U 5      u  n      nU$ ! [         a     g f = f)Nr0   )r   r  r  r   )r   r   r7  r  s       r;   rD  rD    sU    KE5!G{"3E":Q1a   s   2 
??r  c                     [         R                  " [        U 5      [        R                  S9nU H  nUR                  [        U5      5        M     [        UR                  5       5      $ N)	digestmod)rI  newr   rb  rc  r  rd  )r;  r  hashr  s       r;   r  r    sF    88DLGLL9DDJ  !!r:   r   c                     [         R                  " [        U 5      [        R                  S9nUR                  [        U5      5        [        UR                  5       5      $ r  )rI  r  r   rb  sha256r  rd  )r;  r   r  s      r;   r  r    s<    88DLGNN;DKKQ !!r:   r  c                 .   ^  [        U 4S jS 5       5      $ )Nc              3   F   >#    U  H  nTR                  U5      v   M     g 7frN   rp  )rP   rn  r  s     r;   rT   is_absolute.<locals>.<genexpr>  s     D+Catq!!+Cs   !)r  zhttp:zhttps:)any)r  s   `r;   r  r    s    D+CDDDr:   r7  )r  NN)r  r  r*  r   email.utilsr  r  r  rb  rI  http.cookiesr  inspectr   ior   r  r   os.pathr  r  rR  r  r  r   r  r   r  r1  urllib.parserC  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   rK  r   r  r   _CookieSecretTypes"MIN_SUPPORTED_SIGNED_VALUE_VERSION"MAX_SUPPORTED_SIGNED_VALUE_VERSIONr  r  r2   r  r=   r  r  r   r   r  r  r  rH   r  r=  r:  ru   r  r   rA  r  rU  r  rx  r  rJ  r  r  r  r  ra   r	  r1  r  r=  r  r@  r  r  r  rD  r  r  r  r4   r:   r;   <module>r     s   )V               	  
        " I   )    4 4  )	 	 	 C B       	
 UL#w/?/?ARARRS3tCH~tCJ7GGH  &' " &' "  !  $%  	 	 !"x! x!v7 3>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N{
" {
|	W-x33 W-t:	 :z	Y 	8!9 !>  -9n -9`O Odn 8 0V/ Vr"S(9T?334"c8IdO,,-"J@: @:F.x .
-h -
D9X D9N) ). "+/!%;=;=
;= e;= c]	;=
 HRY'(;= #;= ;=@ ::&?@  # 6 +/!%
 sE!" 	
 HRY'( # e_> #u* 
    	 
 BI  e_ FLU LuS%u-L'M L(%%
% % 	%
 BI% e_%P
U3:%6 
8C= 
"sEz!2 "E#u*<M "RW ""sEz!2 "u " "Ec Ed Er:   