
    9i                       d Z 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Zddl	Z	ddl
Z
ddlmZ ddlmZ ddlmZ ddlZddlZddlmZmZ ddlmZ dd	l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&m'Z'm(Z(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z;  G d d      Z<ejz                   G d d             Z> G d d      Z?y)z
Flask-Limiter Extension
    )annotationsN)defaultdict)partial)overload)RateLimitItemWindowStats)ConfigurationError)MemoryStorageStoragestorage_from_string)
STRATEGIESRateLimiter)
OrderedSet)	http_date
parse_date   )request_context)ApplicationLimitLimit	MetaLimit
RouteLimitRuntimeLimit)LimitManager)CallablePRSequencecast)MAX_BACKEND_CHECKS
ConfigVarsExemptionScopeHeaderNames)RateLimitExceeded)get_qualified_namec                      e Zd ZU dZded<   ded<   ded<   ded<   	 	 	 	 	 	 	 	 	 	 	 	 dd	Zedd
       Zedd       Zedd       Z	edd       Z
y)RequestLimitzJ
    Provides details of a rate limit within the context of a request
    r   limitstrkeyboolbreachedsharedc                    t        j                  |      | _        || _        || _         |j
                  | | _        || _        || _        d | _	        y N)
weakrefproxy	extensionr'   request_argskey_forr)   r+   r,   _window)selfr1   r'   r2   r+   r,   s         K/var/www/html/venv/lib/python3.12/site-packages/flask_limiter/_extension.py__init__zRequestLimit.__init__B   sJ     6=]]95M
( 5==,/ +/    c                J    t        t        | j                  j                        S r.   )r   r   r1   limiterr5   s    r6   r:   zRequestLimit.limiterR   s    K!7!788r8   c                    | j                   s6 | j                  j                  | j                  g| j                   | _         | j                   S r.   )r4   r:   get_window_statsr'   r2   r;   s    r6   windowzRequestLimit.windowV   s:    ||84<<88XdFWFWXDL||r8   c                8    t        | j                  d   dz         S )z/Timestamp at which the rate limit will be resetr   r   )intr>   r;   s    r6   reset_atzRequestLimit.reset_at]   s     4;;q>A%&&r8   c                     | j                   d   S )z&Quantity remaining for this rate limitr   )r>   r;   s    r6   	remainingzRequestLimit.remainingc   s     {{1~r8   N)r1   Limiterr'   r   r2   z	list[str]r+   r*   r,   r*   returnNonerE   r   )rE   r   )rE   r@   )__name__
__module____qualname____doc____annotations__r7   propertyr:   r>   rA   rC    r8   r6   r&   r&   1   s    
  
H N L00 0  	0
 0 0 
0  9 9   ' '
  r8   r&   c                      e Zd ZU dZded<    ej                  e      Zded<    ej                  e	      Z
ded<    ej                  e      Zd	ed
<   ddZy)LimiterContextNRequestLimit | Noneview_rate_limit)default_factorylist[RequestLimit]view_rate_limitszdict[RuntimeLimit, list[str]]conditional_deductionszOrderedSet[RuntimeLimit]seen_limitsc                    d | _         | j                  j                          | j                  j                          | j                  j                          y r.   )rR   rU   clearrV   rW   r;   s    r6   resetzLimiterContext.resetq   s@    ###%##))+ r8   rE   rF   )rH   rI   rJ   rR   rL   dataclassesfieldlistrU   dictrV   r   rW   rZ   rN   r8   r6   rP   rP   j   s]    +/O(/+<;+<+<T+R(R<MK<M<M^b<c9c,=K,=,=j,YK)Y!r8   rP   c                     e Zd ZdZdddddddddddddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d$dZd%dZed&d       Zdd	ddddddd
ddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'dZdd	ddddddd
dd
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d(dZ	e
ej                  ej                  z  ej                  z  d	 	 	 	 	 d)d       Ze
ej                  ej                  z  ej                  z  d	 	 	 	 	 d*d       Ze
ej                  ej                  z  ej                  z  d	 	 	 d+d       Z	 d,ej                  ej                  z  ej                  z  d	 	 	 	 	 d-dZd.dZd/dZd0dZd1dZed2d       Zed3d       Zed4d       Zed5d       Zd6dZd7dZd8dZ	 	 	 	 d9dZ	 d:	 	 	 	 	 	 	 	 	 d;d Zd<d!Z	 d=	 	 	 	 	 d>d"Zd,d?d#Zy)@rD   a~  
    The :class:`Limiter` class initializes the Flask-Limiter extension.

    :param key_func: a callable that returns the domain to rate limit by.
    :param app: :class:`flask.Flask` instance to initialize the extension with.
    :param default_limits: a list of strings, callables returning strings denoting default limits
     or :class:`Limit` instances to apply to all routes that are not explicitely decorated with a
     limit. :ref:`ratelimit-string` for  more details.
    :param default_limits_per_method: whether default limits are applied per method, per route or
     as a combination of all method per route.
    :param default_limits_exempt_when: a function that should return True/False to decide if the
     default limits should be skipped
    :param default_limits_deduct_when: a function that receives the current :class:`flask.Response`
     object and returns True/False to decide  if a deduction should be made from the default rate
     limit(s)
    :param default_limits_cost: The cost of a hit to the default limits as an integer or a function
     that takes no parameters and returns an integer (Default: ``1``).
    :param application_limits: a list of strings, callables returning strings for limits or
     :class:`ApplicationLimit` that are applied to  the entire application
     (i.e a shared limit for all routes)
    :param application_limits_per_method: whether application limits are applied per method, per
     route or as a combination of all method per route.
    :param application_limits_exempt_when: a function that should return True/False to decide if the
     application limits should be skipped
    :param application_limits_deduct_when: a function that receives the current
     :class:`flask.Response` object and returns True/False to decide  if a deduction should be made
     from the application rate limit(s)
    :param application_limits_cost: The cost of a hit to the global application limits as an integer
     or a function that takes no parameters and returns an integer (Default: ``1``).
    :param headers_enabled: whether ``X-RateLimit`` response headers are written.
    :param header_name_mapping: Mapping of header names to use if :paramref:`Limiter.headers_enabled`
     is ``True``. If no mapping is provided the default values will be used.
    :param strategy: the strategy to use. Refer to :ref:`ratelimit-strategy`
    :param storage_uri: the storage location. Refer to :data:`RATELIMIT_STORAGE_URI`
    :param storage_options: kwargs to pass to the storage implementation upon instantiation.
    :param swallow_errors: whether to swallow any errors when hitting a rate limit. An exception
     will still be logged. default ``False``
    :param fail_on_first_breach: whether to stop processing remaining limits after the first breach.
     default ``True``
    :param on_breach: a function that will be called when any limit in this extension is breached.
     If the function returns an instance of :class:`flask.Response` that will be the response
     embedded into the :exc:`RateLimitExceeded` exception raised.
    :param meta_limits: a list of strings, callables returning strings for limits or
     :class:`MetaLimit` that are used to control the upper limit of  a requesting client hitting
     any configured rate limit. Once a meta limit is exceeded all subsequent requests will
     raise a :class:`~flask_limiter.RateLimitExceeded` for the duration of the meta limit window.
    :param on_meta_breach: a function that will be called when a meta limit in this extension is
     breached. If the function returns an instance of :class:`flask.Response` that will be the
     response embedded into the :exc:`RateLimitExceeded` exception raised.
    :param in_memory_fallback: a list of strings or callables returning strings denoting fallback
     limits to apply when the storage is down.
    :param in_memory_fallback_enabled: fall back to in memory storage when the main storage is down
     and inherits the original limits. default ``False``
    :param retry_after: Allows configuration of how the value of the `Retry-After` header is
     rendered. One of `http-date` or `delta-seconds`.
    :param key_prefix: prefix prepended to rate limiter keys and app context global names.
    :param request_identifier: a callable that returns the unique identity the current request.
     Defaults to :attr:`flask.Request.endpoint`
    :param enabled: Whether the extension is enabled or not
    N T)appdefault_limitsdefault_limits_per_methoddefault_limits_exempt_whendefault_limits_deduct_whendefault_limits_costapplication_limitsapplication_limits_per_methodapplication_limits_exempt_whenapplication_limits_deduct_whenapplication_limits_costheaders_enabledheader_name_mappingstrategystorage_uristorage_optionsswallow_errorsfail_on_first_breach	on_breachmeta_limitson_meta_breachin_memory_fallbackin_memory_fallback_enabledretry_after
key_prefixrequest_identifierenabledc                  || _         t        j                  d      | _        || _        d| _        || _        || _        || _        || _	        |	| _
        |
| _        || _        || _        g | _        |xs |xr t        |      dkD  | _        i | _        i | _        g | _        || _        |xs i | _        || _        || _        || _        |xs i | _        || _        || _        || _        || _        || _        || _        || _         |rV|D cg c]J  }tC        |tD              s'tE        || j<                  d      jG                  |       n|jG                  |       L c}ng }|rK|D cg c]?  }tC        |tD              stI        |d      jG                  |       n|jG                  |       A c}ng }|rJ|D cg c]>  }tC        |tD              stK        |      jG                  |       n|jG                  |       @ c}ng | _&        |rI|D ]D  }| j                  jO                  tC        |tD              stE        || j<                        n|       F d | _(        d | _)        d| _*        d | _+        d| _,        t[        jZ                         | _.        t_               | _0        | j                  jc                  t        jd                                tg        ||i i | j"                  | j$                        | _4        |r| jk                  |       y y c c}w c c}w c c}w )	Nzflask-limiterFr   )limit_providerkey_function	finalized)r~   r   )r~   r~   r   )rh   rc   decorated_limitsblueprint_limitsroute_exemptionsblueprint_exemptions)6rb   logging	getLoggerloggerr|   initialized_default_limits_per_method_default_limits_exempt_when_default_limits_deduct_when_default_limits_cost_application_limits_per_method_application_limits_exempt_when_application_limits_deduct_when_application_limits_cost_in_memory_fallbacklen_in_memory_fallback_enabled_route_exemptions_blueprint_exemptions_request_filters_headers_enabled_header_mapping_retry_after	_strategy_storage_uri_storage_options_swallow_errors_fail_on_first_breach
_on_breach_on_meta_breach	_key_func_key_prefix_request_identifier
isinstancer   bindr   r   _meta_limitsappend_storage_limiter_storage_dead_fallback_limiter_Limiter__check_backend_counttime_Limiter__last_check_backendset_marked_for_limiting
addHandlerNullHandlerr   limit_managerinit_app) r5   key_funcrb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r'   _default_limits_application_limitss                                    r6   r7   zLimiter.__init__   s3   @ ''8 *C'+E(+E($7!.K+/M,/M,(?%#% +E ,
>3'9#:Q#> 	( =?@B":< /28b'!' / 52-%9"#-!%#5   ,	  "%/ #(!%# $t*ZZ%&	  	2 " 0  "%/	 !#(# $t*ZZ%&  	.  )  "%/ #($t*ZZ%	&  	 + ((//
 &eU3	 ',%)^^
  )-,0"59%&"$(IIK!.1e!w2245)2*!33!%!;!;
 MM# Q	s   AL "AL1AL
c                b   |j                   }|j                  t        j                  | j                        | _        | j                  sy| j
                  .t        |j                  t        j                  d            | _        | j                  xs |j                  t        j                        | _	        | j                  xs |j                  t        j                        | _        | j                  xs  |j                  t        j                  d      | _        | j                  .t        |j                  t        j                   d            | _        | j"                  .t        |j                  t        j$                  d            | _        | j&                  .t        |j                  t        j(                  d            | _        | j*                  j-                  |j                  t        j.                  i              |j                  t        j0                  d      }|s#| j2                  st5        j6                  d       d}t9        t:        t=        | j2                  xs |fi | j*                        | _        | j@                  xs  |j                  t        jB                  d      | _         | j@                  tD        vrtG        d| j@                  z        tE        | j@                     | j>                        | _$        tJ        jL                  | jN                  j                  tJ        jL                  |j                  t        jP                  tJ        jL                  jR                              tJ        jT                  | jN                  j                  tJ        jT                  |j                  t        jV                  tJ        jT                  jR                              tJ        jX                  | jN                  j                  tJ        jX                  |j                  t        jZ                  tJ        jX                  jR                              tJ        j\                  | jN                  j                  tJ        j\                  |j                  t        j^                  tJ        j\                  jR                              i| _'        | j`                  xs |j                  t        jb                        | _0        | jd                  xs  |j                  t        jf                  d	      | _2        | jh                  xs! |j                  t        jj                  d
       | _4        |j                  t        jl                  d      }| jn                  xs  |j                  t        jp                  d      | _7        | jr                  .t        |j                  t        jt                  d            | _9        | jv                  xs |j                  t        jx                        | _;        | jz                  xs |j                  t        j|                        | _=        | j~                  j                  sd|rb| j~                  j                  t        || jr                  | jv                  | jz                  | jn                        j                  |       g       n| j~                  j                  }|D ]Z  }|j                  r| jn                  |_E        | jr                  |_F        | jv                  |_G        | jz                  |_H        d|_D        \ | j~                  j                  |       |j                  t        j                  d      }| j~                  j                  so|rm| j~                  j                  t        || j                  | j
                  | j                  | j                  | j                        j                  |       g       n| j~                  j                  }|D ]Z  }|j                  r| j                  |_E        | j
                  |_F        | j                  |_G        | j                  |_H        d|_D        \ | j~                  j                  |       |j                  t        j                  d      }	| j                  sO|	rMt        |	t              s&t        |	| j                        j                  |       n|	j                  |       g| _O        | j                  xs  |j                  t        j                  d      | _R        | j                  xs  |j                  t        j                  d      | _T        | j                  || j@                         | |j                  j                  dt                     vr_|j                  | j                         |j                  t        t        j                  |              |j                  | j                         |j                  d   j                  |        d| _b        y)zJ
        :param app: :class:`flask.Flask` instance to rate limit.
        NFr   Ta	  Using the in-memory storage for tracking rate limits as no storage was explicitly specified. This is not recommended for production use. See: https://flask-limiter.readthedocs.io#configuring-a-storage-backend for documentation about configuring the storage backend.z	memory://zfixed-windowz!Invalid rate limiting strategy %sra   c                 >    t         j                  j                  xs dS )Nra   )flaskrequestendpointrN   r8   r6   <lambda>z"Limiter.init_app.<locals>.<lambda>  s    5==3I3I3OR r8   )r~   
per_methodexempt_whendeduct_whencost)r~   r   r   r   r   r   r   r:   )cconfig
setdefaultr    ENABLEDr|   r   r*   getDEFAULT_LIMITS_PER_METHODr   DEFAULT_LIMITS_EXEMPT_WHENr   DEFAULT_LIMITS_DEDUCT_WHENr   DEFAULT_LIMITS_COSTr   SWALLOW_ERRORSr   FAIL_ON_FIRST_BREACHr   HEADERS_ENABLEDr   updateSTORAGE_OPTIONSSTORAGE_URIr   warningswarnr   r   r   r   r   STRATEGYr   r	   r   r"   RESETr   HEADER_RESETvalue	REMAININGHEADER_REMAININGLIMITHEADER_LIMITRETRY_AFTERHEADER_RETRY_AFTERr   HEADER_RETRY_AFTER_VALUEr   
KEY_PREFIXr   REQUEST_IDENTIFIERAPPLICATION_LIMITSr   APPLICATION_LIMITS_COSTr   APPLICATION_LIMITS_PER_METHODr   APPLICATION_LIMITS_EXEMPT_WHENr   APPLICATION_LIMITS_DEDUCT_WHENr   r   set_application_limitsr   r   r   r   r   r   r   DEFAULT_LIMITSr   set_default_limitsr   r   META_LIMITSr   r   r   r   	ON_BREACHr   ON_META_BREACH_Limiter__configure_fallbacks
extensionsr   before_request_check_request_limitafter_requestr   rD   _Limiter__inject_headersteardown_request_Limiter__release_contextaddr   )
r5   rb   r   storage_uri_from_config
app_limitsgroupconf_limitsdefault_limit_groupsdefault_groupru   s
             r6   r   zLimiter.init_appF  s    ((););T\\J||**2.2

:??G/D+ ,0+K+K ,
vzz11P
( ,0+K+K ,
vzz11P
( %)$=$= %
**AB
! '#'

:3L3Le(T#UD %%-)-fjj9X9XZ^._)`D&  ($(J4N4NPU)V$WD!$$VZZ
0J0JB%OP"(**Z-C-CT"J&$$O '2#!!<%<@D@U@U
 a6+<+<Z=P=PR`+a>>+$%H4>>%YZZ"4>>24==A t3377!!

:22K4E4E4K4KL  !!4#7#7#;#;%%

:668M8M8S8ST$ t3377!!

:22K4E4E4K4KL  ##T%9%9%=%=''

:88+:Q:Q:W:WX& 
$ !--`J<_<_1`++Tvzz*:O:OQS/T#'#;#; $
vzz))+O@
  ZZ
 = =tD
(,(E(E )
..J
% ..626

:CCUK3D/ 04/S/S 0
W]WaWa55X
, 04/S/S 0
W]WaWa55X
, !!55*55$'1#'#F#F$($H$H$($H$H!:: d4j
 ++??J# +!%!>!>EJ'+'J'JE$(,(L(LE%(,(L(LE%&*EO+ 55jAjj!:!:DA!!11k11'2%)^^#'#B#B$($D$D$($D$D!66 d4j	 $(#5#5#E#E !5 3$..)-)B)BM&/3/N/NM,040P0PM-040P0PM-.2M+3 112FGjj!7!7>  [ "+y9	 #.!% $t* %%d+!D //SVZZ
8L8Ld-S#33bvzz*B[B[]a7b""37s~~00CEBBt889gg&>&>EF  !7!78y!%%d+r8   c                    t               }t        |d      st        t              |_        t        t        t        t        f   |j                        |    S )aE  
        The context is meant to exist for the lifetime of a request/response cycle per instance of
        the extension so as to keep track of any state used at different steps in the lifecycle
        (for example to pass information from the before request hook to the after_request hook)

        :meta private:
        _limiter_request_context)r   hasattrr   rP   r   r   r_   rD   )r5   ctxs     r6   contextzLimiter.context  sQ     s67+6~+FC(.()((
  	r8   Fr   )r   r   methodserror_messager   override_defaultsr   rt   r   scoperu   c               P    t        || |xs | j                  d||||||||	|
|      S )a	  
        Decorator to be used for rate limiting individual routes or blueprints.

        :param limit_value: rate limit string or a callable that returns a string.
         :ref:`ratelimit-string` for more details.
        :param key_func: function/lambda to extract the unique identifier for the rate limit.
        :param per_method: whether the limit is sub categorized into the http method of the request.
        :param methods: if specified, only the methods in this list will be rate limited
         (default: ``None``).
        :param error_message: string (or callable that returns one) to override the error message
         used in the response.
        :param exempt_when: function/lambda used to decide if the rate limit should skipped.
        :param override_defaults:  whether the decorated limit overrides the default limits
         (Default: ``True``).

         .. note:: When used with a :class:`~flask.Blueprint` the meaning
            of the parameter extends to any parents the blueprint instance is
            registered under. For more details see :ref:`recipes:nested blueprints`

        :param deduct_when: a function that receives the current :class:`flask.Response` object and
         returns True/False to decide if a deduction should be done from the rate limit
        :param on_breach: a function that will be called when this limit is breached. If the
         function returns an instance of :class:`flask.Response` that will be the response embedded
         into the :exc:`RateLimitExceeded` exception raised.
        :param cost: The cost of a hit or a function that takes no parameters and returns the cost
         as an integer (Default: ``1``).
        :param scope: a string or callable that returns a string for further categorizing the rate
         limiting scope. This scope is combined with the current endpoint of the request.


        Changes
          - .. versionadded:: 2.9.0

               The returned object can also be used as a context manager
               for rate limiting a code block inside a view. For example::

                 @app.route("/")
                 def route():
                   try:
                     with limiter.limit("10/second"):
                       # something expensive
                   except RateLimitExceeded: pass

        Fr~   r:   r   r,   r  r   r   r   r   r  r   rt   r   ru   r   r   )r5   limit_valuer   r   r   r   r   r  r   rt   r   r  ru   s                r6   r'   zLimiter.limit  sE    z &!3T^^!'#/##
 	
r8   )
r   r   r   r   r   r  r   rt   r   ru   c       
        P    t        || |xs | j                  d|||||||	|
||      S )a  
        decorator to be applied to multiple routes sharing the same rate limit.

        :param limit_value: rate limit string or a callable that returns a string.
         :ref:`ratelimit-string` for more details.
        :param scope: a string or callable that returns a string for defining the rate limiting scope.
        :param key_func: function/lambda to extract the unique identifier for the rate limit.
        :param per_method: whether the limit is sub categorized into the http method of the request.
        :param methods: if specified, only the methods in this list will be rate limited
         (default: ``None``).
        :param error_message: string (or callable that returns one) to override the error message
         used in the response.
        :param function exempt_when: function/lambda used to decide if the rate limit should skipped.
        :param override_defaults: whether the decorated limit overrides the default limits.
         (default: ``True``)

         .. note:: When used with a :class:`~flask.Blueprint` the meaning
            of the parameter extends to any parents the blueprint instance is
            registered under. For more details see :ref:`recipes:nested blueprints`
        :param deduct_when: a function that receives the current :class:`flask.Response` object and
         returns True/False to decide if a deduction should be done from the rate limit
        :param on_breach: a function that will be called when this limit is breached.
         If the function returns an instance of :class:`flask.Response` that will be the response
         embedded into the :exc:`RateLimitExceeded` exception raised.
        :param cost: The cost of a hit or a function that takes no parameters and returns the cost
         as an integer (default: ``1``).
        Tr  r  )r5   r  r  r   r   r   r   r   r  r   rt   r   ru   s                r6   shared_limitzLimiter.shared_limitS  sE    X &!3T^^!'#/##
 	
r8   flagsc                    y r.   rN   r5   objr
  s      r6   exemptzLimiter.exempt  s     r8   c                    y r.   rN   r  s      r6   r  zLimiter.exempt  s     r8   c                    y r.   rN   )r5   r
  s     r6   r  zLimiter.exempt  s     r8   c                  t        |t        j                        r(| j                  j	                  |j
                  |       |S |r'| j                  j                  t        |      |       |S t        j                  | j                  |      S )a  
        Mark a view function or all views in a blueprint as exempt from rate limits.

        :param obj: view function or blueprint to mark as exempt.
        :param flags: Controls the scope of the exemption. By default application wide limits,
         defaults configured on the extension and meta limits are opted out of. Additional flags
         can be used to control the behavior when :paramref:`obj` is a Blueprint that is nested
         under another Blueprint or has other Blueprints nested under it
         (See :ref:`recipes:nested blueprints`)

        The method can be used either as a decorator without any arguments (the default
        flags will apply and the route will be exempt from default and application limits::

            @app.route("...")
            @limiter.exempt
            def route(...):
               ...

        Specific exemption flags can be provided at decoration time::

            @app.route("...")
            @limiter.exempt(flags=ExemptionScope.APPLICATION)
            def route(...):
                ...

        If an entire blueprint (i.e. all routes under it) are to be exempted the method can be
        called with the blueprint as the first parameter and any additional flags::

            bp = Blueprint(...)
            limiter.exempt(bp)
            limiter.exempt(
                bp,
                flags=ExemptionScope.DEFAULT|ExemptionScope.APPLICATION|ExemptionScope.ANCESTORS
            )

        r	  )r   r   	Blueprintr   add_blueprint_exemptionnameadd_route_exemptionr$   	functoolsr   r  r  s      r6   r  zLimiter.exempt  su    d c5??+66sxxG 
 223Ec3JER 
 $$T[[>>r8   c                <    | j                   j                  |       |S )a  
        Decorator to mark a function as a filter to be executed to check if the request is exempt
        from rate limiting.

        :param fn: The function will be called before evaluating any rate limits to decide whether
         to perform rate limit or skip it.
        )r   r   )r5   fns     r6   request_filterzLimiter.request_filter  s     	$$R(	r8   c                   |j                   }|j                  t        j                  d      }|j                  t        j                  d       }| j
                  s1|r/t        || j                  d dd      j                  |       g| _        | j                  s!|xs t        | j
                        dkD  | _	        | j                  r-t               | _        t        |   | j                        | _        y y )NFr   )r~   r   r  r   r   r   )r   r   r    IN_MEMORY_FALLBACK_ENABLEDIN_MEMORY_FALLBACKr   r   r   r   r   r   r
   _fallback_storager   r   )r5   rb   ro   r   fallback_enabledfallback_limitss         r6   __configure_fallbackszLimiter.__configure_fallbacks  s    !::j&K&KUS **Z%B%BDI''O#2!%$ $t*(D$ ///?/d3tG_G_C`cdCdD,++%2_D"%/%9$:P:P%QD" ,r8   c                   | j                   t        kD  rd| _         t        j                         | j                  z
  t	        d| j                         kD  r/t        j                         | _        | xj                   dz  c_         yy)Nr      r   TF)r   r   r   r   powr;   s    r6   __should_check_backendzLimiter.__should_check_backend  sd    %%(::)*D&99;222SD<V<V5WW(,		D%&&!+&r8   c                    	 | j                   j                          | j                  j                  d       y# t        $ r | j                  j                  d       Y yw xY w)z?
        resets the storage if it supports being reset
        z-Storage has been reset and all limits clearedz.This storage type does not support being resetN)storagerZ   r   infoNotImplementedErrorwarningr;   s    r6   rZ   zLimiter.reset  sO    	RLL KKLM" 	RKK PQ	Rs   58 $AAc                6    | j                   sJ | j                   S )zE
        The backend storage configured for the rate limiter
        )r   r;   s    r6   r&  zLimiter.storage#  s    
 }}}}}r8   c                p    | j                   r| j                  r| j                  }n| j                  }|sJ |S )z[
        Instance of the rate limiting strategy used for performing rate limiting.
        )r   r   r   r   )r5   r:   s     r6   r:   zLimiter.limiter,  s5     $"B"B,,GmmGwr8   c                .    | j                   j                  S )aF  
        Get details for the most relevant rate limit used in this request.

        In a scenario where multiple rate limits are active for a single request and none are
        breached, the rate limit which applies to the smallest time window will be returned.

        .. important:: The value of ``remaining`` in :class:`RequestLimit` is after
           deduction for the current request.


        For example::

            @limit("1/second")
            @limit("60/minute")
            @limit("2/day")
            def route(...):
                ...

        - Request 1 at ``t=0`` (no breach): this will return the details for for ``1/second``
        - Request 2 at ``t=1`` (no breach): it will still return the details for ``1/second``
        - Request 3 at ``t=2`` (breach): it will return the details for ``2/day``
        )r   rR   r;   s    r6   current_limitzLimiter.current_limit:  s    2 ||+++r8   c                .    | j                   j                  S )z
        Get a list of all rate limits that were applicable and evaluated
        within the context of this request.

        The limits are returned in a sorted order by smallest window size first.
        )r   rU   r;   s    r6   current_limitszLimiter.current_limitsU  s     ||,,,r8   c                p    | j                   r*| j                  r| j                  sJ | j                         S y)aT  
        Returns the identity of the request (by default this is the :attr:`flask.Request.endpoint`
        associated by the view function that is handling the request). The behavior can be customized
        by initializing the extension with a callable argument for
        :paramref:`~flask_limiter.Limiter.request_identifier`.
        ra   )r   r|   r   r;   s    r6   identify_requestzLimiter.identify_request`  s4     ++++++--r8   c                   | j                   j                  j                         D ]Y  \  }}|j                  s|j                  |      s%	  | j                  j
                  |j                  g|d|j                  i [ y # t        $ r4}| j                  r| j                  j                  d       n|Y d }~d }~ww xY w)Nr   z-Failed to deduct rate limit. Swallowing error)r   rV   itemsr   r:   hitr'   deduction_amount	Exceptionr   r   	exception)r5   responselimargserrs        r6   __check_conditional_deductionsz&Limiter.__check_conditional_deductionso  s    <<BBD 	"IC3??8#<"$DLL$$SYYQQC<P<PQ	" ! "++--.]^!	 _"s   4B	B?*B::B?c           
        | j                  |       | j                  }| j                  r| j                  r|r| j                  r	 |j
                  }|j                  j                  | j                  t        j                     t        |j                  j                               |j                  j                  | j                  t        j                     t        |j                               |j                  j                  | j                  t        j                     t        |             |j                  j!                  d      }|t#        |      }| t%        j$                         t'        |      z   }t)        |t*        j*                        r#t%        j,                  |j/                               }t1        t'        |      |      }|j                  j3                  | j                  t        j4                     t        | j6                  dk(  rt9        |      nt'        |t%        j$                         z
                     |S |S # t:        $ r}| j<                  r@| j>                  s4| j@                  jC                  d       d| _        | jE                  |      }n*| jF                  r| j@                  jI                  d       n|Y d }~|S d }~ww xY w)NzRetry-Afterz	http-dateBRate limit storage unreachable - falling back to in-memory storageTz5Failed to update rate limit headers. Swallowing error)%&_Limiter__check_conditional_deductionsr-  r|   r   r   rA   headersr   r"   r   r(   r'   amountr   rC   r   r   r   r   r@   r   datetimemktime	timetuplemaxr   r   r   r   r6  r   r   r   r)  r   r   r7  )r5   r8  header_limitrA   existing_retry_after_headerry   es          r6   __inject_headerszLimiter.__inject_headersz  sN   ++H5))<<D11ltG[G[5 '00  $$(():):;**112   $$(()>)>?../   $$T%9%9+:K:K%LcRZm\ /7.>.>.B.B=.Q+.:DN3EK #*&*iikC8S4T&T!+x/@/@A&*kk+2G2G2I&J"3{#3X>H   $$(()@)@A,,; "(+ DIIK!78. x   33D<N<NKK''\ *.D&#44X>H++--S   s   	G>I 	KA6KKc                    t        | xsR | j                  xr | j                   xs5 |j                  d      d   dk(  xs t	        d | j
                  D                    S )N.staticc              3  *   K   | ]  } |         y wr.   rN   ).0r  s     r6   	<genexpr>z4Limiter.__check_all_limits_exempt.<locals>.<genexpr>  s     8B248s   )r*   r|   r   splitanyr   )r5   r   s     r6   __check_all_limits_exemptz!Limiter.__check_all_limits_exempt  sf     L 9LL5T%5%569~~c"2&(29 8$"7"788	
 	
r8   c                   |r|}n=t         j                  j                  j                  |xs dd       }|rt	        |      nd}| j                  |      rg S || j                  v xs | j                  j                  |xs d      }g }| j                  r| j                  r|r|| j                  v rn| j                         rP| j                  rD| j                  j                         r*| j                  j                  d       d| _	        d| _        n%t#        t%        j&                  | j(                         }|r|S | j                  j+                  t         j                  |||||      \  }	}
t-        |	      | j.                  j0                  z
  }| j.                  j0                  j3                  |	       t#        |      t#        |
      z   S )Nra   zRate limit storage recoveredFr   )r   current_appview_functionsr   r$   !_Limiter__check_all_limits_exemptr   r   	has_hintsr   r   _Limiter__should_check_backendr   checkr   r'  r   r^   	itertoolschainr   resolve_limitsr   r   rW   r   )r5   r   	blueprintcallable_namein_middlewarer  	view_funcmarked_for_limitingr  defaults	decoratedlimitss               r6   __filter_limitszLimiter.__filter_limits  s     D))88<<X^TRI4=%i02D))(3I"d&?&?? 
4CUCUC_C_ND
 $"8"8)B)B!B..0T]]t}}GZGZG\KK$$%CD).D&12D.&*9??D<T<T+U&VO"""00??
) H%(@(@@  ''1F|d9o--r8   c           
        g }d }g }t        j                  g | j                  |D cg c]  }|j                  s|j                   c} D cg c]  }|j                  s| }}t
        j                  | j                  j                  t        j                  |t        j                  j                        z  s|D ]  }	|	j                         |	j                  |d       }}
|
|g}|	j                  xs | j                   } | j"                  j$                  |	j&                  g|d|	j(                  irxt+        | |	j&                  |d|	j,                        }|| j.                  _        |g| j.                  _        d }|r/	  ||      }t5        |t        j6                  j8                        r|}tC        |	|       tE        |d       D ]  }	|	j                  s|	jF                  r|	j                  |t        j                  jH                        }|	j                         }
|
|g}i }tK        |      s*| j>                  jM                  d|	j&                   d       | jN                  r| jN                  g|}|	jP                  r0|| j.                  jR                  |	<   | j"                  j$                  }n| j"                  jT                  }|	j(                  |d<   t+        | |	j&                  |d	|	j,                        }|jW                  |        ||	j&                  g|i |rZ| j>                  jY                  d
|	j&                  |
|       |jW                  |	|f       d|d   _-        |d   }| j\                  s n |s*|r(|D cg c]  }|j,                  r| }}|r|d   n|d   }|xs d | j.                  _        || j.                  _        d }|D ]  }t+        | |d   j&                  |d   d|d   j,                        }t^        ja                  | jb                  |d   j                  g      D ]4  }|s	  ||      }t5        |t        j6                  j8                        r|}6  |rt        j                  g | j                  |D 	cg c]*  }	|	d   j                  ste        |	d   j                        , c}	 D cg c]  }|j                  s| }}|D ]g  }	|	j                  |t        j                  jH                        }|	j                         }
|
|g} | j"                  jT                  |	j&                  g|  i tC        tE        |d       d   d   |      y c c}w c c}w # t:        $ r6}| j<                  r| j>                  jA                  d|       n|Y d }~d }~ww xY wc c}w # t:        $ r6}| j<                  r| j>                  jA                  d|       n|Y d }~d }~ww xY wc c}	w c c}w )Nr   Tz,on_meta_breach callback failed with error %s)r8  c                    | j                   S r.   r'   xs    r6   r   z+Limiter.__evaluate_limits.<locals>.<lambda>  s
     r8   )r)   zSkipping limit: z". Empty value found in parameters.Fz*ratelimit %s (%s) exceeded at endpoint: %srL  r   r   z'on_breach callback failed with error %sc                     | d   j                   S )Nr   ri  rj  s    r6   r   z+Limiter.__evaluate_limits.<locals>.<lambda>r  s    AaDJJ r8   )3r[  r\  r   ru   	is_exemptr!   METAr   exemption_scoper   rU  r   r^  r   	scope_forrt   r   r:   testr'   r5  r&   r,   r   rR   rU   r   wrappersResponser6  r   r   r7  r#   sortedmethod_exemptmethodallerrorr   r   rV   r4  r   r'  r+   r   r_   fromkeysr   r^   )r5   r   re  failed_limitslimit_for_headerview_limitsr'   
meta_limitru   r9  	limit_keyr  r:  rt   breached_meta_limitmeta_breach_responsecb_responser;  limit_scopekwargsrv  request_limitexpliciton_breach_responsecbs                            r6   __evaluate_limitszLimiter.__evaluate_limits  s   >@04*, (oo ""17M5;L;L%##M
 '' 
 
   00!!8U]]-D-D
 # P#&<<>3==43P5	!5)MMAT-A-A	(t||((UTU@T@TU*6tSYYdTWT^T^*_'3FDLL05H4IDLL1+/( **34G*HK)+u~~7N7NO7B 4 ,C:NOO/P2 &&78 '	C}} 1 1--%--2F2FGKI{+DFt9!!$4SYYK?a"bc((040;?33C8**)) 11F6N(syy$szzRM}-#))5d5f5  @II	 $$c4[1+/B(#.r? --O'	R  K ,7K%ellKHK.6x{KN'7'?4$(3%!" 	&E(uQx~~uQxuUVx_MmmT__eAh6H6H$IJ &	&&(&7%k5>>3J3JK1<.&	&   #,// #&&#:G^33q6K]K]d3q6--.^# "++ K  # 3!mmHemm6J6JKLLN	!;/   2T2	3
 $}*>?B1E+  Q N	
<  ) *#33 $ 5 5$RTW!" '*		!"*l L$ % &// KK112[]`a"%I b& _	s^   U'
U'
U, .U1V3V39.V8W:
"W:
W?1	V0:+V++V08	W7+W22W7c                4   | j                         }	 | j                  |t        j                  j                  ||      }| j                  ||       y # t        $ r}t        |t              r|| j                  rf| j                  sZ| j                  j                  d       d| _
        | j                  j                  j                          | j!                  ||       n/| j"                  r| j                  j%                  d       n|Y d }~y Y d }~y d }~ww xY w)Nr>  T)r_  r`  z&Failed to rate limit. Swallowing error)r1  _Limiter__filter_limitsr   r   r^  _Limiter__evaluate_limitsr6  r   r#   r   r   r   r)  r   rW   rY   r   r   r7  )r5   r_  r`  r   
