o
    NK&hMk                 
   @  s  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZmZm	Z	m
Z
mZmZ d dlmZ d dlmZmZ d dlmZmZmZmZ d dlmZmZ d dlmZ d d	lmZmZ d d
lm Z  d dl!m"Z" d dl#m$Z$ d dl%m%Z% d dl&m'Z' d dl(m)Z) d dl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z: d dl;m<Z<m=Z= d dl>m?Z? d dl@mAZA d dlBmCZCmDZD d dlEmFZFmGZG d dlHmIZI d dlJmKZK d dlLmMZM d dlNmOZOmPZP d dlQmRZRmSZS d dlTmUZUmVZVmWZWmXZX d dlYmZZZ d dl[m\Z\m]Z] d dl^m_Z_ d d l`maZambZbmcZc d d!ldmeZe d d"lfmgZgmhZh d d#limjZj d d$lkmlZl d d%lmmnZn d d&lompZp d d'lqmrZr d d(lsmtZtmuZumvZvmwZwmxZxmyZy d d)lzm{Z{m|Z| d d*lzm}Z~ d d+lmZ d d,lmZmZmZ d d-lmZ d d.lmZ d d/lmZmZmZ d d0lmZmZ d d1lmZ d d2lmZ d d3lmZ d d4lmZ e+rzd d5lmZ d d6lmZ W n ey   e4d7eZY nw eOreP  e4d8Ze4d9eSd:ZG d;d< d<e1eef epeIenejed=Z}dS )>    )annotationsN)AbstractEventLoopCancelledErrorTaskensure_futureget_running_loopwait_for)Future)defaultdictdeque)	Awaitable	CoroutineIterableIterator)contextmanagersuppress)Enum)partialwraps)isawaitable)environ)Path)socket)
format_exc)SimpleNamespace)TYPE_CHECKINGAnyAnyStrCallableClassVarDequeGenericLiteralOptionalTypeVarUnioncastoverload)	urlencode
urlunparse)FinalizationErrorNotFound)Route)	setup_ext)ApplicationStateServerStage)ASGIAppLifespan)	BaseSanic)BlueprintGroup)	Blueprint)OS_IS_WINDOWSenable_windows_color_support)SANIC_PREFIXConfig)
BadRequestSanicExceptionServerErrorURLBuildError)ErrorHandler)Default_default)Stage)LOGGING_CONFIG_DEFAULTSerror_loggerlogger)setup_logging)
MiddlewareMiddlewareLocation)CommandMixin)ListenerEvent)StartupMixin)StaticHandleMixin)REPLContext)FutureExceptionFutureListenerFutureMiddlewareFutureRegistryFutureRouteFutureSignal)ListenerTypeMiddlewareType)Sanic)Request)BaseHTTPResponseHTTPResponseResponseStream)Router)ConnectionClosed)EventSignalSignalRouter)TouchUpTouchUpMeta)SharedContext)	Inspector)
CertLoader)WorkerManager)Extend)	Extensionrd   ctx_typeconfig_type)boundc                      s  e Zd ZU dZdZdZi Zded< dZded< e	d	d	d	d	d	e
d	dd	d
d	d	dd	d	fdd+d,Ze	d	d	d	d	d	e
d	dd	d
d	d	dd	d	fdd/d,Ze	d	d	d	d	d	e
d	dd	d
d	d	dd	d	fdd2d,Ze	d	d	d	d	d	e
d	dd	d
d	d	dd	d	fdd4d,Zd	d	d	d	d	e
d	dd	d
d	d	dd	d	fd fd5d,Zed d7d8Zd9d:d!d@dAZ	Bd"ed:d#dGdHZ	Bd"ed:d$dLdMZ		d%d&dQdRZd'dTdUZ	d(d)dZd[Z		d%d*d]d^Zd+dbdcZe	d	d	d
dddd,dmdnZe	d	d	d
dddod-drdnZd	d	d
dddod.dtdnZ		d%d	d
dud/dzd{Zd0d~dZd1d2ddZd	d	d	d	d	dd3ddZd4ddZ	
d1d5ddZd6ddZd	dddZed7ddZ ed8ddZ!dd Z"dd Z#dd Z$e%dd Z&e'd9ddZ(e%dd Z)e%d	d
dd:ddZ*e'd;ddZ+e'd<ddZ,d	d
dd=ddZ-e	d>ddZ.e	d?ddZ.e	d@ddZ.d
dƜd@ddZ.		d%d
dƜdAddʄZ/dBdd̄Z0	͐dCdDdd҄Z1edEddՄZ2ddׄ Z3d
Z4dFddڄZ5edGdd܄Z6e6j7dHdd܄Z6edGddZ8edGddZ9e9j7dHddZ9edIddZ:edJddZ;edKddZ<d	d
d	ddLddZ=e%dMddZ>e%dMddZ?e%		d%dddNddZ@e%dBddZAeBdOdd ZCdBddZDd1dPddZEdd ZFdBdd	ZGdQddZH		d%dRddZI		d%dSddZJedTddZKedUddZL  ZMS (V  rT   a	  The main application instance

    You will create an instance of this class and use it to register
    routes, listeners, middleware, blueprints, error handlers, etc.

    By convention, it is often called `app`. It must be named using
    the `name` parameter and is roughly constrained to the same
    restrictions as a Python module name, however, it can contain
    hyphens (`-`).

    ```python
    # will cause an error because it contains spaces
    Sanic("This is not legal")
    ```

    ```python
    # this is legal
    Sanic("Hyphens-are-legal_or_also_underscores")
    ```

    Args:
        name (str): The name of the application. Must be a valid
            Python module name (including hyphens).
        config (Optional[config_type]): The configuration to use for
            the application. Defaults to `None`.
        ctx (Optional[ctx_type]): The context to use for the
            application. Defaults to `None`.
        router (Optional[Router]): The router to use for the
            application. Defaults to `None`.
        signal_router (Optional[SignalRouter]): The signal router to
            use for the application. Defaults to `None`.
        error_handler (Optional[ErrorHandler]): The error handler to
            use for the application. Defaults to `None`.
        env_prefix (Optional[str]): The prefix to use for environment
            variables. Defaults to `SANIC_`.
        request_class (Optional[Type[Request]]): The request class to
            use for the application. Defaults to `Request`.
        strict_slashes (bool): Whether to enforce strict slashes.
            Defaults to `False`.
        log_config (Optional[Dict[str, Any]]): The logging configuration
            to use for the application. Defaults to `None`.
        configure_logging (bool): Whether to configure logging.
            Defaults to `True`.
        dumps (Optional[Callable[..., AnyStr]]): The function to use
            for serializing JSON. Defaults to `None`.
        loads (Optional[Callable[..., Any]]): The function to use
            for deserializing JSON. Defaults to `None`.
        inspector (bool): Whether to enable the inspector. Defaults
            to `False`.
        inspector_class (Optional[Type[Inspector]]): The inspector
            class to use for the application. Defaults to `None`.
        certloader_class (Optional[Type[CertLoader]]): The certloader
            class to use for the application. Defaults to `None`.
    )handle_requesthandle_exception_run_response_middleware_run_request_middleware)+	_asgi_app_asgi_lifespan_asgi_client_blueprint_order_delayed_tasks_ext_future_commands_future_exceptions_future_listeners_future_middleware_future_registry_future_routes_future_signals_future_statics
