Skip to content

refactor: DRY code added for ip address #211

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions slowapi/util.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
from starlette.requests import Request


def get_ipaddr(request: Request) -> str:
def get_remote_address(request: Request) -> str:
"""
Returns the ip address for the current request (or 127.0.0.1 if none found)
based on the X-Forwarded-For headers.
Note that a more robust method for determining IP address of the client is
provided by uvicorn's ProxyHeadersMiddleware.
"""
if "X_FORWARDED_FOR" in request.headers:
return request.headers["X_FORWARDED_FOR"]
else:
if not request.client or not request.client.host:
return "127.0.0.1"
is_local = not request.client or not request.client.host

if is_local:
return "127.0.0.1"
else:
return request.client.host


def get_remote_address(request: Request) -> str:
def get_ipaddr(request: Request) -> str:
"""
Returns the ip address for the current request (or 127.0.0.1 if none found)
based on the X-Forwarded-For headers.
Note that a more robust method for determining IP address of the client is
provided by uvicorn's ProxyHeadersMiddleware.
"""
if not request.client or not request.client.host:
return "127.0.0.1"
has_forwarded = "X_FORWARDED_FOR" in request.headers

return request.client.host
if has_forwarded:
return request.headers["X_FORWARDED_FOR"]
else:
return get_remote_address(request)