all_limitsrH  s         r6   r   zLimiter._check_request_limitv  s     ((*	--''	J ""8Z8 	!.///8J8J##X &*"((..0))Ub)c''KK))*RSG T d	s   >A 	DB.DDc                8    | j                   j                          y r.   )r   rZ   )r5   _s     r6   __release_contextzLimiter.__release_context  s    r8   ):r   zCallable[[], str]rb   zflask.Flask | Nonerc   z,list[str | Callable[[], str] | Limit] | Nonerd   bool | Nonere   Callable[[], bool] | Nonerf   0Callable[[flask.wrappers.Response], bool] | Nonerg   int | Callable[[], int] | Nonerh   z7list[str | Callable[[], str] | ApplicationLimit] | Noneri   r  rj   r  rk   r  rl   r  rm   r  rn   zdict[HeaderNames, str] | Nonero   
str | Nonerp   r  rq   zdict[str, str | int] | Nonerr   r  rs   r  rt   ?Callable[[RequestLimit], flask.wrappers.Response | None] | Noneru   z0list[str | Callable[[], str] | MetaLimit] | Nonerv   r  rw   list[str] | Nonerx   r  ry   r  rz   r(   r{   zCallable[..., str] | Noner|   r*   rE   rF   )rb   flask.FlaskrE   rF   )rE   rP   )r  str | Callable[[], str]r   Callable[[], str] | Noner   r*   r   r  r   str | Callable[[], str] | Noner   r  r  r*   r   r  rt   ?None | Callable[[RequestLimit], flask.wrappers.Response | None]r   int | Callable[[], int]r  z!str | Callable[[str], str] | Noneru   4Sequence[str | Callable[[], str] | MetaLimit] | NonerE   r   )r  r  r  zstr | Callable[[str], str]r   r  r   r*   r   r  r   r  r   r  r  r*   r   r  rt   r  r   r  ru   r  rE   r   )r  flask.Blueprintr
  r!   rE   r  )r  Callable[..., R]r
  r!   rE   r  )r
  r!   rE   zYCallable[[Callable[P, R]], Callable[P, R]] | Callable[[flask.Blueprint], flask.Blueprint]r.   )r  z)Callable[..., R] | flask.Blueprint | Noner
  r!   rE   z~Callable[..., R] | flask.Blueprint | Callable[[Callable[P, R]], Callable[P, R]] | Callable[[flask.Blueprint], flask.Blueprint])r  Callable[[], bool]rE   r  )rb   r  ro   r(   rE   rF   )rE   r*   r[   )rE   r   rG   )rE   rQ   )rE   rT   )rE   r(   )r8  flask.wrappers.ResponserE   rF   )r8  r  rE   r  )r   r  rE   r*   )F)
