Add request.client_ip (#2790)

Co-authored-by: L. Kärkkäinen <Tronic@users.noreply.github.com>
This commit is contained in:
L. Kärkkäinen
2023-07-13 21:01:02 +01:00
committed by GitHub
parent dc3c4d1393
commit 31d7ba8f8c
2 changed files with 20 additions and 6 deletions

View File

@@ -838,19 +838,31 @@ class Request(Generic[sanic_type, ctx_type]):
@property
def remote_addr(self) -> str:
"""
Client IP address, if available.
1. proxied remote address `self.forwarded['for']`
2. local remote address `self.ip`
Client IP address, if available from proxy.
:return: IPv4, bracketed IPv6, UNIX socket name or arbitrary string
:rtype: str
"""
if not hasattr(self, "_remote_addr"):
self._remote_addr = str(
self.forwarded.get("for", "")
) # or self.ip
self._remote_addr = str(self.forwarded.get("for", ""))
return self._remote_addr
@property
def client_ip(self) -> str:
"""
Client IP address.
1. proxied remote address `self.forwarded['for']`
2. local peer address `self.ip`
New in Sanic 23.6. Prefer this over `remote_addr` for determining the
client address regardless of whether the service runs behind a proxy
or not (proxy deployment needs separate configuration).
:return: IPv4, bracketed IPv6, UNIX socket name or arbitrary string
:rtype: str
"""
return self.remote_addr or self.ip
@property
def scheme(self) -> str:
"""