File Post FastApi in Python

 To create a directory and save a video in a FastAPI application in Python, you can use the built-in os module. Here's an example:

python
import os

import uvicorn as uvicorn
from fastapi import FastAPI, UploadFile, File, Header

app = FastAPI()

@app.post("/video")
async def save_video(file: UploadFile):
# Get the file name from the header
file_name = file.filename

# Save the file to disk
with open(f"/tmp/{file_name}", "wb") as f:
f.write(await file.read())

return {"message": "Video saved successfully"}

@app.post("/video1")
async def post_video(video: UploadFile):
return {"video_filename": video.filename}

@app.post("/video3")
async def post_video(video: UploadFile):
directory = "videos"
if not os.path.exists(directory):
os.makedirs(directory)
video_path = os.path.join(directory, video.filename)
with open(video_path, "wb") as f:
f.write(await video.read())
return {"video_filename": video.filename}

uvicorn.run(app, host="192.168.100.12",port=8000)

In this example, we first check if the videos directory exists. If it doesn't, we create it using the os.makedirs method. Then, we join the directory with the video filename to create the full path of the video file. Finally, we open the file in write binary mode and write the contents of the uploaded video to it.

This is just a simple example to get you started. You may want to add additional logic to handle any errors that might occur, such as checking for duplicates or handling any issues with file permissions.

Comments