반응형
Notice
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 네트워크보안
- I'm Sorry
- 데이터베이스
- 보안
- 사이버보안
- 네트워크
- 알고리즘
- 파이썬
- 소프트웨어공학
- 2
- 인공지능
- 코딩
- 데이터구조
- 프로그래밍
- 버전관리
- 프로그래밍언어
- 데이터분석
- 머신러닝
- 클라우드컴퓨팅
- 자료구조
- Yes
- 빅데이터
- 딥러닝
- 컴퓨터비전
- 소프트웨어
- 자바스크립트
- 컴퓨터과학
- 데이터과학
- 컴퓨터공학
- 웹개발
Archives
- Today
- Total
스택큐힙리스트
FastAPI에서 UploadFile을 저장하는 방법: 본문
반응형
제가 파일을 POST로 받습니다. 로컬로 저장할 때는 file.read()를 사용하여 내용을 읽을 수 있지만, file.name을 통해 이름을 가져오면 잘못된(16) 이름이 출력됩니다. 이 이름으로 찾으려고 시도하면 오류가 발생합니다. 문제가 무엇일까요?
제 코드:
@router.post(
path=/upload,
response_model=schema.ContentUploadedResponse,
)
async def upload_file(
background_tasks: BackgroundTasks,
uploaded_file: UploadFile = File(...)):
uploaded_file.file.rollover()
uploaded_file.file.flush()
#shutil.copy(uploaded_file.file.name, f'../api/{uploaded_file.filename}')
background_tasks.add_task(s3_upload, uploaded_file=fp)
return schema.ContentUploadedResponse()
답변 1
import shutil
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Callable
from fastapi import UploadFile
def save_upload_file(upload_file: UploadFile, destination: Path) -> None:
try:
with destination.open(wb) as buffer:
shutil.copyfileobj(upload_file.file, buffer)
finally:
upload_file.file.close()
def save_upload_file_tmp(upload_file: UploadFile) -> Path:
try:
suffix = Path(upload_file.filename).suffix
with NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
shutil.copyfileobj(upload_file.file, tmp)
tmp_path = Path(tmp.name)
finally:
upload_file.file.close()
return tmp_path
def handle_upload_file(
upload_file: UploadFile, handler: Callable[[Path], None]
) -> None:
tmp_path = save_upload_file_tmp(upload_file)
try:
handler(tmp_path) # 저장된 임시 파일로 무언가를 수행합니다
finally:
tmp_path.unlink() # 임시 파일을 삭제합니다
노트: 위의 함수들은
async def
이 아닌def
엔드포인트 내에서 사용하고 싶을 것입니다. 왜냐하면 그들은 블로킹 API를 사용하기 때문입니다.
답변 2
FastAPI is a powerful web framework for building APIs in Python. Its features and high performance make it a popular choice among developers. One common requirement in web development is handling file uploads, and FastAPI provides a convenient way to save uploaded files. This essay will discuss how to save an UploadFile in FastAPI, providing step-by-step guidance.To begin, we need to understand the basic structure of a FastAPI application. FastAPI follows a model-view-controller (MVC) architectural pattern, where the endpoints are defined in a Python file called the main file. Typically, this file is named main.py or app.py.
First, we need to import the necessary modules from FastAPI and create an instance of FastAPI. Additionally, we need to import the UploadFile class from the fastapi module. The UploadFile class allows us to work with files uploaded by users.
Once we have set up the basic structure of our FastAPI application, we can define an endpoint that handles file uploads. The endpoint should have a route decorator specifying the URL path and an HTTP POST method decorator. Inside our endpoint function, we declare a parameter of type UploadFile to receive the uploaded file.
When a user makes a POST request to our endpoint and attaches a file, FastAPI will automatically populate the UploadFile object with the file data. We can access the file's contents and details such as filename, content type, and size using the methods and attributes provided by the UploadFile class.
To save the uploaded file, we can use the `write()` method of the UploadFile object. This method takes the destination path where the file should be saved. We can choose any valid path on our system, including relative or absolute paths, as per our requirements.
Before saving the file, it is recommended to validate and sanitize its contents. We can perform checks such as file type validation, size limits, and any additional business logic necessary for our application. Once the file has been validated, we can call the `write()` method to save it.
After saving the file, it is good practice to return a response to the user, indicating the success or failure of the file upload.
In summary, saving an UploadFile in FastAPI is straightforward. We need to define an endpoint that handles file uploads, receive the uploaded file via a parameter of type UploadFile, validate and sanitize the file contents as necessary, and finally, save the file using the `write()` method. With these steps, we can efficiently handle file uploads in FastAPI and create robust and secure applications.
반응형
Comments