HEX
Server: LiteSpeed
System: Linux s1049.use1.mysecurecloudhost.com 4.18.0-477.27.2.lve.el8.x86_64 #1 SMP Wed Oct 11 12:32:56 UTC 2023 x86_64
User: xedaptot (3356)
PHP: 8.3.31
Disabled: NONE
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/tornado/__pycache__/routing.cpython-310.pyc
o

;j4b�@sdZddlZddlmZddlmZddlmZddlm	Z	m
Z
mZddlm
Z
ddlmZmZmZmZdd	lmZmZmZmZmZmZmZmZmZmZGd
d�dej�ZGdd
�d
e�Z Gdd�dej!�Z"Gdd�dej!�Z#eedeeeee$dfefeee$dfeee$effeee$dfeee$efe$ffZ%Gdd�de�Z&Gdd�de e&�Z'Gdd�d�Z(Gdd�d�Z)Gdd�de)�Z*Gdd�de)�Z+Gdd�de)�Z,Gd d!�d!e)�Z-Gd"d#�d#e(�Z.ed$e$d%e/fd&d'��Z0ed*d(d'��Z0d$ee$d%ee/fd)d'�Z0dS)+apFlexible 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�overload�Sequencec@sHeZdZdZdejdedeejfdd�Z	de
dejdejfd	d
�ZdS)�RouterzAbstract router interface.�request�kwargs�returncK�t��)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.
        ��NotImplementedError)�selfrr�r�C/opt/saltstack/salt/lib/python3.10/site-packages/tornado/routing.py�find_handler�szRouter.find_handler�server_conn�request_conncCst|||�S�N)�_RoutingDelegate)rr"r#rrr �
start_request�szRouter.start_requestN)
�__name__�
__module__�__qualname__�__doc__r�HTTPServerRequestr
r�HTTPMessageDelegater!�object�HTTPConnectionr&rrrr r�s ��
����rc@s*eZdZdZdededeefdd�ZdS)�ReversibleRouterzxAbstract router interface for routers that can handle named routes
    and support reversing them to original urls.
    �name�argsrcGr)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``).
        r)rr0r1rrr �reverse_url�szReversibleRouter.reverse_urlN)r'r(r)r*�strr
rr2rrrr r/�sr/c@s�eZdZdededejddfdd�Zdeej	ej
fd	ejdee
dfd
d�Zdedee
dfd
d�Zddd�Zddd�ZdS)r%�routerr"r#rNcCs||_||_d|_||_dSr$)r"r#�delegater4)rr4r"r#rrr �__init__�s
z_RoutingDelegate.__init__�
start_line�headerscCsjt|tj�sJ�tj|j|j||d�}|j�|�|_|jdur.t	�
d|j|j�t
|j�|_|j�||�S)N)�
connection�server_connectionr7r8z$Delegate for %s %s request not found)�
isinstancer�RequestStartLiner+r#r"r4r!r5r�debug�method�path�_DefaultMessageDelegate�headers_received)rr7r8rrrr rA�s �
�z!_RoutingDelegate.headers_received�chunkcCs|jdusJ�|j�|�Sr$)r5�
data_received)rrBrrr rCsz_RoutingDelegate.data_receivedcCs|jdusJ�|j��dSr$)r5�finish�rrrr rDsz_RoutingDelegate.finishcCs|jdur|j��dSdSr$)r5�on_connection_closerErrr rFs
�z$_RoutingDelegate.on_connection_close�rN)r'r(r)rr-rr.r6rr<�ResponseStartLine�HTTPHeadersrrrA�bytesrCrDrFrrrr r%�s(���
���

�
r%c@s*eZdZdejddfdd�Zddd�ZdS)	r@r9rNcCs
||_dSr$)r9)rr9rrr r6s
z _DefaultMessageDelegate.__init__cCs*|j�t�ddd�t���|j��dS)NzHTTP/1.1i�z	Not Found)r9Z
write_headersrrHrIrDrErrr rD"s
�z_DefaultMessageDelegate.finishrG)r'r(r)rr.r6rDrrrr r@sr@�Rule�Matcherc	@s�eZdZdZddeeddfdd�Zdeddfdd�Zddd�Zd
e	j
dedee	jfdd�Z
ded
e	j
dedee	jfdd�ZdS)�
RuleRouterz!Rule-based router implementation.N�rulesrcCsg|_|r|�|�dSdS)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)rN�	add_rules�rrNrrr r6:s�zRuleRouter.__init__cCsv|D]6}t|ttf�r/t|�dvsJ�t|dt�r+tt|d�g|dd��R�}nt|�}|j�|�	|��qdS)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)
r;�tuple�list�lenr	rK�PathMatchesrN�append�process_rule)rrN�rulerrr rOYs"�zRuleRouter.add_rulesr[rKcCs|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�rr[rrr rZiszRuleRouter.process_rulerrcKsZ|jD]'}|j�|�}|dur*|jr|j|d<|j|j|fi|��}|dur*|SqdS)N�
target_kwargs)rN�matcher�matchr]�get_target_delegate�target)rrrr[�
target_paramsr5rrr r!qs

���zRuleRouter.find_handlerrarbcKsxt|t�r|j|fi|��St|tj�r#|jdusJ�|�|j|j�St|�r:|jdus.J�t	t
|fi|��|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)r;rr!r�HTTPServerConnectionDelegater9r&r:�callablerr)rrarrbrrr r`�s
�zRuleRouter.get_target_delegater$�r[rKrrK)r'r(r)r*r�	_RuleListr6rOrZrr+r
r,r!r`rrrr rM7s*
��
�����rMcsXeZdZdZddeeddf�fdd�
Zd�fd	d
�Zdede	deefd
d�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`).
    NrNrcsi|_t��|�dSr$)�named_rules�superr6rP��	__class__rr r6�szReversibleRuleRouter.__init__r[rKcs<t��|�}|jr|j|jvrt�d|j�||j|j<|S)Nz4Multiple handlers named %s; replacing previous value)rirZr0rhr�warningr\rjrr rZ�s�z!ReversibleRuleRouter.process_ruler0r1cGs\||jvr|j|jj|�S|jD]}t|jt�r+|jj|g|�R�}|dur+|SqdSr$)rhr^�reverserNr;rar/r2)rr0r1r[Zreversed_urlrrr r2�s

�z ReversibleRuleRouter.reverse_urlr$re)r'r(r)r*rrfr6rZr3r
r2�
__classcell__rrrjr rg�s
"rgc@sheZdZdZ		ddddedeeeefdeeddf
d	d
�Zdedeefdd
�Z	defdd�Z
dS)rKzA routing rule.Nr^rLrar]r0rcCs6t|t�r	t|�}||_||_|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)r;r3r
r^rar]r0)rr^rar]r0rrr r6�s

z
Rule.__init__r1cGs|jj|�Sr$)r^rm�rr1rrr rm�szRule.reversecCsd�|jj|j|j|j|j�S�Nz${}({!r}, {}, kwargs={!r}, name={!r}))�formatrkr'r^rar]r0rErrr �__repr__�s�z
Rule.__repr__�NN)r'r(r)r*r
rrr3r6rmrrrrrr rK�s"�����
�!c@sFeZdZdZdejdeeee	ffdd�Z
de	deefdd�Zd	S)
rLz*Represents a matcher for request features.rrcCr)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.r�rrrrr r_�s
z
Matcher.matchr1cGsdS)zEReconstructs full url from matcher instance and additional arguments.Nrrorrr rm�zMatcher.reverseN)r'r(r)r*rr+rrr3r
r_rmrrrr rL�s c@s0eZdZdZdejdeeee	ffdd�Z
dS)�
AnyMatcheszMatches any request.rrcCsiSr$rrtrrr r_szAnyMatches.matchN)r'r(r)r*rr+rrr3r
r_rrrr rv	s$rvc@sJeZdZdZdeeefddfdd�Zdej	de
eeeffdd	�Z
dS)
�HostMatchesz@Matches requests from hosts specified by ``host_pattern`` regex.�host_patternrNcCs6t|t�r|�d�s|d7}t�|�|_dS||_dS)N�$)r;r	�endswith�re�compilerx)rrxrrr r6s



zHostMatches.__init__rcCs|j�|j�r	iSdSr$)rxr_Z	host_namertrrr r_szHostMatches.match)r'r(r)r*rr3rr6rr+rrr
r_rrrr rws$rwc@sFeZdZdZdededdfdd�Zdejde	e
eeffd	d
�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.
    �applicationrxrNcCs||_||_dSr$)r~rx)rr~rxrrr r6's
zDefaultHostMatches.__init__rcCs"d|jvr|j�|jj�riSdS)Nz	X-Real-Ip)r8rxr_r~Zdefault_hostrtrrr r_+s
zDefaultHostMatches.match)
r'r(r)r*r
rr6rr+rrr3r_rrrr r}"s$r}c@s~eZdZdZdeeefddfdd�Zdej	de
eeeffdd	�Z
d
ede
efdd�Zdee
ee
effd
d�ZdS)rXz@Matches requests with paths specified by ``path_pattern`` regex.�path_patternrNcCslt|t�r|�d�s|d7}t�|�|_n||_t|jj�d|jjfvs,Jd|jj	��|�
�\|_|_dS)NryrzDgroups in url regexes must either be all named or all positional: %r)
r;r	rzr{r|�regexrW�
groupindex�groups�pattern�_find_groups�_path�_group_count)rrrrr r66s

��zPathMatches.__init__rcCsl|j�|j�}|dur
dS|jjsiSg}i}|jjr'dd�|����D�}n	dd�|��D�}t||d�S)NcSsi|]\}}t|�t|��qSr)r3�_unquote_or_none)�.0�k�vrrr �
<dictcomp>Ts�z%PathMatches.match.<locals>.<dictcomp>cSsg|]}t|��qSr)r�)r��srrr �
<listcomp>Xsz%PathMatches.match.<locals>.<listcomp>)�	path_args�path_kwargs)r�r_r?r�r��	groupdict�items�dict)rrr_r�r�rrr r_Es
�zPathMatches.matchr1cGs�|jdur
td|jj��t|�|jksJd��t|�s|jSg}|D]}t|ttf�s0t	|�}|�
tt|�dd��q#|jt
|�S)NzCannot reverse url regex z&required number of arguments not foundF)�plus)r��
ValueErrorr�r�rWr�r;rrJr3rYrrrU)rr1Zconverted_args�arrr rm\s
�zPathMatches.reversec	Cs�|jj}|�d�r|dd�}|�d�r|dd�}|jj|�d�kr%dSg}|�d�D]F}d|vr[|�d�}|d	krZzt||dd��}Wnt	yRYdSw|�
d
|�q,zt|�}Wnt	ylYdSw|�
|�q,d�|�|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).
        �^rTNry����(rs�)rz%s�)r�r��
startswithrzr��count�split�indexrr�rY�join)rr��pieces�fragmentZ	paren_locZunescaped_fragmentrrr r�ks4


���zPathMatches._find_groups)r'r(r)r*rr3rr6rr+rrr
r_rmr�intr�rrrr rX3s "rXcsbeZdZdZ		ddeeefdedee	eefdeeddf
�fdd	�
Z
defd
d�Z�ZS)
�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.
    Nr��handlerrr0rcs4t|�}t��||||�|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)rXrir6r�ra�
handler_classr)rr�r�rr0r^rjrr r6�s

zURLSpec.__init__cCs d�|jj|jj|j|j|j�Srp)rqrkr'r�r�r�rr0rErrr rr�s�zURLSpec.__repr__rs)
r'r(r)r*rr3rr
rrr6rrrnrrrjr r��s �
�����r�r�rcC�dSr$r�r�rrr r��rur�cCr�r$rr�rrr r��rucCs|dur|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�)rr�rrr r��s)r�NrN)1r*r{�	functoolsrZtornadorZtornado.httpserverrZtornado.escaperrrZtornado.logrZtornado.utilr	r
rr�typingr
rrrrrrrrrrcrr/r,r%r@r3rfrMrgrKrLrvrwr}rXr�rJr�rrrr �<module>sL$0.���h%1a1