Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Obtener y devolver fichero PDF usando FAST-API

Tiempo de lectura: < 1 minuto

Hola, hoy vamos a ver cómo podemos obtener un fichero PDF guardado y devolverlo usando Fast API con Python.

Vamos a nuestro archivo de routes y añadimos las dependencias necesarias (aparte de las de Fast API):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
from fastapi.responses import FileResponse
import os from fastapi.responses import FileResponse
import os
from fastapi.responses import FileResponse

Ahora vamos a crear nuestro Route que será un GET que devolverá el archivo PDF.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@app.get("/get_pdf", status_code=status.HTTP_200_OK)
def get_convenio_pdf() -> FileResponse:
# Teniendo el nombre del fichero, devolver el fichero dentro de la carpeta pdf
nombre_fichero = "nombre_fichero_devolver"
pdf_folder = "pdf"
pdf = os.path.join(pdf_folder, nombre_fichero)
# Verificar si el archivo existe
if not os.path.exists(pdf):
return {"error": "El archivo no existe"}
# Devolver el fichero pdf de la carpeta /pdf/
return FileResponse(pdf, media_type='application/pdf', filename=nombre_fichero)
@app.get("/get_pdf", status_code=status.HTTP_200_OK) def get_convenio_pdf() -> FileResponse: # Teniendo el nombre del fichero, devolver el fichero dentro de la carpeta pdf nombre_fichero = "nombre_fichero_devolver" pdf_folder = "pdf" pdf = os.path.join(pdf_folder, nombre_fichero) # Verificar si el archivo existe if not os.path.exists(pdf): return {"error": "El archivo no existe"} # Devolver el fichero pdf de la carpeta /pdf/ return FileResponse(pdf, media_type='application/pdf', filename=nombre_fichero)
@app.get("/get_pdf", status_code=status.HTTP_200_OK)
def get_convenio_pdf() -> FileResponse:
   

    # Teniendo el nombre del fichero, devolver el fichero dentro de la carpeta pdf
    nombre_fichero = "nombre_fichero_devolver"
    pdf_folder = "pdf"
    pdf = os.path.join(pdf_folder, nombre_fichero)

    # Verificar si el archivo existe
    if not os.path.exists(pdf):
        return {"error": "El archivo no existe"}
   # Devolver el fichero pdf de la carpeta /pdf/
    return FileResponse(pdf, media_type='application/pdf', filename=nombre_fichero)

En esta función tan simple, cuando invocamos /get_pdf obtenemos el PDF dentro de la carpeta /pdf/fichero.pdf

Indicamos el nombre en la variable nombre_fichero, pero podemos pasar el nombre como parámetro por ejemplo o también podemos almacenarlo en la base de datos y enlazarlo por ID.

Finalmente lo devuleve mediante un objeto FileResponse, esto devolverá un BLOB del PDF.

1

Deja un comentario