Skip to content

Mb adding websockets + htmx in examples #113

Description

@SoulNaturalist

i mean somethink like this:
It's just primitive example, for getting data by websockets and update by htmx

import json
from pathlib import Path
from fastapi_htmx import htmx, htmx_init
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request, WebSocket

app = FastAPI()
templates = Jinja2Templates(directory=Path("my_app") / "templates")
htmx_init(templates=templates)

@app.get("/", response_class=HTMLResponse)
@htmx("index", "index")
async def root_page(request: Request):
    return {"greeting": "Hello World"}

@app.get("/customers", response_class=HTMLResponse)
@htmx("customers")
async def get_customers(request: Request):
    return {"customers": ["John Doe", "Jane Doe"]}

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        import asyncio
        await asyncio.sleep(5)
        data = {"message": "Hello, WebSocket + HTMX!"}
        await websocket.send_text(json.dumps(data))
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTMX + WebSocket</title>
    <script src="https://unpkg.com/htmx.org"></script>
</head>
<body>
    <h1>{{ greeting }}</h1>
    <div id="your-element" hx-swap="innerHTML"></div>
    <script>
        const socket = new WebSocket('ws://localhost:8000/ws');
        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            htmx.trigger('#your-element', 'update', data);
        };
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customers</title>
    <script src="https://unpkg.com/htmx.org"></script>
</head>
<body>
    <h1>Customers</h1>
    <ul>
        {% for customer in customers %}
        <li>{{ customer }}</li>
        {% endfor %}
    </ul>
    <div id="your-element" hx-swap="innerHTML"></div>
    <script>
        const socket = new WebSocket('ws://localhost:8000/ws');
        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);
            htmx.trigger('#your-element', 'update', data);
        };
    </script>
</body>
</html>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions