BYPASS SHELL BY ./RAZORGANZ
Server: nginx/1.20.1
System: Linux iZdzfnv9mwfppeZ 5.10.134-19.2.al8.x86_64 #1 SMP Wed Oct 29 22:47:09 CST 2025 x86_64
User: apache (48)
PHP: 8.2.30
Disabled: NONE
Upload Files
File: //lib64/python3.6/site-packages/tornado/__pycache__/routing.cpython-36.pyc
3

	��f�`�@sdZddlZddlmZddlmZddlmZddlm	Z	m
Z
mZddlm
Z
ddlmZmZmZmZdd	lmZmZmZmZmZmZmZmZmZGd
d�dej�ZGdd
�d
e�ZGdd�dej �Z!Gdd�dej �Z"eedeeeee#dfefeee#dfeee#effeee#dfeee#efe#ffZ$Gdd�de�Z%Gdd�dee%�Z&Gdd�de'�Z(Gdd�de'�Z)Gdd�de)�Z*Gdd�de)�Z+Gdd�de)�Z,Gd d!�d!e)�Z-Gd"d#�d#e(�Z.ee#e/d$�d%d&��Z0eddd$�d'd&��Z0ee#ee/d$�d(d&�Z0dS))aqFlexible routing implementation.

Tornado routes HTTP requests to appropriate handlers using `Router`
class implementations. The `tornado.web.Application` class is a
`Router` implementation and may be used directly, or the classes in
this module may be used for additional flexibility. The `RuleRouter`
class can match on more criteria than `.Application`, or the `Router`
interface can be subclassed for maximum customization.

`Router` interface extends `~.httputil.HTTPServerConnectionDelegate`
to provide additional routing capabilities. This also means that any
`Router` implementation can be used directly as a ``request_callback``
for `~.httpserver.HTTPServer` constructor.

`Router` subclass must implement a ``find_handler`` method to provide
a suitable `~.httputil.HTTPMessageDelegate` instance to handle the
request:

.. code-block:: python

    class CustomRouter(Router):
        def find_handler(self, request, **kwargs):
            # some routing logic providing a suitable HTTPMessageDelegate instance
            return MessageDelegate(request.connection)

    class MessageDelegate(HTTPMessageDelegate):
        def __init__(self, connection):
            self.connection = connection

        def finish(self):
            self.connection.write_headers(
                ResponseStartLine("HTTP/1.1", 200, "OK"),
                HTTPHeaders({"Content-Length": "2"}),
                b"OK")
            self.connection.finish()

    router = CustomRouter()
    server = HTTPServer(router)

The main responsibility of `Router` implementation is to provide a
mapping from a request to `~.httputil.HTTPMessageDelegate` instance
that will handle this request. In the example above we can see that
routing is possible even without instantiating an `~.web.Application`.

For routing to `~.web.RequestHandler` implementations we need an
`~.web.Application` instance. `~.web.Application.get_handler_delegate`
provides a convenient way to create `~.httputil.HTTPMessageDelegate`
for a given request and `~.web.RequestHandler`.

Here is a simple example of how we can we route to
`~.web.RequestHandler` subclasses by HTTP method:

.. code-block:: python

    resources = {}

    class GetResource(RequestHandler):
        def get(self, path):
            if path not in resources:
                raise HTTPError(404)

            self.finish(resources[path])

    class PostResource(RequestHandler):
        def post(self, path):
            resources[path] = self.request.body

    class HTTPMethodRouter(Router):
        def __init__(self, app):
            self.app = app

        def find_handler(self, request, **kwargs):
            handler = GetResource if request.method == "GET" else PostResource
            return self.app.get_handler_delegate(request, handler, path_args=[request.path])

    router = HTTPMethodRouter(Application())
    server = HTTPServer(router)

`ReversibleRouter` interface adds the ability to distinguish between
the routes and reverse them to the original urls using route's name
and additional arguments. `~.web.Application` is itself an
implementation of `ReversibleRouter` class.

`RuleRouter` and `ReversibleRuleRouter` are implementations of
`Router` and `ReversibleRouter` interfaces and can be used for
creating rule-based routing configurations.

Rules are instances of `Rule` class. They contain a `Matcher`, which
provides the logic for determining whether the rule is a match for a
particular request and a target, which can be one of the following.

1) An instance of `~.httputil.HTTPServerConnectionDelegate`:

.. code-block:: python

    router = RuleRouter([
        Rule(PathMatches("/handler"), ConnectionDelegate()),
        # ... more rules
    ])

    class ConnectionDelegate(HTTPServerConnectionDelegate):
        def start_request(self, server_conn, request_conn):
            return MessageDelegate(request_conn)

2) A callable accepting a single argument of `~.httputil.HTTPServerRequest` type:

.. code-block:: python

    router = RuleRouter([
        Rule(PathMatches("/callable"), request_callable)
    ])

    def request_callable(request):
        request.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
        request.finish()

3) Another `Router` instance:

.. code-block:: python

    router = RuleRouter([
        Rule(PathMatches("/router.*"), CustomRouter())
    ])

Of course a nested `RuleRouter` or a `~.web.Application` is allowed:

.. code-block:: python

    router = RuleRouter([
        Rule(HostMatches("example.com"), RuleRouter([
            Rule(PathMatches("/app1/.*"), Application([(r"/app1/handler", Handler)]))),
        ]))
    ])

    server = HTTPServer(router)

In the example below `RuleRouter` is used to route between applications:

.. code-block:: python

    app1 = Application([
        (r"/app1/handler", Handler1),
        # other handlers ...
    ])

    app2 = Application([
        (r"/app2/handler", Handler2),
        # other handlers ...
    ])

    router = RuleRouter([
        Rule(PathMatches("/app1.*"), app1),
        Rule(PathMatches("/app2.*"), app2)
    ])

    server = HTTPServer(router)

For more information on application-level routing see docs for `~.web.Application`.

.. versionadded:: 4.5

�N)�partial)�httputil)�_CallableAdapter)�
url_escape�url_unescape�utf8)�app_log)�basestring_type�
import_object�re_unescape�unicode_type)	�Any�Union�Optional�	Awaitable�List�Dict�Pattern�Tuple�overloadc@s@eZdZdZejeeejd�dd�Z	e
ejejd�dd�ZdS)	�RouterzAbstract router interface.)�request�kwargs�returncKs
t��dS)a�Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate`
        that can serve the request.
        Routing implementations may pass additional kwargs to extend the routing logic.

        :arg httputil.HTTPServerRequest request: current HTTP request.
        :arg kwargs: additional keyword arguments passed by routing implementation.
        :returns: an instance of `~.httputil.HTTPMessageDelegate` that will be used to
            process the request.
        N)�NotImplementedError)�selfrr�r�/usr/lib64/python3.6/routing.py�find_handler�szRouter.find_handler)�server_conn�request_connrcCst|||�S)N)�_RoutingDelegate)rrr rrr�
start_request�szRouter.start_requestN)
�__name__�
__module__�__qualname__�__doc__r�HTTPServerRequestr
r�HTTPMessageDelegater�object�HTTPConnectionr"rrrrr�s

rc@s&eZdZdZeeeed�dd�ZdS)�ReversibleRouterzxAbstract router interface for routers that can handle named routes
    and support reversing them to original urls.
    )�name�argsrcGs
t��dS)aReturns url string for a given route name and arguments
        or ``None`` if no match is found.

        :arg str name: route name.
        :arg args: url parameters.
        :returns: parametrized url string for a given route name (or ``None``).
        N)r)rr,r-rrr�reverse_url�szReversibleRouter.reverse_urlN)r#r$r%r&�strr
rr.rrrrr+�sr+c@s~eZdZeeejdd�dd�Zeej	ej
fejee
dd�dd�Zeee
dd�d	d
�Zdd�dd
�Zdd�dd�ZdS)r!N)�routerrr rcCs||_||_d|_||_dS)N)rr �delegater0)rr0rr rrr�__init__�sz_RoutingDelegate.__init__)�
start_line�headersrcCsjt|tj�st�tj|j|j||d�}|jj|�|_	|j	dkr\t
jd|j|j
�t|j�|_	|j	j||�S)N)�
connection�server_connectionr3r4z$Delegate for %s %s request not found)�
isinstancer�RequestStartLine�AssertionErrorr'r rr0rr1r�debug�method�path�_DefaultMessageDelegate�headers_received)rr3r4rrrrr>�s
z!_RoutingDelegate.headers_received)�chunkrcCs|jdk	st�|jj|�S)N)r1r9�
data_received)rr?rrrr@sz_RoutingDelegate.data_received)rcCs|jdk	st�|jj�dS)N)r1r9�finish)rrrrrA
sz_RoutingDelegate.finishcCs|jdk	st�|jj�dS)N)r1r9�on_connection_close)rrrrrBsz$_RoutingDelegate.on_connection_close)r#r$r%rr)rr*r2rr8�ResponseStartLine�HTTPHeadersrrr>�bytesr@rArBrrrrr!�sr!c@s,eZdZejdd�dd�Zdd�dd�ZdS)r=N)r5rcCs
||_dS)N)r5)rr5rrrr2sz _DefaultMessageDelegate.__init__)rcCs*|jjtjddd�tj��|jj�dS)NzHTTP/1.1i�z	Not Found)r5Z
write_headersrrCrDrA)rrrrrAs
z_DefaultMessageDelegate.finish)r#r$r%rr*r2rArrrrr=sr=�Rule�Matcherc@sxeZdZdZdedd�dd�Zedd�dd�Zddd	�d
d�Zej	e
eejd�d
d�Z
e
ej	e
eejd�dd�ZdS)�
RuleRouterz!Rule-based router implementation.N)�rulesrcCsg|_|r|j|�dS)aIConstructs a router from an ordered list of rules::

            RuleRouter([
                Rule(PathMatches("/handler"), Target),
                # ... more rules
            ])

        You can also omit explicit `Rule` constructor and use tuples of arguments::

            RuleRouter([
                (PathMatches("/handler"), Target),
            ])

        `PathMatches` is a default matcher, so the example above can be simplified::

            RuleRouter([
                ("/handler", Target),
            ])

        In the examples above, ``Target`` can be a nested `Router` instance, an instance of
        `~.httputil.HTTPServerConnectionDelegate` or an old-style callable,
        accepting a request argument.

        :arg rules: a list of `Rule` instances or tuples of `Rule`
            constructor arguments.
        N)rI�	add_rules)rrIrrrr2/szRuleRouter.__init__cCsxxr|D]j}t|ttf�r^t|�dks(t�t|dt�rVtt|d�f|dd���}nt|�}|jj	|j
|��qWdS)z�Appends new rules to the router.

        :arg rules: a list of Rule instances (or tuples of arguments, which are
            passed to Rule constructor).
        ���r�N)rKrLrM)r7�tuple�list�lenr9r	rF�PathMatchesrI�append�process_rule)rrI�rulerrrrJNs
 zRuleRouter.add_rulesrF)rUrcCs|S)z�Override this method for additional preprocessing of each rule.

        :arg Rule rule: a rule to be processed.
        :returns: the same or modified Rule instance.
        r)rrUrrrrT^szRuleRouter.process_rule)rrrcKsVxP|jD]F}|jj|�}|dk	r|jr0|j|d<|j|j|f|�}|dk	r|SqWdS)N�
target_kwargs)rI�matcher�matchrV�get_target_delegate�target)rrrrU�
target_paramsr1rrrrfs
zRuleRouter.find_handler)rZrr[rcKspt|t�r|j|f|�St|tj�rB|jdk	s2t�|j|j|j�St	|�rl|jdk	sXt�t
t|f|�|j�SdS)a�Returns an instance of `~.httputil.HTTPMessageDelegate` for a
        Rule's target. This method is called by `~.find_handler` and can be
        extended to provide additional target types.

        :arg target: a Rule's target.
        :arg httputil.HTTPServerRequest request: current request.
        :arg target_params: additional parameters that can be useful
            for `~.httputil.HTTPMessageDelegate` creation.
        N)r7rrr�HTTPServerConnectionDelegater5r9r"r6�callablerr)rrZrr[rrrrYxs
zRuleRouter.get_target_delegate)N)r#r$r%r&�	_RuleListr2rJrTrr'r
rr(rrYrrrrrH,s	rHcsTeZdZdZd
edd��fdd�
Zddd��fdd	�Zeee	ed
�dd�Z
�ZS)�ReversibleRuleRouteraA rule-based router that implements ``reverse_url`` method.

    Each rule added to this router may have a ``name`` attribute that can be
    used to reconstruct an original uri. The actual reconstruction takes place
    in a rule's matcher (see `Matcher.reverse`).
    N)rIrcsi|_tt|�j|�dS)N)�named_rules�superr_r2)rrI)�	__class__rrr2�szReversibleRuleRouter.__init__rF)rUrcs@tt|�j|�}|jr<|j|jkr0tjd|j�||j|j<|S)Nz4Multiple handlers named %s; replacing previous value)rar_rTr,r`rZwarning)rrU)rbrrrT�s
z!ReversibleRuleRouter.process_rule)r,r-rcGsZ||jkr|j|jj|�Sx8|jD].}t|jt�r$|jj|f|��}|dk	r$|Sq$WdS)N)r`rW�reverserIr7rZr+r.)rr,r-rUZreversed_urlrrrr.�s
z ReversibleRuleRouter.reverse_url)N)r#r$r%r&r^r2rTr/r
rr.�
__classcell__rr)rbrr_�sr_c@sReZdZdZd
deeeefedd�dd�Zeeed�dd	�Z	ed
�dd�Z
dS)rFzA routing rule.NrG)rWrZrVr,rcCs6t|t�rt|�}||_||_|r&|ni|_||_dS)adConstructs a Rule instance.

        :arg Matcher matcher: a `Matcher` instance used for determining
            whether the rule should be considered a match for a specific
            request.
        :arg target: a Rule's target (typically a ``RequestHandler`` or
            `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
            depending on routing implementation).
        :arg dict target_kwargs: a dict of parameters that can be useful
            at the moment of target instantiation (for example, ``status_code``
            for a ``RequestHandler`` subclass). They end up in
            ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
            method.
        :arg str name: the name of the rule that can be used to find it
            in `ReversibleRouter.reverse_url` implementation.
        N)r7r/r
rWrZrVr,)rrWrZrVr,rrrr2�s
z
Rule.__init__)r-rcGs|jj|�S)N)rWrc)rr-rrrrc�szRule.reverse)rcCsd|jj|j|j|j|jfS)Nz%s(%r, %s, kwargs=%r, name=%r))rbr#rWrZrVr,)rrrr�__repr__�sz
Rule.__repr__)NN)r#r$r%r&r
rr/r2rrcrerrrrrF�sc@sBeZdZdZejeeee	fd�dd�Z
e	eed�dd�ZdS)	rGz*Represents a matcher for request features.)rrcCs
t��dS)a1Matches current instance against the request.

        :arg httputil.HTTPServerRequest request: current HTTP request
        :returns: a dict of parameters to be passed to the target handler
            (for example, ``handler_kwargs``, ``path_args``, ``path_kwargs``
            can be passed for proper `~.web.RequestHandler` instantiation).
            An empty dict is a valid (and common) return value to indicate a match
            when the argument-passing features are not used.
            ``None`` must be returned to indicate that there is no match.N)r)rrrrrrX�s
z
Matcher.match)r-rcGsdS)zEReconstructs full url from matcher instance and additional arguments.Nr)rr-rrrrc�szMatcher.reverseN)r#r$r%r&rr'rrr/r
rXrcrrrrrG�sc@s.eZdZdZejeeee	fd�dd�Z
dS)�
AnyMatcheszMatches any request.)rrcCsiS)Nr)rrrrrrXszAnyMatches.matchN)r#r$r%r&rr'rrr/r
rXrrrrrf�srfc@sFeZdZdZeeefdd�dd�Zej	e
eeefd�dd�Z
dS)	�HostMatchesz@Matches requests from hosts specified by ``host_pattern`` regex.N)�host_patternrcCs4t|t�r*|jd�s|d7}tj|�|_n||_dS)N�$)r7r	�endswith�re�compilerh)rrhrrrr2s


zHostMatches.__init__)rrcCs|jj|j�riSdS)N)rhrXZ	host_name)rrrrrrXszHostMatches.match)r#r$r%r&rr/rr2rr'rrr
rXrrrrrgsrgc@s@eZdZdZeedd�dd�Zeje	e
eefd�dd�ZdS)	�DefaultHostMatchesz�Matches requests from host that is equal to application's default_host.
    Always returns no match if ``X-Real-Ip`` header is present.
    N)�applicationrhrcCs||_||_dS)N)rnrh)rrnrhrrrr2szDefaultHostMatches.__init__)rrcCs"d|jkr|jj|jj�riSdS)Nz	X-Real-Ip)r4rhrXrnZdefault_host)rrrrrrX s
zDefaultHostMatches.match)
r#r$r%r&r
rr2rr'rrr/rXrrrrrmsrmc@sxeZdZdZeeefdd�dd�Zej	e
eeefd�dd�Z
ee
ed	�d
d�Zee
ee
efd�d
d�ZdS)rRz@Matches requests with paths specified by ``path_pattern`` regex.N)�path_patternrcCslt|t�r*|jd�s|d7}tj|�|_n||_t|jj�d|jjfksXt	d|jj
��|j�\|_|_
dS)NrirzDgroups in url regexes must either be all named or all positional: %r)r7r	rjrkrl�regexrQ�
groupindex�groupsr9�pattern�_find_groups�_path�_group_count)rrorrrr2+s

zPathMatches.__init__)rrcCsp|jj|j�}|dkrdS|jjs&iSg}i}|jjrRtdd�|j�j�D��}ndd�|j�D�}t||d�S)Ncss"|]\}}t|�t|�fVqdS)N)r/�_unquote_or_none)�.0�k�vrrr�	<genexpr>Jsz$PathMatches.match.<locals>.<genexpr>cSsg|]}t|��qSr)rw)rx�srrr�
<listcomp>Msz%PathMatches.match.<locals>.<listcomp>)�	path_args�path_kwargs)rprXr<rrrq�dict�	groupdict�items)rrrXr~rrrrrX:szPathMatches.match)r-rcGs�|jdkrtd|jj��t|�|jks0td��t|�s>|jSg}x8|D]0}t|tt	f�sbt
|�}|jtt
|�dd��qHW|jt|�S)NzCannot reverse url regex z&required number of arguments not foundF)�plus)ru�
ValueErrorrprsrQrvr9r7rrEr/rSrrrO)rr-Zconverted_args�arrrrcQs

zPathMatches.reverse)rcCs�|jj}|jd�r|dd�}|jd�r4|dd
�}|jj|jd�krJdSg}xt|jd�D]f}d|kr�|jd�}|dkr�|jd||dd��qZyt	|�}Wnt
k
r�dSX|j|�qZWd	j|�|jjfS)
z�Returns a tuple (reverse string, group count) for a url.

        For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
        would return ('/%s/%s/', 2).
        �^rNNri�(�)rz%s����)NN)NN)rprs�
startswithrjrr�count�split�indexrSrr��join)rrs�piecesZfragmentZ	paren_locZunescaped_fragmentrrrrt`s&


