Add ruff and secret key
This commit is contained in:
33
app.py
33
app.py
@@ -1,18 +1,30 @@
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
|
||||
import logfire
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi import Depends, FastAPI, Header, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from weasyprint import HTML
|
||||
from weasyprint.text.fonts import FontConfiguration
|
||||
|
||||
# Initialize logging
|
||||
logfire.configure()
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.basicConfig(handlers=[logfire.LogfireLoggingHandler()])
|
||||
logger = logging.getLogger("weasyprint")
|
||||
logger.handlers.clear()
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logger.addHandler(logfire.LogfireLoggingHandler())
|
||||
|
||||
# Load secret from environment variable
|
||||
SECRET_KEY = os.getenv("SECRET_KEY")
|
||||
|
||||
if not SECRET_KEY:
|
||||
raise RuntimeError("SECRET_KEY environment variable is not set")
|
||||
|
||||
|
||||
class PdfRequest(BaseModel):
|
||||
@@ -66,7 +78,21 @@ async def pdf_generator(byte_string: bytes):
|
||||
chunk = byte_stream.read(4096)
|
||||
|
||||
|
||||
@app.post("/pdf")
|
||||
def verify_secret_key(x_secret_key: str = Header(...)):
|
||||
"""
|
||||
Dependency to verify the secret key from the request header.
|
||||
|
||||
Args:
|
||||
x_secret_key (str): The secret key from the request header.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the secret key is invalid.
|
||||
"""
|
||||
if x_secret_key != SECRET_KEY:
|
||||
raise HTTPException(status_code=401, detail="Invalid secret key")
|
||||
|
||||
|
||||
@app.post("/pdf", dependencies=[Depends(verify_secret_key)])
|
||||
async def pdf(body: PdfRequest):
|
||||
"""
|
||||
Endpoint to convert HTML content to a PDF file.
|
||||
@@ -78,8 +104,9 @@ async def pdf(body: PdfRequest):
|
||||
StreamingResponse: A streaming response with the generated PDF file.
|
||||
"""
|
||||
logging.info("Received request to generate PDF")
|
||||
font_config = FontConfiguration()
|
||||
try:
|
||||
byte_string = HTML(string=body.html).write_pdf()
|
||||
byte_string = HTML(string=body.html).write_pdf(font_config=font_config)
|
||||
except Exception as e:
|
||||
logging.error(f"Error generating PDF: {e}")
|
||||
raise HTTPException(status_code=400, detail="Invalid HTML input") from e
|
||||
|
||||
Reference in New Issue
Block a user