Last active
November 10, 2023 02:16
-
-
Save zspine/90195112570a546bdb055d771ce58781 to your computer and use it in GitHub Desktop.
Detecting File Mime Types in FastAPI Using the Python Magic Library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Using `magic` library to detect the MIME type of uploaded files. | |
""" | |
from typing import Annotated | |
from fastapi import FastAPI, File, UploadFile, APIRouter | |
import magic | |
app = FastAPI() | |
#router = APIRouter() | |
@app.post("/files/", tags=["contrib"]) | |
#@router.post("/files/", tags=["contrib"]) | |
async def create_file(file: Annotated[bytes, File()]): | |
return {"file_size": len(file)} | |
@app.post("/uploadfile/", tags=["contrib"]) | |
#@router.post("/uploadfile/", tags=["contrib"]) | |
async def create_upload_file(file: UploadFile): | |
buffer = file.file.read(1024) | |
mime_type = magic.from_buffer(buffer, True) | |
file.file.seek(0) | |
return {"filename": file.filename, "mime": mime_type} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment