File size: 2,452 Bytes
2956062
a2d05fd
cbd1739
 
 
a2d05fd
3d86c39
2956062
3d86c39
a2d05fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2956062
 
a2d05fd
 
 
 
 
 
 
 
 
 
cbd1739
 
 
 
 
a2d05fd
cbd1739
 
a2d05fd
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# app.py
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse
import qrcode
import io
from functools import lru_cache

app = FastAPI()

# ---------------------------------------------------------------------------
# QR‑code generation helper (cached)
# ---------------------------------------------------------------------------
@lru_cache(maxsize=512)
def _qr_png(text: str) -> bytes:
    """Return PNG bytes for *text*.

    * Uses `qrcode.make`, which is faster than constructing a `QRCode` object
      manually.
    * Memoised with `lru_cache` so repeated requests for the same text are
      served from memory (~10× faster, avoids QR code re‑creation and pillow
      image encoding).
    """
    img = qrcode.make(text)  # Fast 1‑liner QR generation
    buf = io.BytesIO()
    img.save(buf, format="PNG")
    return buf.getvalue()


# ---------------------------------------------------------------------------
# API endpoint
# ---------------------------------------------------------------------------
@app.post("/echo")
async def echo(request: Request):
    """Generate a QR‑code for the given JSON body.

    Accepted payloads:
    • Plain JSON string  → "Hello"
    • Object with `text` → {"text": "Hello"}
    Any other JSON types are stringified via `str(payload)`.
    """
    # ---------------------------------------------------------------------
    # 1. Extract JSON body
    # ---------------------------------------------------------------------
    try:
        payload = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Expected a JSON body")

    if payload in (None, "", []):
        raise HTTPException(status_code=400, detail="Payload cannot be empty")

    # Normalise to string
    text = payload["text"] if isinstance(payload, dict) and "text" in payload else str(payload)

    # ---------------------------------------------------------------------
    # 2. Build / fetch QR code PNG (cached)
    # ---------------------------------------------------------------------
    png_bytes = _qr_png(text)

    # ---------------------------------------------------------------------
    # 3. Return as stream (new BytesIO per request so multiple clients can read)
    # ---------------------------------------------------------------------
    return StreamingResponse(io.BytesIO(png_bytes), media_type="image/png")