Movatterモバイル変換


[0]ホーム

URL:


Skip to content
❤️ Support Starlette viasponsors! 📚 Do you like the new docs?Let us know!

Requests

Starlette includes aRequest class that gives you a nicer interface ontothe incoming request, rather than accessing the ASGI scope and receive channel directly.

Request

Signature:Request(scope, receive=None)

fromstarlette.requestsimportRequestfromstarlette.responsesimportResponseasyncdefapp(scope,receive,send):assertscope['type']=='http'request=Request(scope,receive)content='%s%s'%(request.method,request.url.path)response=Response(content,media_type='text/plain')awaitresponse(scope,receive,send)

Requests present a mapping interface, so you can use them in the sameway as ascope.

For instance:request['path'] will return the ASGI path.

If you don't need to access the request body you can instantiate a requestwithout providing an argument toreceive.

Method

The request method is accessed asrequest.method.

URL

The request URL is accessed asrequest.url.

The property is a string-like object that exposes all thecomponents that can be parsed out of the URL.

For example:request.url.path,request.url.port,request.url.scheme.

Headers

Headers are exposed as an immutable, case-insensitive, multi-dict.

For example:request.headers['content-type']

Query Parameters

Query parameters are exposed as an immutable multi-dict.

For example:request.query_params['search']

Path Parameters

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-tuplerequest.client (orNone).

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.

For example:request.cookies.get('mycookie')

Cookies are ignored in case of an invalid cookie. (RFC2109)

Body

There are a few different interfaces for returning the body of the request:

The request body as bytes:await request.body()

The request body, parsed as form data or multipart:async with request.form() as form:

The request body, parsed as JSON:await request.json()

You can also access the request body as a stream, using theasync for syntax:

fromstarlette.requestsimportRequestfromstarlette.responsesimportResponseasyncdefapp(scope,receive,send):assertscope['type']=='http'request=Request(scope,receive)body=b''asyncforchunkinrequest.stream():body+=chunkresponse=Response(body,media_type='text/plain')awaitresponse(scope,receive,send)

If you access.stream() then the byte chunks are provided without storingthe entire body to memory. Any subsequent calls to.body(),.form(), or.json()will raise an error.

In some cases such as long-polling, or streaming responses you might need todetermine if the client has dropped the connection. You can determine thisstate withdisconnected = await request.is_disconnected().

Request Files

Request files are normally sent as multipart form data (multipart/form-data).

Signature:request.form(max_files=1000, max_fields=1000, max_part_size=1024*1024)

You can configure the number of maximum fields or files with the parametersmax_files andmax_fields; and part size usingmax_part_size:

asyncwithrequest.form(max_files=1000,max_fields=1000,max_part_size=1024*1024):...

Info

These limits are for security reasons, allowing an unlimited number of fields or files could lead to a denial of service attack by consuming a lot of CPU and memory parsing too many empty fields.

When you callasync with request.form() as form you receive astarlette.datastructures.FormData which is an immutablemultidict, containing both file uploads and text input. File upload items are represented as instances ofstarlette.datastructures.UploadFile.

UploadFile has the following attributes:

UploadFile has the followingasync methods. They all call the corresponding file methods underneath (using the internalSpooledTemporaryFile).

  • async write(data): Writesdata (bytes) to the file.
  • async read(size): Readssize (int) bytes of the file.
  • async seek(offset): Goes to the byte positionoffset (int) in the file.
    • E.g.,await myfile.seek(0) would go to the start of the file.
  • async close(): Closes the file.

As all these methods areasync methods, you need to "await" them.

For example, you can get the file name and the contents with:

asyncwithrequest.form()asform:filename=form["upload_file"].filenamecontents=awaitform["upload_file"].read()

Info

As settled inRFC-7578: 4.2, form-data content part that contains fileassumed to havename andfilename fields inContent-Disposition header:Content-Disposition: form-data;name="user"; filename="somefile". Thoughfilename field is optional according to RFC-7578, it helpsStarlette to differentiate which data should be treated as file. Iffilename field was supplied,UploadFileobject will be created to access underlying file, otherwise form-data part will be parsed and available as a rawstring.

Application

The originating Starlette application can be accessed viarequest.app.

Other state

If you want to store additional information on the request you can do sousingrequest.state.

For example:

request.state.time_started = time.time()


[8]ページ先頭

©2009-2026 Movatter.jp