Add documentation for UploadFile class in the Request section (#418)

* Add documentation for UploadFile class in Request section

* Implement changes requested in code review

* Simplify upload file reading example
This commit is contained in:
Sebastián Ramírez 2019-03-04 23:25:03 +04:00 committed by Tom Christie
parent 47207129ec
commit 8f138ce922
1 changed files with 32 additions and 0 deletions

View File

@ -116,6 +116,38 @@ In some cases such as long-polling, or streaming responses you might need to
determine if the client has dropped the connection. You can determine this
state with `disconnected = await request.is_disconnected()`.
#### Request Files
Request files are normally sent as multipart form data (`multipart/form-data`).
When you call `await request.form()` you receive a `starlette.datastructures.FormData` which is an immutable
multidict, containing both file uploads and text input. File upload items are represented as instances of `starlette.datastructures.UploadFile`.
`UploadFile` has the following attributes:
* `filename`: A `str` with the original file name that was uploaded (e.g. `myimage.jpg`).
* `content_type`: A `str` with the content type (MIME type / media type) (e.g. `image/jpeg`).
* `file`: A <a href="https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile" target="_blank">`SpooledTemporaryFile`</a> (a <a href="https://docs.python.org/3/glossary.html#term-file-like-object" target="_blank">file-like</a> object). This is the actual Python file that you can pass directly to other functions or libraries that expect a "file-like" object.
`UploadFile` has the following `async` methods. They all call the corresponding file methods underneath (using the internal `SpooledTemporaryFile`).
* `async write(data)`: Writes `data` (`str` or `bytes`) to the file.
* `async read(size)`: Reads `size` (`int`) bytes/characters of the file.
* `async seek(offset)`: Goes to the byte position `offset` (`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 are `async` methods, you need to "await" them.
For example, you can get the file name and the contents with:
```python
form = await request.form()
filename = form["upload_file"].filename
contents = await form["upload_file"].read()
```
#### Other state
If you want to store additional information on the request you can do so