mirror of https://github.com/tiangolo/fastapi.git
Merge 5a38a03bf8 into 272204c0c7
This commit is contained in:
commit
dc3bd24325
|
|
@ -137,6 +137,32 @@ class UploadFile(StarletteUploadFile):
|
|||
"""
|
||||
return await super().close()
|
||||
|
||||
async def read_text(
|
||||
self,
|
||||
encoding: Annotated[
|
||||
str,
|
||||
Doc("The text encoding to use when decoding bytes. Defaults to 'utf-8'."),
|
||||
] = "utf-8",
|
||||
) -> str:
|
||||
"""
|
||||
Read the entire file as a text string.
|
||||
This is a convenience wrapper around `await self.read()`
|
||||
that decodes the bytes using the given encoding.
|
||||
## Example
|
||||
```python
|
||||
@app.post("/upload-text/")
|
||||
async def upload_text(file: UploadFile):
|
||||
text = await file.read_text()
|
||||
return {"length": len(text)}
|
||||
```
|
||||
Args:
|
||||
encoding: The text encoding to use (default: 'utf-8').
|
||||
Returns:
|
||||
The decoded file content as a string.
|
||||
"""
|
||||
data = await self.read()
|
||||
return data.decode(encoding)
|
||||
|
||||
@classmethod
|
||||
def __get_validators__(cls: Type["UploadFile"]) -> Iterable[Callable[..., Any]]:
|
||||
yield cls.validate
|
||||
|
|
|
|||
|
|
@ -172,6 +172,9 @@ addopts = [
|
|||
]
|
||||
xfail_strict = true
|
||||
junit_family = "xunit2"
|
||||
markers = [
|
||||
"asyncio: mark test to run with asyncio event loop",
|
||||
]
|
||||
filterwarnings = [
|
||||
"error",
|
||||
'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\..*:DeprecationWarning:starlette',
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
-e .[all]
|
||||
-r requirements-docs-tests.txt
|
||||
pytest >=7.1.3,<9.0.0
|
||||
pytest-asyncio >=0.21.0,<0.25.0
|
||||
coverage[toml] >= 6.5.0,< 8.0
|
||||
mypy ==1.14.1
|
||||
dirty-equals ==0.9.0
|
||||
|
|
|
|||
|
|
@ -70,3 +70,17 @@ async def test_upload_file():
|
|||
await file.seek(0)
|
||||
assert await file.read() == b"data and more data!"
|
||||
await file.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uploadfile_read_text(tmp_path):
|
||||
file_path = tmp_path / "sample.txt"
|
||||
file_path.write_text("Hello FastAPI!")
|
||||
|
||||
with open(file_path, "rb") as f:
|
||||
upload = UploadFile(filename="sample.txt", file=f)
|
||||
content = await upload.read_text()
|
||||
assert content == "Hello FastAPI!"
|
||||
assert (
|
||||
upload.filename == "sample.txt"
|
||||
) # make sure .read_text() doesn't modify filename or headers
|
||||
|
|
|
|||
Loading…
Reference in New Issue