_inspector_manager_state_task_registry_test_client_test_manager
blueprintscertloader_classconfigconfigure_loggingctxerror_handlerinspector_classgo_fast	listenersmultiplexernamed_request_middlewarenamed_response_middlewarerepl_ctxrequest_classrequest_middlewareresponse_middlewarerouter
shared_ctxsignal_routersockstrict_slasheswebsocket_enabledwebsocket_taskszClassVar[dict[str, Sanic]]_app_registryFzClassVar[bool]	test_modeNTselfSanic[Config, SimpleNamespace]namestrr   Noner   r   Optional[Router]r   Optional[SignalRouter]r   Optional[ErrorHandler]
env_prefixOptional[str]r   Optional[type[Request]]r   bool
log_configOptional[dict[str, Any]]r   dumpsOptional[Callable[..., AnyStr]]loadsOptional[Callable[..., Any]]	inspectorr   Optional[type[Inspector]]r   Optional[type[CertLoader]]returnc                 C     d S N r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   </var/www/html/venv/lib/python3.10/site-packages/sanic/app.py__init__      zSanic.__init__#Sanic[config_type, SimpleNamespace]Optional[config_type]c                 C  r   r   r   r   r   r   r   r      r   Sanic[Config, ctx_type]Optional[ctx_type]c                 C  r   r   r   r   r   r   r   r     r   Sanic[config_type, ctx_type]c                 C  r   r   r   r   r   r   r   r   $  r   c                   s  t  j|d |r|
pt}tj| |r|tkrtdtt	|p%t
|d| _|r.|| j_d | _d | _d | _g | _g | _t | _d | _d | _t| d| _i | _d | _d | _d| _d| _i | _|pbt| _|| _tt |pmt! | _"|ptt# | _$|pyt%| _&t't(| _)i | _*i | _+t, | _-|pt.| _/t0 | _1t0 | _2|pt3 | _4t5 | _6|pt7 | _8d | _9|	| _:d| _;t< | _=| j>| _?| | j4j"_@| | j8j"_@| jAB|  |r|tC_D|r|t._Ed S d S )Nr   zEWhen instantiating Sanic with config, you cannot also pass env_prefix)r   appF)Fsuperr   rA   loggingr   
dictConfigr7   r:   r&   rg   r8   	INSPECTORrm   rn   ro   rp   rq   rO   rw   r{   r|   r.   r}   r~   r   r   asgiauto_reloadr   rb   r   r   rf   r   r   r=   r   ra   r   r
   listr   r   r   rK   r   rU   r   r   r   r   rY   r   r`   r   r]   r   r   r   r   setr   runr   r   	__class__register_apprV   _dumps_loads)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   dict_configr   r   r   r   9  sr   





r   c                 C  s^   | j jtju r| jdu rtdzt W S  ty.   tj	dkr(t
   Y S t
  Y S w )a&  Synonymous with asyncio.get_event_loop().

        .. note::
            Only supported when using the `app.run` method.

        Returns:
            AbstractEventLoop: The event loop for the application.

        Raises:
            SanicException: If the application is not running.
        FziLoop can only be retrieved after the app has started running. Not supported with `create_server` function)   
   )statestager/   STOPPEDr   r:   r   RuntimeErrorsysversion_infoasyncioget_event_loop_policyget_event_loopr   r   r   r   loop  s   
z
Sanic.loopr   prioritylistenerListenerType[SanicVar]eventr   intc             	   C  s   zt |  }W n  ttfy(   dtdd t j }td| d| w d|v r>| j	|j
|dt| j|d |S |rItd	|j
  | j|j
 | |S )
zRegister the listener for a given event.

        Args:
            listener (Callable): The listener to register.
            event (str): The event to listen for.

        Returns:
            Callable: The listener that was registered.
        , c                 S  s   |   S r   )lower)xr   r   r   <lambda>  s    z)Sanic.register_listener.<locals>.<lambda>zInvalid event: z. Use one of: .r   )r   zPriority is not supported for )rH   upper
ValueErrorAttributeErrorjoinmap__members__keysr9   signalvaluer   	_listenerrB   warningr   append)r   r   r   r   _eventvalidr   r   r   register_listener  s&   

zSanic.register_listenerrequest
middleware!Union[MiddlewareType, Middleware]	attach_toUnion[Default, int]c                C  s   |}t |  }t|tst||t|tr|ndd}n|j|kr/t|tr/t|j|j|d}|t ju r?|| j	vr?| j	
| |t ju rO|| jvrO| j| |S )ab  Register a middleware to be called before a request is handled.

        Args:
            middleware (Callable): A callable that takes in a request.
            attach_to (str): Whether to attach to request or response.
                Defaults to `'request'`.
            priority (int): The priority level of the middleware.
                Lower numbers are executed first. Defaults to `0`.

        Returns:
            Union[Callable, Callable[[Callable], Callable]]: The decorated
                middleware function or a partial function depending on how
                the method was called.
        r   locationr   )rF   r   
isinstancerE   r   r   funcr   REQUESTr   r   RESPONSEr   
appendleft)r   r   r   r   retvalr   r   r   r   register_middleware  s*   




zSanic.register_middlewarerS   route_namesIterable[str]c                C  s   |}t |  }t|tst||t|tr|ndd}n|j|kr/t|tr/t|j|j|d}|t ju rS|D ]}|| j	vrCt
 | j	|< || j	| vrR| j	| | q6|t ju rw|D ]}|| jvrgt
 | j|< || j| vrv| j| | qZ|S )a  Used to register named middleqare (middleware typically on blueprints)

        Args:
            middleware (Callable): A callable that takes in a request.
            route_names (Iterable[str]): The route names to attach the
                middleware to.
            attach_to (str): Whether to attach to request or response.
                Defaults to `'request'`.
            priority (int): The priority level of the middleware.
                Lower numbers are executed first. Defaults to `0`.

        Returns:
            Union[Callable, Callable[[Callable], Callable]]: The decorated
                middleware function or a partial function depending on how
                the method was called.
        r   r   )rF   r   r   rE   r   r   r   r   r   r   r   r   r   r   r   )r   r   r  r   r   r  r   _rnr   r   r   register_named_middleware  s:   




zSanic.register_named_middlewarehandlerrL   Optional[list[str]]c                 C  sP   |j D ]!}t|ttfr|D ]}| j||j| qq| j||j| q|jS )zDecorate a function to be registered as a handler for exceptions

        :param exceptions: exceptions
        :return: decorated function
        )
exceptionsr   tupler   r   addr  )r   r  r  	exceptioner   r   r   _apply_exception_handler7  s   
zSanic._apply_exception_handlerrM   c                 C  s   | j |j|j|jdS )Nr   )r   r   r   r   )r   r   r   r   r   _apply_listenerJ  s   zSanic._apply_listenerrouterP   	overwritelist[Route]c           
      C  s   |  }||d< |dd}|dd }|r/|   t| j|j|d}|jj|_d|_||d< |d}|  2 | j	j
d
i |}t|trJ|g}|D ]}	||	j_|d	d|	j_|	jj| qLW d    |S 1 smw   Y  |S )Nr  	websocketFsubprotocolsr  Tr  route_contextstaticr   )_asdictpopenable_websocketr   _websocket_handlerr  __name__is_websocketamendr   r  r   r,   extrar  getr  r   __dict__update)
r   r  r  paramsr  r  websocket_handlerr   routesrr   r   r   _apply_routeO  s8   






zSanic._apply_routerN   c                 C  s`   |   " |r| |j||jW  d    S | |j|jW  d    S 1 s)w   Y  d S r   )r  r  r   r   r  )r   r   r  r   r   r   _apply_middlewarep  s   

$zSanic._apply_middlewarer   rQ   r\   c                 C  sL   |    | jj|j|j|j|j|jdW  d    S 1 sw   Y  d S )N)r  r   	condition	exclusiver   )r  r   r  r  r   r)  r*  r   )r   r   r   r   r   _apply_signal  s   
$zSanic._apply_signal)r)  contextfail_not_foundreverser)  Optional[dict[str, str]]r,  r-  inlineLiteral[True]r.  #Coroutine[Any, Any, Awaitable[Any]]c                C  r   r   r   r   r   r)  r,  r-  r0  r.  r   r   r   dispatch     
zSanic.dispatch)r)  r,  r-  r0  r.  Literal[False]$Coroutine[Any, Any, Awaitable[Task]]c                C  r   r   r   r3  r   r   r   r4    r5  0Coroutine[Any, Any, Awaitable[Union[Task, Any]]]c                C  s   | j j||||||dS )a~  Dispatches an event to the signal router.

        Args:
            event (str): Name of the event to dispatch.
            condition (Optional[Dict[str, str]]): Condition for the
                event dispatch.
            context (Optional[Dict[str, Any]]): Context for the event dispatch.
            fail_not_found (bool): Whether to fail if the event is not found.
                Default is `True`.
            inline (bool): If `True`, returns the result directly. If `False`,
                returns a `Task`. Default is `False`.
            reverse (bool): Whether to reverse the dispatch order.
                Default is `False`.

        Returns:
            Coroutine[Any, Any, Awaitable[Union[Task, Any]]]: An awaitable
                that returns the result directly if `inline=True`, or a `Task`
                if `inline=False`.

        Examples:
            ```python
            @app.signal("user.registration.created")
            async def send_registration_email(**context):
                await send_email(context["email"], template="registration")

            @app.post("/register")
            async def handle_registration(request):
                await do_registration(request)
                await request.app.dispatch(
                    "user.registration.created",
                    context={"email": request.json.email}
                })
            ```
        )r,  r)  r0  r.  r-  )r   r4  r3  r   r   r   r4    s   ,)r)  r*  Union[str, Enum]timeoutOptional[Union[int, float]]r*  c                  sv   | j |||}|s'| jjr'| j   | d| | j |||}| j   |s0td| t|	 |dI dH S )ae  Wait for a specific event to be triggered.

        This method waits for a named event to be triggered and can be used
        in conjunction with the signal system to wait for specific signals.
        If the event is not found and auto-registration of events is enabled,
        the event will be registered and then waited on. If the event is not
        found and auto-registration is not enabled, a `NotFound` exception
        is raised.

        Auto-registration can be handled by setting the `EVENT_AUTOREGISTER`
        config value to `True`.

        ```python
        app.config.EVENT_AUTOREGISTER = True
        ```

        Args:
            event (str): The name of the event to wait for.
            timeout (Optional[Union[int, float]]): An optional timeout value
                in seconds. If provided, the wait will be terminated if the
                timeout is reached. Defaults to `None`, meaning no timeout.
            condition: If provided, method will only return when the signal
                is dispatched with the given condition.
            exclusive: When true (default), the signal can only be dispatched
                when the condition has been met. When ``False``, the signal can
                be dispatched either with or without it.

        Raises:
            NotFound: If the event is not found and auto-registration of
                events is not enabled.

        Returns:
            The context dict of the dispatched signal.

        Examples:
            ```python
            async def wait_for_event(app):
                while True:
                    print("> waiting")
                    await app.event("foo.bar.baz")
                    print("> event found")

            @app.after_server_start
            async def after_server_start(app, loop):
                app.add_task(wait_for_event(app))
            ```
        NzCould not find signal )r:  )
r   
get_waiterr   EVENT_AUTOREGISTERreset
add_signalfinalizer+   r   wait)r   r   r:  r)  r*  waiterr   r   r   r     s   8

zSanic.event7Callable[[Sanic, Exception], Coroutine[Any, Any, None]]0Callable[[Exception], Coroutine[Any, Any, None]]c                   s.   t  d	 fdd}j|tjjd |S )
a  Register a handler to report exceptions.

        A convenience method to register a handler for the signal that
        is emitted when an exception occurs. It is typically used to
        report exceptions to an external service.

        It is equivalent to:

        ```python
        @app.signal(Event.SERVER_EXCEPTION_REPORT)
        async def report(exception):
            await do_something_with_error(exception)
        ```

        Args:
            handler (Callable[[Sanic, Exception], Coroutine[Any, Any, None]]):
                The handler to register.

        Returns:
            Callable[[Sanic, Exception], Coroutine[Any, Any, None]]: The
                handler that was registered.
        r  	Exceptionr   r   c                   s    | I d H  d S r   r   )r  r  r   r   r   report5  s   z&Sanic.report_exception.<locals>.report)r  r   N)r  rE  r   r   )r   r?  r[   SERVER_EXCEPTION_REPORTr   )r   r  rG  r   rF  r   report_exception  s   zSanic.report_exceptionenablec                 C  s    | j s| d| j || _ dS )a  Enable or disable the support for websocket.

        Websocket is enabled automatically if websocket routes are
        added to the application. This typically will not need to be
        called manually.

        Args:
            enable (bool, optional): If set to `True`, enables websocket
                support. If set to `False`, disables websocket support.
                Defaults to `True`.

        Returns:
            None
        before_server_stopN)r   r   _cancel_websocket_tasks)r   rJ  r   r   r   r  ?  s   
zSanic.enable_websocket)
url_prefixversionr   version_prefixname_prefix	blueprint5Union[Blueprint, Iterable[Blueprint], BlueprintGroup]rM  rN   Optional[Union[int, float, str]]Optional[bool]rO  rP  c                C  s  i }|dur
||d< |dur||d< |dur||d< |dur"||d< |dur*||d< t |ttfr|D ]}i |}	t |tr|dd|jpGdg}
t |tsV|
|jpTd dd	d
 |
D d}d| |	d< dD ]}t||du rt||p~|||	|< ql|j	dkr|j	dkr|d|	d< n|j	|	d< t|dd}|rd|	vr||	d< | j
|fi |	 q3dS |j| jv r| j|j |u sJ d|jf n|| j|j< | j| | jdur|jdu r| j|_|| | dS )a  Register a blueprint on the application.

        See [Blueprints](/en/guide/best-practices/blueprints) for more information.

        Args:
            blueprint (Union[Blueprint, Iterable[Blueprint], BlueprintGroup]): Blueprint object or (list, tuple) thereof.
            url_prefix (Optional[str]): Prefix for all URLs bound to the blueprint. Defaults to `None`.
            version (Optional[Union[int, float, str]]): Version prefix for URLs. Defaults to `None`.
            strict_slashes (Optional[bool]): Enforce the trailing slashes. Defaults to `None`.
            version_prefix (Optional[str]): Prefix for version. Defaults to `None`.
            name_prefix (Optional[str]): Prefix for the blueprint name. Defaults to `None`.

        Example:
            ```python
            app = Sanic("TestApp")
            bp = Blueprint('TestBP')

            @bp.route('/route')
            def handler(request):
                return text('Hello, Blueprint!')

            app.blueprint(bp, url_prefix='/blueprint')
            ```
        NrM  rN  r   rO  rP   /c                 s  s"    | ]}|rt |d V  qdS )rV  N)r   strip).0ur   r   r   	<genexpr>  s    
z"Sanic.blueprint.<locals>.<genexpr>)rN  r   z/vzVA blueprint with the name "%s" is already registered.  Blueprint names must be unique.)r   r   r3   r   rM  r   r   rstripgetattrrO  rQ  r   r   rp   r   register)r   rQ  rM  rN  r   rO  rP  optionsitemr#  
merge_frommerged_prefix_attrr   r   r   rQ  V  sr   "









zSanic.blueprint	view_namec              	   K  s  i }d|vr| j  d| }|dr'|dd}|r!|d|}|j|d | jj|fi |}|s;td| d|j}t	|j
ddrq|d	d
}d|v rq|ddd }|drb|dd }|drm|dd }||d< |dkr|dr|js|jdd s|dd }|dsd| }|}	|dd |dd
}
|dd}|ddpt|}|dd
}|j
jr|r|st|j
jdkrtdd|j
j |r||j
jvrtd| d|j
j |st|j
jd }|r|std|dd}|du r|r|p| jdd
}|rL|s;d|dd v r.|dd ddd }nd }|j
jr;|d d!}d"|dd v rL|d"dd }|  |j D ]u}z
t||j }W n tyr   td#|j  d$w |jrt|jtr|jd n|j}| |}|s|j!turd%| d&|j  d'|j!j" d(|j }t|d%| d&|j  d)|j }t|d*|j  d+}t#$|||	}	qU|rt%|d,d-nd
}t&|||	d
||
f}	|	S ).a	  Build a URL based on a view name and the values provided.

        This method constructs URLs for a given view name, taking into account
        various special keyword arguments that can be used to modify the resulting
        URL. It can handle internal routing as well as external URLs with different
        schemes.

        There are several special keyword arguments that can be used to modify
        the URL that is built. They each begin with an underscore. They are:

        - `_anchor`
        - `_external`
        - `_host`
        - `_server`
        - `_scheme`

        Args:
            view_name (str): String referencing the view name.
            _anchor (str): Adds an "#anchor" to the end.
            _scheme (str): Should be either "http" or "https", default is "http".
            _external (bool): Whether to return the path or a full URL with scheme and host.
            _host (str): Used when one or more hosts are defined for a route to tell Sanic which to use.
            _server (str): If not using "_host", this will be used for defining the hostname of the URL.
            **kwargs: Keys and values that are used to build request parameters and
                    query string arguments.

        Raises:
            URLBuildError: If there are issues with constructing the URL.

        Returns:
            str: The built URL.

        Examples:
            Building a URL for a specific view with parameters:
            ```python
            url_for('view_name', param1='value1', param2='value2')
            # /view-name?param1=value1&param2=value2
            ```

            Creating an external URL with a specific scheme and anchor:
            ```python
            url_for('view_name', _scheme='https', _external=True, _anchor='section1')
            # https://example.com/view-name#section1
            ```

            Creating a URL with a specific host:
            ```python
            url_for('view_name', _host='subdomain.example.com')
            # http://subdomain.example.com/view-name
        r   z.staticr   Nr  r   zEndpoint with name `z` was not foundfilenamerU  __file_uri__z<__file_uri__:   r   rV  _method_anchor_host	_externalF_schemezHost is ambiguous: r   zRequested host (z#) is not available for this route: z/When specifying _scheme, _external must be True_serverSERVER_NAME:   httpwsz://zRequired parameter `z` was not passed to url_forzValue "z" for parameter `z#` does not match pattern for type `z`: z` does not satisfy pattern z(<z.*?>)T)doseq)'r   endswithr  replacer"  r   find_route_by_view_namer<   pathr\  r  split
startswithstrictraw_pathr   hostslenr   r   r   r   r   r  r@  r#  valuesr   KeyErrorpatternr   r
  matchr&   r  resubr(   r)   )r   rc  kwargskwr   r  urird  folder_outanchorhostexternalschemenetloc
param_infosupplied_paramr  passes_patternmsgreplacement_regexquery_stringr   r   r   url_for  s   4








zSanic.url_forrU   r  BaseExceptionrun_middlewarec           	   
     s  d}t |dds	 | jdd|idI dH  | jdd||d	d
I dH  |jdurZ|jjtjurZtj|dd t	d| d | j
||rI|jnd}|rXtd|j d dS |rz|jod|jjjpg| j}| ||I dH }W n ty } z| ||dI dH W  Y d}~S d}~ww |sz| j
||}t|r|I dH }W n6 ty } z*t|tr| j
||}n| jrtd| dt  dd}ntddd}W Y d}~nd}~ww |dur	z|  ||I dH }W n# ty   |jr|j| |j ddI dH   w |jr|jj}t|t!r0| jdd||dd
I dH  |j ddI dH  dS t|t"rT||I dH }| jdd||dd
I dH  |# I dH  dS t$d|d)a  A handler that catches specific exceptions and outputs a response.

        .. note::
            This method is typically used internally, and you should not need
            to call it directly.

        Args:
            request (Request): The current request object.
            exception (BaseException): The exception that was raised.
            run_middleware (bool): Whether to run middleware. Defaults
                to `True`.

        Raises:
            ServerError: response 500.
        N__dispatched__Fserver.exception.reportr  r,  zhttp.lifecycle.exceptionT)r   r  r0  r,  )exc_infozOThe error response will not be sent to the client for the following exception:"z8". A previous response has at least partially been sent.zAn error occurred while handling the request after at least some part of the response was sent to the client. The response from your custom exception handler ag   will not be sent to the client.Exception handlers should only be used to generate the exception responses. If you would like to perform any other action on a raised exception, consider using a signal handler like `@app.signal("http.lifecycle.exception")`
For further information, please see the docs: https://sanicframework.org/en/guide/advanced/signals.htmlzError while handling error: z
Stack: i  )statusz)An error occurred while handling an error
end_streamhttp.lifecycle.responser   responseInvalid response type  (need HTTPResponse))%r\  r4  streamr   r@   HANDLERrB   r  rC   errorr   _lookupr   r   r  r  r  r   rl   rE  rj   r  r   r   r:   defaultdebugrW   r   reset_responserespondr  sendrV   rX   eofr;   )	r   r   r  r  r  r  r   r  respr   r   r   rj   u  s   
 



zSanic.handle_exceptionc           
   
     s  d}| j ddd|idI dH  d}d}z!| j ddd|idI dH  | j|j|j|jdd\}}}i ||_||_| j dd||||d	dI dH  |j	rk|j	j
rk|jjskt|d
rdtd|j	_n| I dH  d}|jjjr~| ||jjjI dH }|s|du rtd| j ddd|idI dH  ||fi |j}t|r|I dH }| j ddd|idI dH  |jr|durtd |j	dur|j	j}n|dur||I dH }n	t|ds|j	j}t|tr| j dd||ddI dH  	 |jddI dH  W dS t|tr&||I dH }| j dd||ddI dH  | I dH  W dS t|ds4td|dW dS  t y?     t!y] }	 z| j"||	|dI dH  W Y d}	~	dS d}	~	ww )aL  Handles a request by dispatching it to the appropriate handler.

        .. note::
            This method is typically used internally, and you should not need
            to call it directly.

        Args:
            request (Request): The current request object.

        Raises:
            ServerError: response 500.
        Tzhttp.lifecycle.handler   r  Nzhttp.routing.beforer  zhttp.routing.after)r   r  r  r  	is_streaminfFz>'None' was returned while requesting a handler from the routerzhttp.handler.beforezhttp.handler.afterzxThe response object returned by the route handler will not be sent to client. The request has already been responded to.r  r  r  r  r  r  )r  )#r4  r   r   rw  methodheadersgetone_match_infor  r  request_bodyr  ignore_bodyhasattrfloatrequest_max_sizereceive_bodyr   rl   r;   
