You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

53 regels
1.8 KiB

  1. #standard
  2. import asyncio
  3. import html
  4. import traceback
  5. #custom
  6. import dataset
  7. from fastapi import FastAPI, WebSocket, Form, File, UploadFile, Response, Request, WebSocketDisconnect, websockets
  8. from fastapi.responses import HTMLResponse
  9. from fastapi.staticfiles import StaticFiles
  10. from fastapi.templating import Jinja2Templates
  11. import starlette.status as status
  12. from starlette.responses import RedirectResponse
  13. app = FastAPI()
  14. app.mount('/static', StaticFiles(directory="./static"), name="static")
  15. templates = Jinja2Templates(directory="templates")
  16. @app.get('/', response_class=HTMLResponse)
  17. async def getRoot(request: Request):
  18. return RedirectResponse('/static/index.html', status_code=status.HTTP_302_FOUND)
  19. db = dataset.connect('sqlite:///../state.db')
  20. @app.websocket('/websocket')
  21. async def runGameSession(websocket: WebSocket):
  22. await websocket.accept()
  23. try:
  24. await websocket.send_json({
  25. 'type': 'header',
  26. 'rawHTML': 'Testing Header Text'
  27. })
  28. while True:
  29. await websocket.send_json({
  30. 'type': 'narrative',
  31. 'rawHTML': 'Something <i>interesting</i> happened.'
  32. })
  33. while True:
  34. try:
  35. resp = await asyncio.wait_for(websocket.receive_json(), timeout=5)
  36. await websocket.send_json({
  37. 'type': 'playerEcho',
  38. 'rawHTML': '> ' + html.escape(resp['playerInput'])
  39. })
  40. break
  41. except asyncio.exceptions.TimeoutError:
  42. # timeout
  43. await websocket.send_json({
  44. 'type': 'narrativeUpdate',
  45. 'rawHTML': 'Something <i>EVEN MORE interesting</i> happened.'
  46. })
  47. except Exception as e:
  48. traceback.print_exc()