-
Notifications
You must be signed in to change notification settings - Fork 80
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refac: DRY code added for ip address
- Loading branch information
1 parent
a72bcc6
commit 4d0ef07
Showing
1 changed file
with
10 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,23 @@ | ||
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 | ||
|
||
return request.client.host | ||
return "127.0.0.1" if is_local else 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.headers["X_FORWARDED_FOR"] if has_forwarded else get_remote_address(request) | ||
|
||
|
||
return request.client.host |