r   r  r^  r  r_  r  r`  r*   rE   list[RuntimeLimit])r   r(   re  r  rE   rF   )NT)r_  r  r`  r*   rE   rF   )r  zBaseException | NonerE   rF   ) rH   rI   rJ   rK   r7   r   rM   r   r'   r  r   r!   APPLICATIONDEFAULTrn  r  r  r   rY  rZ   r&  r:   r-  r/  r1  r?  r   rW  r  r  r   r   rN   r8   r6   rD   rD   x   so   ;B #'GK15@DW[>BVZ59DH[_BF'+=A#"&7;&*,0UYHLZ^/326"&8<=N#N  	N
 EN $/N %>N %UN <N TN (3N )BN )YN "@N %N  ;!N" #N$  %N& 5'N( $)N* *+N, S-N. F/N0 X1N2 -3N4 %05N6  7N8 9N: 6;N< =N> 
?N`j X  , .2 $(8<15"&HLW[()37LPL
,L
 +	L

 L
 "L
 6L
 /L
  L
 FL
 UL
 &L
 1L
 JL
 
L
f .2 $(8<15"&HLW[()LP;
,;
 *;

 +;
 ;
 ";
 6;
 /;
  ;
 F;
 U;
 &;
 J;
 
;
z 
 !/ : :

 
 !!


!	 	 
  
 !/ : :

 
 !!


!	 	 
   !/ : :

 
 !!


!  	b  :>9 !/ : :

 
 !!


!	969 	9	79v
R.
R     , ,4 - -	"<|	
	
 
	
  $.... .. "	..
 .. 
..`AH GK'?C	:r8   rD   )@rK   
__future__r   r\   rB  r  r[  r   r   r   r/   collectionsr   r   typingr   r   flask.wrappersre  r   r   limits.errorsr	   limits.storager
   r   r   limits.strategiesr   r   ordered_setr   werkzeug.httpr   r   _compatr   _limitsr   r   r   r   r   _managerr   _typingr   r   r   r   r   	constantsr   r    r!   r"   errorsr#   utilr$   r&   	dataclassrP   rD   rN   r8   r6   <module>r     s    #         #     - , F F 5 " / $  #  S R % $6 6r 
! 
! 
!\ \r8   