|
- #standard
- import asyncio
- import html
- import traceback
- #custom
- import dataset
- from fastapi import FastAPI, WebSocket, Form, File, UploadFile, Response, Request, WebSocketDisconnect, websockets
- from fastapi.responses import HTMLResponse
- from fastapi.staticfiles import StaticFiles
- from fastapi.templating import Jinja2Templates
- import starlette.status as status
- from starlette.responses import RedirectResponse
-
- app = FastAPI()
- app.mount('/static', StaticFiles(directory="./static"), name="static")
- templates = Jinja2Templates(directory="templates")
- @app.get('/', response_class=HTMLResponse)
- async def getRoot(request: Request):
- return RedirectResponse('/static/index.html', status_code=status.HTTP_302_FOUND)
-
- db = dataset.connect('sqlite:///../state.db')
-
- @app.websocket('/websocket')
- async def runGameSession(websocket: WebSocket):
- await websocket.accept()
- try:
- await websocket.send_json({
- 'type': 'header',
- 'rawHTML': 'Testing Header Text'
- })
-
- while True:
- await websocket.send_json({
- 'type': 'narrative',
- 'rawHTML': 'Something <i>interesting</i> happened.'
- })
- while True:
- try:
- resp = await asyncio.wait_for(websocket.receive_json(), timeout=5)
- await websocket.send_json({
- 'type': 'playerEcho',
- 'rawHTML': '> ' + html.escape(resp['playerInput'])
- })
- break
- except asyncio.exceptions.TimeoutError:
- # timeout
- await websocket.send_json({
- 'type': 'narrativeUpdate',
- 'rawHTML': 'Something <i>EVEN MORE interesting</i> happened.'
- })
- except Exception as e:
- traceback.print_exc()
-
|