Cara membuat server file dengan FastAPI

Dalam contoh ini saya akan menunjukkan cara mengunggah, mengunduh, menghapus, dan mendapatkan file dengan FastAPI

Cara mengunggah file dengan Data Formulir menggunakan FastAPI

Dalam kode berikut kita mendefinisikan bidang file, di sanalah kita akan menerima file dengan Form Data

 from fastapi import FastAPI , UploadFile , File app = FastAPI () @ app . post ( "/upload" ) async def upload_file ( file : UploadFile = File (...)): with open ( file . filename , 'wb' ) as image : content = await file . read () image . write ( content ) image . close () return JSONResponse ( content = { "filename" : file . filename }, status_code = 200 )

Unggah file ke fastapi dengan tukang pos

Cara mengunduh file menggunakan FastAPI

 from fastapi import FastAPI from os import getcwd from fastapi.responses import FileResponse app = FastAPI () @ router . get ( "/download/{name_file}" ) def download_file ( name_file : str ): return FileResponse ( path = getcwd () + "/" + name_file , media_type = 'application/octet-stream' , filename = name_file )

Cara mendapatkan file menggunakan FastAPI

 from fastapi import FastAPI from os import getcwd from fastapi.responses import FileResponse app = FastAPI () @ router . get ( "/file/{name_file}" ) def get_file ( name_file : str ): return FileResponse ( path = getcwd () + "/" + name_file )

Cara menghapus file menggunakan FastAPI

 from fastapi import FastAPI from os import getcwd , remove from fastapi.responses import JSONResponse app = FastAPI () @ router . delete ( "/delete/file/{name_file}" ) def delete_file ( name_file : str ): try : remove ( getcwd () + "/" + name_file ) return JSONResponse ( content = { "removed" : True }, status_code = 200 ) except FileNotFoundError : return JSONResponse ( content = { "removed" : False , "error_message" : "File not found" }, status_code = 404 )
July 30, 2021

codeorayo

Ampuh! Ini rahasia mengembangkan aplikasi secara instan, tinggal download dan kembangkan. Gabung sekarang juga! Premium Membership [PRIVATE] https://premium.codeorayo.com

Leave a Reply

Your email address will not be published. Required fields are marked *