Add request.client (#272)

* Add request.client

* Docs for request.client
This commit is contained in:
Tom Christie 2018-12-14 09:58:27 +00:00 committed by GitHub
parent 6d04e284d9
commit a2613494a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 34 additions and 1 deletions

View File

@ -61,6 +61,15 @@ Router path parameters are exposed as a dictionary interface.
For example: `request.path_params['username']`
#### Client Address
The client's remote address is exposed as a named two-tuple `request.client`.
Either item in the tuple may be `None`.
The hostname or IP address: `request.client.host`
The port number from which the client is connecting: `request.client.port`
#### Cookies
Cookies are exposed as a regular dictionary interface.

View File

@ -1,8 +1,11 @@
import typing
from collections import namedtuple
from urllib.parse import ParseResult, parse_qsl, urlencode, urlparse
from starlette.types import Scope
Address = namedtuple("Address", ["host", "port"])
class URL:
def __init__(

View File

@ -3,7 +3,7 @@ import json
import typing
from collections.abc import Mapping
from starlette.datastructures import URL, Headers, QueryParams
from starlette.datastructures import URL, Address, Headers, QueryParams
from starlette.formparsers import FormParser, MultiPartParser
from starlette.types import Message, Receive, Scope
@ -71,6 +71,11 @@ class HTTPConnection(Mapping):
self._cookies = cookies
return self._cookies
@property
def client(self) -> Address:
host, port = self._scope.get("client") or (None, None)
return Address(host=host, port=port)
@property
def session(self) -> dict:
assert (

View File

@ -63,6 +63,22 @@ def test_request_headers():
}
def test_request_client():
def app(scope):
async def asgi(receive, send):
request = Request(scope, receive)
response = JSONResponse(
{"host": request.client.host, "port": request.client.port}
)
await response(receive, send)
return asgi
client = TestClient(app)
response = client.get("/")
assert response.json() == {"host": "testclient", "port": 50000}
def test_request_body():
def app(scope):
async def asgi(receive, send):