如何上傳大型檔案(≥3GB)到FastAPI後端?
FastAPI可以透過擷取檔案的部分內容來處理超過1MB的檔案一次從請求主體。這種方法不需要將整個檔案載入到記憶體中,在處理大檔案時建議這樣做。
客戶端請求:
m = MultipartEncoder(fields = {"upload_file":open(file_name,'rb')}) prefix = "http://xxx:5000" url = "{}/v1/uploadfiles".format(prefix) try: req = requests.post( url, data=m, verify=False, )
伺服器端回應:
HTTP 422 {"detail":[{"loc":["body","upload_file"],"msg":"field required","type":"value_error.missing"}]}
對於錯誤:
發生錯誤是因為客戶端請求省略了Content-Type 標頭。 FastAPI 希望客戶端在上傳文件時發送多部分/表單資料請求。如果沒有 Content-Type 標頭,FastAPI 無法正確解析請求正文。解決方案 1(建議):使用串流檔案上傳和區塊編碼請求
HTTPX庫預設支援串流檔案上傳,允許您發送檔案而無需將它們完全載入到範例:
import httpx import time url = 'http://127.0.0.1:8000/upload' files = {'file': open('bigFile.zip', 'rb')} headers = {'Filename': 'bigFile.zip'} data = {'data': 'Hello World!'} with httpx.Client() as client: start = time.time() r = client.post(url, data=data, files=files, headers=headers) end = time.time() print(f'Time elapsed: {end - start}s') print(r.status_code, r.json(), sep=' ')
解決方案2:使用streaming_form_data函式庫
此函式庫提供串流multipart/form -Python的資料解析器,可讓您解析多部分/表單資料請求,而無需完全載入整個請求身體進入記憶。範例:
from streaming_form_data import StreamingFormDataParser from streaming_form_data.targets import FileTarget, ValueTarget app = FastAPI() MAX_REQUEST_BODY_SIZE = 1024 * 1024 * 1024 * 4 # = 4GB MAX_FILE_SIZE = 1024 * 1024 * 1024 * 3 # = 3GB @app.post('/upload') async def upload(request: Request): parser = StreamingFormDataParser(headers=request.headers) filename = request.headers.get('Filename') file_ = FileTarget('./' + filename) data = ValueTarget() parser.register('file', file_) parser.register('data', data) body_validator = MaxBodySizeValidator(MAX_REQUEST_BODY_SIZE) file_validator = MaxSizeValidator(MAX_FILE_SIZE) async for chunk in request.stream(): body_validator(chunk) parser.data_received(chunk)
以上是如何有效上傳大檔案(≥3GB)到FastAPI後端?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3漢化版
中文版,非常好用

WebStorm Mac版
好用的JavaScript開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器