zPathMatches._find_groups)r#r$r%r&rr/rr2rr'rrr
rXrcr�intrtrrrrrR(s
rRcsNeZdZdZd	eeefeeeefedd��fdd�
Z	ed�dd�Z
�ZS)
�URLSpecz�Specifies mappings between URLs and handlers.

    .. versionchanged: 4.5
       `URLSpec` is now a subclass of a `Rule` with `PathMatches` matcher and is preserved for
       backwards compatibility.
    N)rs�handlerrr,rcs8t|�}tt|�j||||�|j|_|j|_||_dS)a�Parameters:

        * ``pattern``: Regular expression to be matched. Any capturing
          groups in the regex will be passed in to the handler's
          get/post/etc methods as arguments (by keyword if named, by
          position if unnamed. Named and unnamed capturing groups
          may not be mixed in the same rule).

        * ``handler``: `~.web.RequestHandler` subclass to be invoked.

        * ``kwargs`` (optional): A dictionary of additional arguments
          to be passed to the handler's constructor.

        * ``name`` (optional): A name for this handler.  Used by
          `~.web.Application.reverse_url`.

        N)rRrar�r2rprZ�
handler_classr)rrsr�rr,rW)rbrrr2�s
zURLSpec.__init__)rcCs d|jj|jj|j|j|jfS)Nz%s(%r, %s, kwargs=%r, name=%r))rbr#rprsr�rr,)rrrrre�szURLSpec.__repr__)NN)r#r$r%r&rr/rr
rr2rerdrr)rbrr��s
r�)r|rcCsdS)Nr)r|rrrrw�srwcCsdS)Nr)r|rrrrw�scCs|dkr|St|ddd�S)z�None-safe wrapper around url_unescape to handle unmatched optional
    groups correctly.

    Note that args are passed as bytes so the handler can decide what
    encoding to use.
    NF)�encodingr�)r)r|rrrrw�s)1r&rk�	functoolsrZtornadorZtornado.httpserverrZtornado.escaperrrZtornado.logrZtornado.utilr	r
rrZtypingr
rrrrrrrrr\rr+r(r!r=r/r^rHr_r)rFrGrfrgrmrRr�rErwrrrr�<module>�sB,.&h%1[1