Git Commit: serve template for upcoming websockets
Sorry, I promised not to build a chat app, however, It is one of the simplest apps to understand websockets :( Let's start with it, but don't worry, we will be building a real-time collaborative codesharing application as the final product.
To use WebSockets using JS we will first need to serve an HTML template. To serve an HTML template, we will need to create a route using FastAPI. Let's create an HTTP route that serves a template. Filename: codeshare/main.py
from fastapi import FastAPI, WebSocket, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="templates")
app = FastAPI()
@app.get("/{room_id}", response_class=HTMLResponse)
async def chatroom(request: Request, room_id: str):
context = {"request": request, "room_id": room_id}
return templates.TemplateResponse("chatroom.html", context)
Simultaneously, let's create a template file at codeshare/templates/chatroom.html
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<h2 class="mb-5 font-sans text-3xl font-bold text-gray-900 sm:text-4xl">
Websocket
<span class="inline-block text-rose-500">Chat</span>
</h2>
<div id="room-id" style="display: none;">{{room_id}}</div>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off" class="w-lg bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg p-2.5">
<button type="button" class="text-white bg-rose-500 font-lg rounded-lg text-sm px-5 py-2.5 text-center mr-2 mb-2">Send</button>
</form>
<ul id='messages'>
</ul>
</body>
</html>
Now, all we need to do is to add Jinja2==3.1.2 in the requirements.txt file and do a pip install -r requirements.txt.
Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.
We know, we might make it hard for you but definitely worth the efforts.
© Copyright 2022-23 Team FastAPITutorial