match_infor   	respondedrB   r  r  r  r   rV   r  rX   r  r   rE  rj   )
r   r   __tracebackhide__r  r  r  r  r  r  r  r   r   r   ri     s   









zSanic.handle_requestr  c             
     s  | j r|j }||I d H  n|j }|||I d H }| jdd||dddI d H  t|||g|R i |}| j	| d}	zgz|I d H  | jdd||ddddI d H  W n6 t
tfyj   d}	Y n* ty }
 z| j||
 | jdd|||
d	dddI d H  W Y d }
~
nd }
~
ww W | j| |	r|d
 d S | I d H  d S | j| |	r|d
 w | I d H  w )Nzwebsocket.handler.beforeT)r   r  F)r0  r,  r-  zwebsocket.handler.after)r0  r,  r.  r-  zwebsocket.handler.exception)r   r  r  i  )r   	transportget_websocket_connectionacceptget_protocolwebsocket_handshaker4  r   r   r  r   rZ   rE  r   logremoveend_connectionclose)r   r  r   r  argsr  rr  protocolfut	cancelledr  r   r   r   r    s\   

	


zSanic._websocket_handlerSanicTestClientc                 C  6   | j r| j S | jr| jjS ddlm} || | _ | j S )a  A testing client that uses httpx and a live running server to reach into the application to execute handlers.

        This property is available if the `sanic-testing` package is installed.

        See [Test Clients](/en/plugins/sanic-testing/clients#wsgi-client-sanictestclient) for details.

        Returns:
            SanicTestClient: A testing client from the `sanic-testing` package.
        r   )r  )r   r   test_clientsanic_testing.testingr  )r   r  r   r   r   r       
zSanic.test_clientSanicASGITestClientc                 C  r  )a  A testing client that uses ASGI to reach into the application to execute handlers.

        This property is available if the `sanic-testing` package is installed.

        See [Test Clients](/en/plugins/sanic-testing/clients#asgi-async-client-sanicasgitestclient) for details.

        Returns:
            SanicASGITestClient: A testing client from the `sanic-testing` package.
        r   )r  )ro   r   asgi_clientr  r  )r   r  r   r   r   r    r  zSanic.asgi_clientc                   s   d|_ |D ]7}| jdd|d dddidI d H  ||}t|r&|I d H }| jdd|d dddidI d H  |r=|  S qd S )NThttp.middleware.beforer  r   r   r0  r,  r)  http.middleware.after)_request_middleware_startedr4  r   )r   r   middleware_collectionr   r  r   r   r   rl     s4   


zSanic._run_request_middlewarec                   s   |D ]H}| j dd||dddidI d H  |||}t|r$|I d H }| j dd||r-|n|dddidI d H  |rK|}t|trH|j|} |S q|S )Nr  Tr  r   r  r  r  )r4  r   r   rV   r  r  )r   r   r  r  r   	_responser   r   r   rk   $  s:   





zSanic._run_response_middlewarec                 G  s   | j g|}d|S )Nr   )r   r   )r   partsr   r   r   _build_endpoint_nameG  s   
zSanic._build_endpoint_namec                 C  s   |j D ]}|  qd S r   )r   cancel)clsr   r   taskr   r   r   rL  K  s   

zSanic._cancel_websocket_tasksr   r   rR   c                   sN   z|| }W n t y   || |}Y nw |r#t|r%|I d H  d S d S d S r   )	TypeErrorr   )r   r   r   
maybe_coror   r   r   r   P  s   zSanic._listenerc                   s    fdd}||S )Nc              
     s   z&t | rz|  } W n ty   |  } Y nw t| r%| I d H  W d S W d S  ty8   td|  d   tyP } z jdd|idI d H   d }~ww )NzTask z# was cancelled before it completed.r  r  r  )callabler  r   r   rB   r   rE  r4  )r  r  r   r   r   dof  s0   

zSanic._prep_task.<locals>.dor   )r  r  r   r   r  r   r   r   
_prep_task_  s   zSanic._prep_taskr   r]  r]  r   c                C  s@   |}t |ts| |||}|j||d}|r|r||j|< |S )Nr   )r   r	   r  create_taskr~   )r  r  r   r   r   r]  tskpreppedr   r   r   _loop_add_task}  s   


zSanic._loop_add_taskc                   s6   | j D ]}| j|| |ddI dH  q| j   dS )a  Signal handler for dispatching delayed tasks.

        This is used to dispatch tasks that were added before the loop was
        started, and will be called after the loop has started. It is
        not typically used directly.

        Args:
            app (Sanic): The Sanic application instance.
            loop (AbstractEventLoop): The event loop in which the tasks are
                being run.

        Returns:
            None
        r   r   r  N)rq   r4  clear)r   r   r   r   r   r   dispatch_delayed_tasks  s   
zSanic.dispatch_delayed_tasksr  -Union[Future[Any], Task[Any], Awaitable[Any]]c                   s   |  || |}|I dH  dS )aF  Executes a delayed task within the context of a given app and loop.

        This method prepares a given task by invoking the app's private
        `_prep_task` method and then awaits the execution of the prepared task.

        Args:
            app (Any): The application instance on which the task will
                be executed.
            loop (AbstractEventLoop): The event loop where the task will
                be scheduled.
            task (Task[Any]): The task function that will be prepared
                and executed.

        Returns:
            None
        N)r  )r   r   r  r  r   r   r   run_delayed_task  s   zSanic.run_delayed_task<Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]]Optional[Task[Any]]c                C  s   z| j }| j|| |||dW S  tyB   dt| }| js'| t| j |r-td| 	|t| j
|d | j| Y dS w )a  Schedule a task to run later, after the loop has started.

        While this is somewhat similar to `asyncio.create_task`, it can be
        used before the loop has started (in which case it will run after the
        loop has started in the `before_server_start` listener).

        Naming tasks is a good practice as it allows you to cancel them later,
        and allows Sanic to manage them when the server is stopped, if needed.

        [See user guide re: background tasks](/en/guide/basics/tasks#background-tasks)

        Args:
            task (Union[Future[Any], Coroutine[Any, Any, Any], Awaitable[Any]]):
                The future, coroutine, or awaitable to schedule.
            name (Optional[str], optional): The name of the task, if needed for
                later reference. Defaults to `None`.
            register (bool, optional): Whether to register the task. Defaults
                to `True`.

        Returns:
            Optional[Task[Any]]: The task that was scheduled, if applicable.
        r  zsanic.delayed_task.z1Cannot name task outside of a running application)r  N)r   r  r:   hashrq   after_server_startr   r  r   r   r  r   )r   r  r   r]  r   	task_namer   r   r   add_task  s"   
zSanic.add_taskraise_exceptionc                C  r   r   r   r   r   r  r   r   r   get_task     zSanic.get_taskOptional[Task]c                C  r   r   r   r  r   r   r   r    r  c                C  r   r   r   r  r   r   r   r    r  r  c                C  s6   z| j | W S  ty   |rtd| dY dS w )a  Get a named task.

        This method is used to get a task by its name. Optionally, you can
        control whether an exception should be raised if the task is not found.

        Args:
            name (str): The name of the task to be retrieved.
            raise_exception (bool): If `True`, an exception will be raised if
                the task is not found. Defaults to `True`.

        Returns:
            Optional[Task]: The task, if found.
        zRegistered task named "z" not found.N)r~   r  r:   r  r   r   r   r     s   
r  c                  sb   | j ||d}|r-| s/d}|r|f}|j|  z|I dH  W dS  ty,   Y dS w dS dS )a  Cancel a named task.

        This method is used to cancel a task by its name. Optionally, you can
        provide a message that describes why the task was canceled, and control
        whether an exception should be raised if the task is not found.

        Args:
            name (str): The name of the task to be canceled.
            msg (Optional[str]): Optional message describing why the task was canceled. Defaults to None.
            raise_exception (bool): If True, an exception will be raised if the task is not found. Defaults to True.

        Example:
            ```python
            async def my_task():
                try:
                    await asyncio.sleep(10)
                except asyncio.CancelledError as e:
                    current_task = asyncio.current_task()
                    print(f"Task {current_task.get_name()} was cancelled. {e}")
                    # Task sleepy_task was cancelled. No more sleeping!


            @app.before_server_start
            async def before_start(app):
                app.add_task(my_task, name="sleepy_task")
                await asyncio.sleep(1)
                await app.cancel_task("sleepy_task", msg="No more sleeping!")
            ```
        r  r   N)r  r  r  r   )r   r   r  r  r  r  r   r   r   cancel_task  s   $
zSanic.cancel_taskc                 C  sR   | j  D ]\}}|du rq| s| rd| j |< qdd | j  D | _ dS )a  Purges completed and cancelled tasks from the task registry.

        This method iterates through the task registry, identifying any tasks
        that are either done or cancelled, and then removes those tasks,
        leaving only the pending tasks in the registry.
        Nc                 S  s   i | ]\}}|d ur||qS r   r   )rX  kvr   r   r   
<dictcomp>U      z%Sanic.purge_tasks.<locals>.<dictcomp>)r~   itemsdoner  )r   keyr  r   r   r   purge_tasksH  s   
zSanic.purge_tasks皙?Optional[float]	incrementr  c                 C  s   | j D ]}| dkr|  q|du r| jj}t| jrO|rQtt t	 }|
t| W d   n1 s9w   Y  |   ||8 }t| jrS|sdS dS dS dS )a  Cancel all tasks except the server task.

        This method is used to cancel all tasks except the server task. It
        iterates through the task registry, cancelling all tasks except the
        server task, and then waits for the tasks to complete. Optionally, you
        can provide a timeout and an increment to control how long the method
        will wait for the tasks to complete.

        Args:
            timeout (Optional[float]): The amount of time to wait for the tasks
                to complete. Defaults to `None`.
            increment (float): The amount of time to wait between checks for
                whether the tasks have completed. Defaults to `0.1`.
        	RunServerN)tasksget_namer  r   GRACEFUL_SHUTDOWN_TIMEOUTr}  r~   r   r   r   run_until_completer   sleepr   )r   r:  r  r  running_loopr   r   r   shutdown_tasksY  s   

zSanic.shutdown_tasksIterable[Task[Any]]c                 C  s   dd t | j D S )zThe tasks that are currently registered with the application.

        Returns:
            Iterable[Task[Any]]: The tasks that are currently registered with
                the application.
        c                 s  s    | ]	}|d ur|V  qd S r   r   )rX  r  r   r   r   rZ    s    zSanic.tasks.<locals>.<genexpr>)iterr~   r~  r   r   r   r   r  x  s   zSanic.tasksc                   s|   |d dkr)t | jj| jj d| _| d t| |||| _|  I dH  dS t	
| |||I dH | _|  I dH  dS )z
        To be ASGI compliant, our instance must be a callable that accepts
        three arguments: scope, receive, send. See the ASGI reference for more
        details: https://asgi.readthedocs.io/en/latest
        typelifespanTrU  N)rD   r   is_debugr   NO_COLORr   motdr1   rn   r0   createrm   )r   scopereceiver  r   r   r   __call__  s   
zSanic.__call__Union[bytes, str, dict, Any]c                 C  s   | j | dS )a  Update the application configuration.

        This method is used to update the application configuration. It can
        accept a configuration object, a dictionary, or a path to a file that
        contains a configuration object or dictionary.

        See [Configuration](/en/guide/deployment/configuration) for details.

        Args:
            config (Union[bytes, str, dict, Any]): The configuration object,
                dictionary, or path to a configuration file.
        N)r   update_config)r   r   r   r   r   r    s   zSanic.update_configc                 C     | j jS )z(Whether the app is running in ASGI mode.r   r   r   r   r   r   r        z
Sanic.asgir   c                 C  s   || j _d S r   r  r   r   r   r   r   r     s   c                 C  r  )z)Whether the app is running in debug mode.)r   r  r   r   r   r   r    r  zSanic.debugc                 C  r  )z/Whether the app is running in auto-reload mode.)r   AUTO_RELOADr   r   r   r   r     r  zSanic.auto_reloadc                 C  s   || j _|| j_d S r   )r   r  r   r   r  r   r   r   r     s   r.   c                 C  s   | j S )zuThe application state.

        Returns:
            ApplicationState: The current state of the application.
        )r}   r   r   r   r   r     s   zSanic.state	set[Path]c                 C  r  )zThe directories that are monitored for auto-reload.

        Returns:
            Set[str]: The set of directories that are monitored for
                auto-reload.
        )r   reload_dirsr   r   r   r   r    s   zSanic.reload_dirsrd   c                 C  s.   t | dst| dd t | dstd| jS )a  Convenience property for accessing Sanic Extensions.

        This property is available if the `sanic-ext` package is installed.

        See [Sanic Extensions](/en/plugins/sanic-ext/getting-started)
            for details.

        Returns:
            Extend: The Sanic Extensions instance.

        Examples:
            A typical use case might be for registering a dependency injection.
            ```python
            app.ext.dependency(SomeObject())
            ```
        rr   T)failzSanic Extensions is not installed. You can add it to your environment using:
$ pip install sanic[ext]
or
$ pip install sanic-ext)r  r-   r   rr   r   r   r   r   ext  s   

z	Sanic.ext)
extensionsbuilt_in_extensionsr   r"  Optional[list[type[Extension]]]r#  'Optional[Union[Config, dict[str, Any]]]c                K  s2   t | dr	tdt| f|||dd| | jS )a  Extend Sanic with additional functionality using Sanic Extensions.

        This method enables you to add one or more Sanic Extensions to the
        current Sanic instance. It allows for more control over the Extend
        object, such as enabling or disabling built-in extensions or providing
        custom configuration.

        See [Sanic Extensions](/en/plugins/sanic-ext/getting-started)
            for details.

        Args:
            extensions (Optional[List[Type[Extension]]], optional): A list of
                extensions to add. Defaults to `None`, meaning only built-in
                extensions are added.
            built_in_extensions (bool, optional): Whether to enable built-in
                extensions. Defaults to `True`.
            config (Optional[Union[Config, Dict[str, Any]]], optional):
                Optional custom configuration for the extensions. Defaults
                to `None`.
            **kwargs: Additional keyword arguments that might be needed by
                specific extensions.

        Returns:
            Extend: The Sanic Extensions instance.

        Raises:
            RuntimeError: If an attempt is made to extend Sanic after Sanic
                Extensions has already been set up.

        Examples:
            A typical use case might be to add a custom extension along with
                built-in ones.
            ```python
            app.extend(
                extensions=[MyCustomExtension],
                built_in_extensions=True
            )
            ```
        rr   z:Cannot extend Sanic after Sanic Extensions has been setup.T)r"  r#  r   r   )r  r   r-   r!  )r   r"  r#  r   r  r   r   r   extend  s   
