Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature | Can this support individual limits by IP address or user token? #155

Open
jordanparker6 opened this issue Apr 1, 2023 · 1 comment · May be fixed by #160
Open

Feature | Can this support individual limits by IP address or user token? #155

jordanparker6 opened this issue Apr 1, 2023 · 1 comment · May be fixed by #160

Comments

@jordanparker6
Copy link

Can this project support rate limiting by IP address or individual user tokens?

@colin99d colin99d linked a pull request Apr 11, 2023 that will close this issue
@a-yangyi
Copy link

a-yangyi commented Apr 12, 2023

hey, hope its useful for u:
u can define limiter as Limiter(key_func=get_limiter_key, ...)

def get_limiter_key(request: Request):
    current_key = request.scope.get("client")[0]
    request_headers = request.scope.get("headers")
    limiter_prefix = request.scope.get("root_path") + request.scope.get("path") + ":"

    for headers in request_headers:
        if headers[0].decode() == "authorization":
            current_key = headers[1].decode()
            break

        if headers[0].decode() in ("user-agent", "x-real-ip"):
            current_key += headers[1].decode()

    # shorter key
    hash_object = hashlib.sha256(current_key.encode())
    current_key = hash_object.hexdigest()

    limiter_key = re.sub(
        r":{1,}",
        ":",
        re.sub(r"/{1,}", ":", limiter_prefix + current_key),
    )
    return limiter_key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants