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

we�a�@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.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�overloadc@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�H/home/arjun/projects/env/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%rrrrr�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)rr/r0rrr�reverse_url�szReversibleRouter.reverse_urlN)r&r'r(r)�strr
rr1rrrrr.�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"�delegater3)rr3r!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_connectionr6r7z$Delegate for %s %s request not found)�
isinstancer�RequestStartLiner*r"r!r3r r4r�debug�method�path�_DefaultMessageDelegate�headers_received)rr6r7rrrrr@�s �
�z!_RoutingDelegate.headers_received�chunkcCs|jdusJ�|j�|�Sr#)r4�
data_received)rrArrrrBsz_RoutingDelegate.data_receivedcC�|jdusJ�|j��dSr#)r4�finish�rrrrrD
�z_RoutingDelegate.finishcCrCr#)r4�on_connection_closerErrrrGrFz$_RoutingDelegate.on_connection_close�rN)r&r'r(rr,rr-r5rr;�ResponseStartLine�HTTPHeadersrrr@�bytesrBrDrGrrrrr$�s(���
���

�
r$c@s*eZdZdejddfdd�Zddd�ZdS)	r?r8rNcCs
||_dSr#)r8)rr8rrrr5s
z _DefaultMessageDelegate.__init__cCs*|j�t�ddd�t���|j��dS)NzHTTP/1.1i�z	Not Found)r8�
write_headersrrIrJrDrErrrrDs
�z_DefaultMessageDelegate.finishrH)r&r'r(rr-r5rDrrrrr?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)rP�	add_rules�rrPrrrr5/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	rM�PathMatchesrP�append�process_rule)rrP�rulerrrrQNs"�zRuleRouter.add_rulesr]rMcCs|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]rrrr\^szRuleRouter.process_rulerrcKsZ|jD]'}|j�|�}|dur*|jr|j|d<|j|j|fi|��}|dur*|SqdS)N�
target_kwargs)rP�matcher�matchr_�get_target_delegate�target)rrrr]�
target_paramsr4rrrr fs

���zRuleRouter.find_handlerrcrdcKsxt|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�HTTPServerConnectionDelegater8r%r9�callablerr)rrcrrdrrrrbxs
�zRuleRouter.get_target_delegater#�r]rMrrM)r&r'r(r)r�	_RuleListr5rQr\rr*r
r+r rbrrrrrO,s*
��
�����rOcsXeZdZdZddeeddf�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`).
    NrPrcsi|_t��|�dSr#)�named_rules�superr5rR��	__class__rrr5�szReversibleRuleRouter.__init__r]rMcs<t��|�}|jr|j|jvrt�d|j�||j|j<|S)Nz4Multiple handlers named %s; replacing previous value)rkr\r/rjr�warningr^rlrrr\�s�z!ReversibleRuleRouter.process_ruler/r0cGs\||jvr|j|jj|�S|jD]}t|jt�r+|jj|g|�R�}|dur+|SqdSr#)rjr`�reverserPr:rcr.r1)rr/r0r]�reversed_urlrrrr1�s

�z ReversibleRuleRouter.reverse_urlr#rg)r&r'r(r)rrhr5r\r2r
r1�
__classcell__rrrlrri�s
"ric@sheZdZdZ		ddddedeeeefdeeddf
d	d
�Zdedeefdd
�Z	defdd�Z
dS)rMzA routing rule.Nr`rNrcr_r/rcCs6t|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:r2r
r`rcr_r/)rr`rcr_r/rrrr5�s

z
Rule.__init__r0cGs|jj|�Sr#)r`ro�rr0rrrro�szRule.reversecCsd|jj|j|j|j|jfS�Nz%s(%r, %s, kwargs=%r, name=%r))rmr&r`rcr_r/rErrr�__repr__�s�z
Rule.__repr__�NN)r&r'r(r)r
rrr2r5rortrrrrrM�s"�����
�!c@sFeZdZdZdejdeeee	ffdd�Z
de	deefdd�Zd	S)
rNz*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�rrrrrra�s
z
Matcher.matchr0cGsdS)zEReconstructs full url from matcher instance and additional arguments.Nrrrrrrro��zMatcher.reverseN)r&r'r(r)rr*rrr2r
rarorrrrrN�s c@s0eZdZdZdejdeeee	ffdd�Z
dS)�
AnyMatcheszMatches any request.rrcCsiSr#rrvrrrraszAnyMatches.matchN)r&r'r(r)rr*rrr2r
rarrrrrx�s$rxc@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�compilerz)rrzrrrr5s



zHostMatches.__init__rcCs|j�|j�r	iSdSr#)rzra�	host_namervrrrraszHostMatches.match)r&r'r(r)rr2rr5rr*rrr
rarrrrrys$ryc@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.
    �applicationrzrNcCs||_||_dSr#)r�rz)rr�rzrrrr5s
zDefaultHostMatches.__init__rcCs"d|jvr|j�|jj�riSdS)Nz	X-Real-Ip)r7rzrar��default_hostrvrrrra s
zDefaultHostMatches.match)
r&r'r(r)r
rr5rr*rrr2rarrrrr�s$r�c@s~eZdZdZdeeefddfdd�Zdej	de
eeeffdd	�Z
d
ede
efdd�Zdee
ee
effd
d�ZdS)rZz@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)Nr{rzDgroups in url regexes must either be all named or all positional: %r)
r:r	r|r}r~�regexrY�
groupindex�groups�pattern�_find_groups�_path�_group_count)rr�rrrr5+s

��zPathMatches.__init__rcCsp|j�|j�}|dur
dS|jjsiSg}i}|jjr)tdd�|����D��}n	dd�|��D�}t||d�S)Ncss$�|]
\}}t|�t|�fVqdSr#)r2�_unquote_or_none)�.0�k�vrrr�	<genexpr>Is�
�z$PathMatches.match.<locals>.<genexpr>cSsg|]}t|��qSr)r�)r��srrr�
<listcomp>Msz%PathMatches.match.<locals>.<listcomp>)�	path_args�path_kwargs)r�rar>r�r��dict�	groupdict�items)rrrar�r�rrrra:s

�zPathMatches.matchr0cGs�|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�rYr�r:rrKr2r[rrrW)rr0�converted_args�arrrroQs
�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).
        �^rVNr{����(ru�)rz%s�)r�r��
startswithr|r��count�split�indexrr�r[�join)rr��pieces�fragment�	paren_loc�unescaped_fragmentrrrr�`s4


���zPathMatches._find_groups)r&r'r(r)rr2rr5rr*rrr
raror�intr�rrrrrZ(s "rZcsbeZdZdZ		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��handlerrr/rcs4t|�}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)rZrkr5r�rc�
handler_classr)rr�r�rr/r`rlrrr5�s

zURLSpec.__init__cCs d|jj|jj|j|j|jfSrs)rmr&r�r�r�rr/rErrrrt�s�zURLSpec.__repr__ru)
r&r'r(r)rr2rr
rrr5rtrqrrrlrr��s �
�����r�r�rcC�dSr#r�r�rrrr��rwr�cCr�r#rr�rrrr��rwcCs|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�rrrr��s)r�NrN)1r)r}�	functoolsr�tornador�tornado.httpserverr�tornado.escaperrr�tornado.logr�tornado.utilr	r
rr�typingr
rrrrrrrrrerr.r+r$r?r2rhrOrir,rMrNrxryr�rZr�rKr�rrrr�<module>sL$,.���h%1a1