/zSanic.extendc                 C  sF   t || s	td|j}|| jv r| jstd| d|| j|< dS )a  Register a Sanic instance with the class registry.

        This method adds a Sanic application instance to the class registry,
        which is used for tracking all instances of the application. It is
        usually used internally, but can be used to register an application
        that may have otherwise been created outside of the class registry.

        Args:
            app (Sanic): The Sanic instance to be registered.

        Raises:
            SanicException: If the app is not an instance of Sanic or if the
                name of the app is already in use (unless in test mode).

        Examples:
            ```python
            Sanic.register_app(my_app)
            ```
        +Registered app must be an instance of SaniczSanic app name "z" already in use.N)r   r:   r   r   r   r  r   r   r   r   r   r   =  s   
zSanic.register_appc                 C  s2   t || s	td|j}|| jv r| j|= dS dS )a}  Unregister a Sanic instance from the class registry.

        This method removes a previously registered Sanic application instance
        from the class registry. This can be useful for cleanup purposes,
        especially in testing or when an app instance is no longer needed. But,
        it is typically used internally and should not be needed in most cases.

        Args:
            app (Sanic): The Sanic instance to be unregistered.

        Raises:
            SanicException: If the app is not an instance of Sanic.

        Examples:
            ```python
            Sanic.unregister_app(my_app)
            ```
        r'  N)r   r:   r   r   r(  r   r   r   unregister_app[  s   

zSanic.unregister_appforce_creater+  c                C  s   |du r#t | jdkrtdt | jdkrtdt| j d S z| j| W S  tyM   |dkr=| jd|d Y S |rE| | Y S td	| d
w )a  Retrieve an instantiated Sanic instance by name.

        This method is best used when needing to get access to an already
        defined application instance in another part of an app.

        .. warning::
            Be careful when using this method in the global scope as it is
            possible that the import path running will cause it to error if
            the imported global scope runs before the application instance
            is created.

            It is typically best used in a function or method that is called
            after the application instance has been created.

            ```python
            def setup_routes():
                app = Sanic.get_app()
                app.add_route(handler_1, '/route1')
                app.add_route(handler_2, '/route2')
            ```

        Args:
            name (Optional[str], optional): Name of the application instance
                to retrieve. When not specified, it will return the only
                application instance if there is only one. If not specified
                and there are multiple application instances, it will raise
                an exception. Defaults to `None`.
            force_create (bool, optional): If `True` and the named app does
                not exist, a new instance will be created. Defaults to `False`.

        Returns:
            Sanic: The requested Sanic app instance.

        Raises:
            SanicException: If there are multiple or no Sanic apps found, or
                if the specified name is not found.


        Example:
            ```python
            app1 = Sanic("app1")
            app2 = Sanic.get_app("app1")  # app2 is the same instance as app1
            ```
        Nrf  z8Multiple Sanic apps found, use Sanic.get_app("app_name")r   z#No Sanic apps have been registered.__main____mp_main__r*  zSanic app name 'z' not found.
App instantiation must occur outside if __name__ == '__main__' block or by using an AppLoader.
See https://sanic.dev/en/guide/deployment/app-loader.html for more details.)r}  r   r:   r   r~  r  get_app)r  r   r+  r   r   r   r.  v  s&   0
zSanic.get_appc                 C  s2   dd | j  D }t|dkrtd d S d S )Nc                 S  s   h | ]}|j jqS r   )r   
USE_UVLOOP)rX  r   r   r   r   	<setcomp>      z/Sanic._check_uvloop_conflict.<locals>.<setcomp>rf  zIt looks like you're running several apps with different uvloop settings. This is not supported and may lead to unintended behaviour.)r   r~  r}  rB   r   )r  r~  r   r   r   _check_uvloop_conflict  s   zSanic._check_uvloop_conflictIterator[None]c                 c  sr    | j js
dV  dS | jj}| jj}|r| j  |r | j  dV  |r/| tt| j	j
 |r7|   dS dS )a  Context manager to allow changes to the app after it has started.

        Typically, once an application has started and is running, you cannot
        make certain changes, like adding routes, middleware, or signals. This
        context manager allows you to make those changes, and then finalizes
        the app again when the context manager exits.

        Yields:
            None

        Example:
            ```python
            with app.amend():
                app.add_route(handler, '/new_route')
            ```
        N)r   
is_startedr   	finalizedr   r>  	signalizer&   r   r   TOUCHUPr@  )r   	do_routerdo_signal_routerr   r   r   r    s   


zSanic.amendc              
   C  sJ   z| j   W n ty } ztjs|W Y d}~nd}~ww |   dS )a;  Finalize the routing configuration for the Sanic application.

        This method completes the routing setup by calling the router's
        finalize method, and it also finalizes any middleware that has been
        added to the application. If the application is not in test mode,
        any finalization errors will be raised.

        Finalization consists of identifying defined routes and optimizing
        Sanic's performance to meet the application's specific needs. If
        you are manually adding routes, after Sanic has started, you will
        typically want to use the  `amend` context manager rather than
        calling this method directly.

        .. note::
            This method is usually called internally during the server setup
            process and does not typically need to be invoked manually.

        Raises:
            FinalizationError: If there is an error during the finalization
                process, and the application is not in test mode.

        Example:
            ```python
            app.finalize()
            ```
        N)r   r@  r*   rT   r   finalize_middleware)r   r  r   r   r   r@    s   zSanic.finalizeallow_fail_builtinc              
   C  sJ   || j _z| j   W dS  ty$ } ztjs|W Y d}~dS d}~ww )a  Finalize the signal handling configuration for the Sanic application.

        This method completes the signal handling setup by calling the signal
        router's finalize method. If the application is not in test mode,
        any finalization errors will be raised.

        Finalization consists of identifying defined signaliz and optimizing
        Sanic's performance to meet the application's specific needs. If
        you are manually adding signals, after Sanic has started, you will
        typically want to use the  `amend` context manager rather than
        calling this method directly.

        .. note::
            This method is usually called internally during the server setup
            process and does not typically need to be invoked manually.

        Args:
            allow_fail_builtin (bool, optional): If set to `True`, will allow
                built-in signals to fail during the finalization process.
                Defaults to `True`.

        Raises:
            FinalizationError: If there is an error during the signal
                finalization process, and the application is not in test mode.

        Example:
            ```python
            app.signalize(allow_fail_builtin=False)
            ```
        N)r   r;  r@  r*   rT   r   )r   r;  r  r   r   r   r6  	  s   zSanic.signalizec                   s   | j   t| dst|  t| dr| j  | jjr(| jj	dur(d| j_	nt
| jj	tr3d| j_	| | jj	 |   dd | jjD   fdd D }|rad|}d	| d
}t|t  | jjrr| jj	rrt|  d| j_d S )Nrr   TFc                 S  s   g | ]}|j jqS r   )r  ident)rX  r  r   r   r   
<listcomp>G	  r1  z"Sanic._startup.<locals>.<listcomp>c                   s   h | ]}  |d kr|qS )rf  )count)rX  r   r  r   r   r0  H	  r  z!Sanic._startup.<locals>.<setcomp>r   z Duplicate route names detected: a  . You should rename one or more of them explicitly by using the `name` param, or changing the implicit name derived from the class and function name. For more details, please see https://sanic.dev/en/guide/release-notes/v23.3.html#duplicated-route-names-are-no-longer-allowed)rw   r  r  r-   r!  _displayr   r  r   r7  r   r>   r6  r@  r   r%  r   r;   rT   r2  primaryr^   r   r4  )r   
duplicatesnamesmessager   r?  r   _startup6	  s4   








