使用requests-toolbelt程式庫時,在宣告 upload_file 欄位時,請務必指定檔案名稱和 Content-Type 標頭。以下是一個範例:
filename = 'my_file.txt' m = MultipartEncoder(fields={'upload_file': (filename, open(filename, 'rb'))}) r = requests.post( url, data=m, headers={'Content-Type': m.content_type}, verify=False, ) print(r.request.headers) # confirm that the 'Content-Type' header has been set.
另一個選擇是使用 Python 的 requests 或 HTTPX 函式庫,它們都可以有效地處理串流檔案上傳。以下是每個範例:
使用請求:
import requests url = '...' filename = '...' with open(filename, 'rb') as file: r = requests.post( url, files={'upload_file': file}, headers={'Content-Type': 'multipart/form-data'}, )
自動使用HTTPX:
import httpx url = '...' filename = '...' with open(filename, 'rb') as file: r = httpx.post( url, files={'upload_file': file}, )
自動支援串流檔案上傳,而請求則需要設定Content-Type header為'multipart/form-data'。
FastAPI 的 .stream() 方法可讓您透過將請求正文作為流存取來避免將大檔案載入到記憶體中。若要使用此方法,請依照下列步驟操作:
確保上傳檔案大小符合不超過指定的限制,可以使用 MaxSizeValidator。這是一個範例:
from streaming_form_data import streaming_form_data from streaming_form_data import MaxSizeValidator FILE_SIZE_LIMIT = 1024 * 1024 * 1024 # 1 GB def validate_file_size(chunk: bytes): if FILE_SIZE_LIMIT > 0: streaming_form_data.validators.MaxSizeValidator( FILE_SIZE_LIMIT). __call__(chunk)
這是一個包含這些技術的範例端點:
from fastapi import FastAPI, File, Request from fastapi.responses import HTMLResponse from streaming_form_data.targets import FileTarget, ValueTarget from streaming_form_data import StreamingFormDataParser app = FastAPI() @app.post('/upload') async def upload(request: Request): # Parse the HTTP headers to retrieve the boundary string. parser = StreamingFormDataParser(headers=request.headers) # Register FileTarget and ValueTarget objects. file_ = FileTarget() data = ValueTarget() parser.register('upload_file', file_) parser.register('data', data) async for chunk in request.stream(): parser.data_received(chunk) # Validate file size (if necessary) validate_file_size(file_.content) # Process the uploaded file and data. return {'message': 'File uploaded successfully!'}
以上是如何有效率地上傳大檔案(≥3GB)到FastAPI後端?的詳細內容。更多資訊請關注PHP中文網其他相關文章!