# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['ratelimit', 'ratelimit.auths', 'ratelimit.backends']

package_data = \
{'': ['*']}

extras_require = \
{':python_version >= "3.6" and python_version < "3.7"': ['dataclasses>=0.6,<0.7'],
 'full': ['pyjwt>=1.7.1,<2.0.0', 'redis>=4.2.0rc2'],
 'jwt': ['pyjwt>=1.7.1,<2.0.0'],
 'redis': ['redis>=4.2.0rc2']}

setup_kwargs = {
    'name': 'asgi-ratelimit',
    'version': '0.8.0',
    'description': '',
    'long_description': '# ASGI RateLimit\n\nLimit user access frequency. Base on ASGI.\n\n100% coverage. High performance. Support regular matching. Customizable.\n\n## Install\n\n```\n# Only install\npip install asgi-ratelimit\n\n# Use redis\npip install asgi-ratelimit[redis]\n\n# Use jwt\npip install asgi-ratelimit[jwt]\n\n# Install all\npip install asgi-ratelimit[full]\n```\n\n## Usage\n\nThe following example will limit users under the `"default"` group to access `/towns` at most once per second and `/forests` at most once per minute. And the users in the `"admin"` group have no restrictions.\n\n```python\nfrom typing import Tuple\n\nfrom ratelimit import RateLimitMiddleware, Rule\nfrom ratelimit.auths import EmptyInformation\nfrom ratelimit.backends.redis import MemoryBackend, RedisBackend\n\n# Simple rate-limiter in memory:\n\nrate_limit = RateLimitMiddleware(\n    ASGI_APP,\n    AUTH_FUNCTION,\n    MemoryBackend(),\n    {\n        r"^/towns": [Rule(second=1, group="default"), Rule(group="admin")],\n        r"^/forests": [Rule(minute=1, group="default"), Rule(group="admin")],\n    },\n)\n\n# with Redis:\n\nrate_limit = RateLimitMiddleware(\n    ASGI_APP,\n    AUTH_FUNCTION,\n    RedisBackend(),\n    {\n        r"^/towns": [Rule(second=1, group="default"), Rule(group="admin")],\n        r"^/forests": [Rule(minute=1, group="default"), Rule(group="admin")],\n    },\n)\n\n# Or if using Starlette, FastApi, or index.py framework\napp.add_middleware(\n    RateLimitMiddleware,\n    authenticate=AUTH_FUNCTION,\n    backend=RedisBackend(),\n    config={\n        r"^/towns": [Rule(second=1, group="default"), Rule(group="admin")],\n        r"^/forests": [Rule(minute=1, group="default"), Rule(group="admin")],\n    },\n)\n```\n\n:warning: **The pattern\'s order is important, rules are set on the first match**: Be careful here !\n\nNext, provide a custom authenticate function, or use one of the [existing auth methods](#built-in-auth-functions).\n\n```python\nasync def AUTH_FUNCTION(scope: Scope) -> Tuple[str, str]:\n    """\n    Resolve the user\'s unique identifier and the user\'s group from ASGI SCOPE.\n\n    If there is no user information, it should raise `EmptyInformation`.\n    If there is no group information, it should return "default".\n    """\n    # FIXME\n    # You must write the logic of this function yourself,\n    # or use the function in the following document directly.\n    return USER_UNIQUE_ID, GROUP_NAME\n\n\nrate_limit = RateLimitMiddleware(ASGI_APP, AUTH_FUNCTION, ...)\n```\n\nThe `Rule` type takes a time unit (e.g. `"second"`) and/or a `"group"`, as a param. If the `"group"` param is not specified then the `"authenticate"` method needs to return the "default group".\n\nExample:\n```python\n    ...\n    config={\n        r"^/towns": [Rule(second=1), Rule(second=10, group="admin")],\n    }\n    ...\n\n\nasync def AUTH_FUNCTION(scope: Scope) -> Tuple[str, str]:\n    ...\n    # no group information about this user\n    if user not in admins_group:\n        return user_unique_id, \'default\'\n\n    return user_unique_id, user_group\n```\n\n### Customizable rules\n\nIt is possible to mix the rules to obtain higher level of control.\n\nThe below example will allow up to 10 requests per second and no more than 200 requests per minute, for everyone, for the same API endpoint.\n\n```python\n    ...\n    config={\n        r"^/towns": [Rule(minute=200, second=10)],\n    }\n    ...\n```\n\nExample for a "admin" group with higher limits.\n\n```python\n    ...\n    config={\n        r"^/towns": [\n            Rule(day=400, minute=200, second=10),\n            Rule(minute=500, second=25, group="admin"),\n        ],\n    }\n    ...\n```\n\nSometimes you may want to specify that some APIs share the same flow control pool. In other words, flow control is performed on the entire set of APIs instead of a single specific API. Only the `zone` parameter needs to be used. **Note**: You can give different rules the same `zone` value, and all rules with the same `zone` value share the same flow control pool.\n\n```python\n    ...\n    config={\n        r"/user/\\d+": [\n            Rule(minute=200, zone="user-api"),\n            Rule(second=100, zone="user-api", group="admin"),\n        ],\n    }\n    ...\n```\n\n### Block time\n\nWhen the user\'s request frequency triggers the upper limit, all requests in the following period of time will be returned with a `429` status code.\n\nExample: `Rule(second=5, block_time=60)`, this rule will limit the user to a maximum of 5 visits per second. Once this limit is exceeded, all requests within the next 60 seconds will return `429`.\n\n### Custom block handler\n\nJust specify `on_blocked` and you can customize the asgi application that is called when blocked.\n\n```python\ndef yourself_429(retry_after: int):\n    async def inside_yourself_429(scope: Scope, receive: Receive, send: Send) -> None:\n        await send({"type": "http.response.start", "status": 429})\n        await send(\n            {\n                "type": "http.response.body",\n                "body": b"custom 429 page",\n                "more_body": False,\n            }\n        )\n\n    return inside_yourself_429\n\nRateLimitMiddleware(..., on_blocked=yourself_429)\n```\n\n### Built-in auth functions\n\n#### Client IP\n\n```python\nfrom ratelimit.auths.ip import client_ip\n```\n\nObtain user IP through `scope["client"]` or `X-Real-IP`.\n\nNote: this auth method will not work if your IP address (such as 127.0.0.1 etc) is not allocated for public networks.\n\n#### Starlette Session\n\n```python\nfrom ratelimit.auths.session import from_session\n```\n\nGet `user` and `group` from `scope["session"]`.\n\nIf key `group` not in session, will return `default`. If key `user` not in session, will raise a `EmptyInformation`.\n\n#### Json Web Token\n\n```python\nfrom ratelimit.auths.jwt import create_jwt_auth\n\njwt_auth = create_jwt_auth("KEY", "HS256")\n```\n\nGet `user` and `group` from JWT that in `Authorization` header.\n\n### Custom auth error handler\n\nNormally exceptions raised in the authentication function result in an Internal Server Error, but you can pass a function to handle the errors and send the appropriate response back to the user. For example, if you\'re using FastAPI or Starlette:\n\n```python\nfrom fastapi.responses import JSONResponse\nfrom ratelimit.types import ASGIApp\n\nasync def handle_auth_error(exc: Exception) -> ASGIApp:\n    return JSONResponse({"message": "Unauthorized access."}, status_code=401)\n\nRateLimitMiddleware(..., on_auth_error=handle_auth_error)\n```\n\nFor advanced usage you can handle the response completely by yourself:\n\n```python\nfrom fastapi.responses import JSONResponse\nfrom ratelimit.types import ASGIApp, Scope, Receive, Send\n\nasync def handle_auth_error(exc: Exception) -> ASGIApp:\n    async def response(scope: Scope, receive: Receive, send: Send):\n        # do something here e.g.\n        # await send({"type": "http.response.start", "status": 429})\n    return response\n```\n',
    'author': 'abersheeran',
    'author_email': 'me@abersheeran.com',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://github.com/abersheeran/asgi-ratelimit',
    'packages': packages,
    'package_data': package_data,
    'extras_require': extras_require,
    'python_requires': '>=3.6,<4.0',
}


setup(**setup_kwargs)