zSanic._startupc                 C  s   t | dr| j  dS dS )zShorthand to send an ack message to the Server Manager.

        In general, this should usually not need to be called manually.
        It is used to tell the Manager that a process is operational and
        ready to begin operation.
        r   N)r  r   ackr   r   r   r   rF  a	  s   
z	Sanic.ackservingc                 C  s&   || j _t| dr| j| dS dS )a'  Set the serving state of the application.

        This method is used to set the serving state of the application.
        It is used internally by Sanic and should not typically be called
        manually.

        Args:
            serving (bool): Whether the application is serving.
        r   N)r   
is_runningr  r   set_serving)r   rG  r   r   r   rI  k	  s   

zSanic.set_servingconcernactionOptional[AbstractEventLoop]c                   s   d| d| }|dvs|dvrt d| tjd| ddid	 |d
k}|d u r/| j}| j|d|d| |ddI d H  d S )Nzserver.r   )beforeafter)initshutdownzInvalid server event: zTriggering server events: 	verbosityrf  )r  rP  FTr  )r-  r.  r0  r,  )r:   rC   r  r   r4  )r   rJ  rK  r   r   r.  r   r   r   _server_eventy	  s&   zSanic._server_eventpassthruc                 C  s   | j | j}| |ur|jjs| jj|j_|} |r@| D ]"\}}t|tr9| D ]\}}tt	| ||| q*qt| || qt
| drJ| j  | S )a  Refresh the application instance. **This is used internally by Sanic**.

        .. warning::
            This method is intended for internal use only and should not be
            called directly.

        Args:
            passthru (Optional[Dict[str, Any]], optional): Optional dictionary
                of attributes to pass through to the new instance. Defaults to
                `None`.

        Returns:
            Sanic: The refreshed application instance.
        r   )r   r.  r   r   server_infor  r   dictsetattrr\  r  r   lock)r   rS  
registeredattrinfor  r   r   r   r   refresh	  s   


zSanic.refreshra   c                 C     t ds| jstd| jS )a?  An instance of Inspector for accessing the application's state.

        This can only be accessed from a worker process, and only if the
        inspector has been enabled.

        See [Inspector](/en/guide/deployment/inspector) for details.

        Returns:
            Inspector: An instance of Inspector.
        SANIC_WORKER_PROCESSzCan only access the inspector from the main process after main_process_start has run. For example, you most likely want to use it inside the @app.main_process_ready event listener.)r   r   r{   r:   r   r   r   r   r   	  s
   zSanic.inspectorrc   c                 C  r\  )aX  
        Property to access the WorkerManager instance.

        This property provides access to the WorkerManager object controlling
        the worker processes. It can only be accessed from the main process.

        .. note::
            Make sure to only access this property from the main process,
            as attempting to do so from a worker process will result
            in an exception.

        See [WorkerManager](/en/guide/deployment/manager) for details.

        Returns:
            WorkerManager: The manager responsible for managing
                worker processes.

        Raises:
            SanicException: If an attempt is made to access the manager
                from a worker process or if the manager is not initialized.

        Example:
            ```python
            app.manager.manage(...)
            ```
        r]  zCan only access the manager from the main process after main_process_start has run. For example, you most likely want to use it inside the @app.main_process_ready event listener.)r   r   r|   r:   r   r   r   r   manager	  s
   zSanic.manager)$r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )$r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )$r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )$r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )"r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   )r   r   r   r   r   r   r   r   )r   )r   r   r   r   r   r   r   r   )r   rS   r  r  r   r   r   r   r   )r  rL   r  r  )r   rM   )F)r  rP   r  r   r   r  )r   rN   r  r  )r   rQ   r   r\   )r   r   r)  r/  r,  r   r-  r   r0  r1  r.  r   r   r2  )r   r   r)  r/  r,  r   r-  r   r0  r6  r.  r   r   r7  )r   r   r)  r/  r,  r   r-  r   r0  r   r.  r   r   r8  )
r   r9  r:  r;  r)  r   r*  r   r   r   )r  rC  r   rD  )T)rJ  r   r   r   )rQ  rR  rM  r   rN  rS  r   rT  rO  r   rP  r   r   r   )rc  r   )r   rU   r  r  r  r   r   r   )r   rU   r   r   )r   r  )r   r  )r   rT   r   r   r   rR   )r   r   r]  r   r   r   )r   rT   r   r   r   r   )r   rT   r   r   r  r  r   r   )r  r  r   r   r]  r   r   r  )r   r   r  r1  r   r   )r   r   r  r6  r   r  )r   r   r  r   r   r  )r   r   r  r   r  r   r   r   )r   r   )Nr  )r:  r  r  r  r   r   )r   r  )r   r  r   r   )r   r   )r   r   )r   r.   )r   r  )r   rd   )r"  r$  r#  r   r   r%  r   rd   )r   rT   r   r   )r   r   r+  r   r   rT   )r   r3  )r;  r   r   r   )rG  r   r   r   )rJ  r   rK  r   r   rL  r   r   )rS  r   r   rT   )r   ra   )r   rc   )Nr  
__module____qualname____doc____touchup__	__slots__r   __annotations__r   r'   r7   r   propertyr   r   r?   r  r  r  r  r'  r(  r+  r4  r   rI  r  rQ  r  rj   ri   r  r  r  rl   rk   r  classmethodrL  staticmethodr   r  r  r  r  r  r  r  r   r  r  r  _asgi_single_callabler  r   setterr  r   r   r  r!  r&  r   r)  r.  r2  r   r  r@  r6  rE  rF  rI  rR  r[  r   r^  __classcell__r   r   r   r   rT   o   s  
 7.W")19$
8E$] G  !5"#

0/AH "&+
#"rT   )	metaclass)
__future__r   r   r   logging.configr  r   r   r   r   r   r   r   asyncio.futuresr	   collectionsr
   r   collections.abcr   r   r   r   
contextlibr   r   enumr   	functoolsr   r   inspectr   osr   pathlibr   r   	tracebackr   typesr   typingr   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   urllib.parser(   r)   sanic_routing.exceptionsr*   r+   sanic_routing.router,   sanic.application.extr-   sanic.application.stater.   r/   
sanic.asgir0   r1   sanic.base.rootr2   sanic.blueprint_groupr3   sanic.blueprintsr4   sanic.compatr5   r6   sanic.configr7   r8   sanic.exceptionsr9   r:   r;   r<   sanic.handlersr=   sanic.helpersr>   r?   
sanic.httpr@   	sanic.logrA   rB   rC   sanic.logging.setuprD   sanic.middlewarerE   rF   sanic.mixins.commandsrG   sanic.mixins.listenersrH   sanic.mixins.startuprI   sanic.mixins.staticrJ   sanic.models.ctx_typesrK   sanic.models.futuresrL   rM   rN   rO   rP   rQ   sanic.models.handler_typesrR   rS   rT   SanicVarsanic.requestrU   sanic.responserV   rW   rX   sanic.routerrY   sanic.server.websockets.implrZ   sanic.signalsr[   r\   r]   sanic.touchupr^   r_   sanic.types.shared_ctxr`   sanic.worker.inspectorra   sanic.worker.loaderrb   sanic.worker.managerrc   	sanic_extrd   sanic_ext.extensions.basere   ImportErrorr  rf   rg   r   r   r   r   <module>   s     < 


