adding the logic to generate the image
This commit is contained in:
16
backend/app/api/qr.py
Normal file
16
backend/app/api/qr.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from fastapi.responses import Response
|
||||
|
||||
from app.schemas.qr import QRRequest
|
||||
from app.services.qr_service import generate_qr_image_bytes
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/generate")
|
||||
async def generate_qr(payload: QRRequest):
|
||||
try:
|
||||
img_bytes = generate_qr_image_bytes(payload.text, payload.size)
|
||||
return Response(content=img_bytes, media_type="image/png")
|
||||
except Exception as exc: # pragma: no cover
|
||||
raise HTTPException(status_code=500, detail=str(exc))
|
||||
24
backend/app/main.py
Normal file
24
backend/app/main.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.qr import router as qr_router
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
app = FastAPI(title="QR Code Service")
|
||||
|
||||
# Open CORS to all origins
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(qr_router, prefix="/api/qrcode")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
8
backend/app/schemas/qr.py
Normal file
8
backend/app/schemas/qr.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class QRRequest(BaseModel):
|
||||
text: str = Field(..., description="Text or URL to encode into the QR code")
|
||||
size: int = Field(
|
||||
500, gt=0, le=2000, description="Output image size in pixels (square)"
|
||||
)
|
||||
19
backend/app/services/qr_service.py
Normal file
19
backend/app/services/qr_service.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from io import BytesIO
|
||||
|
||||
import qrcode
|
||||
|
||||
|
||||
def generate_qr_image_bytes(text: str, size: int = 300) -> bytes:
|
||||
img = qrcode.make(text)
|
||||
|
||||
# Ensure RGB for consistent PNG output
|
||||
if getattr(img, "mode", None) != "RGB":
|
||||
img = img.convert("RGB")
|
||||
|
||||
if size:
|
||||
img = img.resize((size, size))
|
||||
|
||||
buf = BytesIO()
|
||||
img.save(buf, "PNG")
|
||||
buf.seek(0)
|
||||
return buf.getvalue()
|
||||
4
backend/main.py
Normal file
4
backend/main.py
Normal file
@@ -0,0 +1,4 @@
|
||||
import uvicorn
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("app.main:app", host="0.0.0.0", port=5001, log_level="info")
|
||||
5
backend/requirements.txt
Normal file
5
backend/requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
fastapi
|
||||
uvicorn[standard]
|
||||
qrcode
|
||||
pillow
|
||||
pydantic
|
||||
Reference in New Issue
Block a user