fastapi-with-liveview/main.py
Andros Fenollosa 6a9fc0a72a Fist commit
2024-06-18 14:50:41 +02:00

46 lines
1.1 KiB
Python

import os
import pathlib
from fastapi import FastAPI, Request, WebSocket
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import home
import about_us
app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')
BASE_DIR = pathlib.Path(__file__).parent
templates = Jinja2Templates(
directory=[
BASE_DIR / 'templates',
]
)
@app.get('/')
async def welcome_page(request: Request):
context = {
'request': request,
}
return templates.TemplateResponse(
'layouts/base.html', context,
)
@app.websocket('/ws/liveview/')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data_frontend = await websocket.receive_json()
if data_frontend and 'action' in data_frontend:
action_data = data_frontend['action'].split('->')
if len(action_data) == 2:
action = action_data[0].lower()
function = action_data[1].lower()
await eval(
f'{action}.{function}(websocket, templates, data_frontend)'
)