Coverage for docs_src/websockets/tutorial001.py: 100%

12 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from fastapi import FastAPI, WebSocket 1abcde

2from fastapi.responses import HTMLResponse 1abcde

3 

4app = FastAPI() 1abcde

5 

6html = """ 1abcde

7<!DOCTYPE html> 

8<html> 

9 <head> 

10 <title>Chat</title> 

11 </head> 

12 <body> 

13 <h1>WebSocket Chat</h1> 

14 <form action="" onsubmit="sendMessage(event)"> 

15 <input type="text" id="messageText" autocomplete="off"/> 

16 <button>Send</button> 

17 </form> 

18 <ul id='messages'> 

19 </ul> 

20 <script> 

21 var ws = new WebSocket("ws://localhost:8000/ws"); 

22 ws.onmessage = function(event) { 

23 var messages = document.getElementById('messages') 

24 var message = document.createElement('li') 

25 var content = document.createTextNode(event.data) 

26 message.appendChild(content) 

27 messages.appendChild(message) 

28 }; 

29 function sendMessage(event) { 

30 var input = document.getElementById("messageText") 

31 ws.send(input.value) 

32 input.value = '' 

33 event.preventDefault() 

34 } 

35 </script> 

36 </body> 

37</html> 

38""" 

39 

40 

41@app.get("/") 1abcde

42async def get(): 1abcde

43 return HTMLResponse(html) 1abcde

44 

45 

46@app.websocket("/ws") 1abcde

47async def websocket_endpoint(websocket: WebSocket): 1abcde

48 await websocket.accept() 1abcde

49 while True: 

50 data = await websocket.receive_text() 1abcde

51 await websocket.send_text(f"Message text was: {data}") 1abcde