| from fastapi import FastAPI, Request, Form |
| from fastapi.responses import HTMLResponse, RedirectResponse |
| import sqlite3 |
|
|
| app = FastAPI() |
|
|
| conn = sqlite3.connect("chat.db", check_same_thread=False) |
| c = conn.cursor() |
|
|
| c.execute(""" |
| CREATE TABLE IF NOT EXISTS users( |
| username TEXT, |
| password TEXT |
| ) |
| """) |
|
|
| c.execute(""" |
| CREATE TABLE IF NOT EXISTS messages( |
| username TEXT, |
| message TEXT |
| ) |
| """) |
|
|
| conn.commit() |
|
|
|
|
| @app.get("/", response_class=HTMLResponse) |
| def home(): |
| return """ |
| <h1>Emalawi19 Chat</h1> |
| <a href='/login'>Login</a><br> |
| <a href='/register'>Register</a> |
| """ |
|
|
|
|
| @app.get("/register", response_class=HTMLResponse) |
| def register_page(): |
| return """ |
| <h2>Register</h2> |
| <form method="post"> |
| <input name="username" placeholder="username"><br> |
| <input name="password" type="password" placeholder="password"><br> |
| <button type="submit">Register</button> |
| </form> |
| """ |
|
|
|
|
| @app.post("/register") |
| def register(username: str = Form(...), password: str = Form(...)): |
| c.execute("INSERT INTO users VALUES(?,?)",(username,password)) |
| conn.commit() |
| return RedirectResponse("/login", status_code=302) |
|
|
|
|
| @app.get("/login", response_class=HTMLResponse) |
| def login_page(): |
| return """ |
| <h2>Login</h2> |
| <form method="post"> |
| <input name="username"><br> |
| <input name="password" type="password"><br> |
| <button type="submit">Login</button> |
| </form> |
| """ |
|
|
|
|
| @app.post("/login") |
| def login(username: str = Form(...), password: str = Form(...)): |
| user = c.execute( |
| "SELECT * FROM users WHERE username=? AND password=?", |
| (username,password) |
| ).fetchone() |
|
|
| if user: |
| return RedirectResponse(f"/chat/{username}", status_code=302) |
|
|
| return "Login failed" |
|
|
|
|
| @app.get("/chat/{username}", response_class=HTMLResponse) |
| def chat(username: str): |
|
|
| msgs = c.execute("SELECT username,message FROM messages").fetchall() |
|
|
| chat_html = "" |
|
|
| for u,m in msgs: |
| chat_html += f"<p><b>{u}</b>: {m}</p>" |
|
|
| return f""" |
| <h2>Emalawi19 Chat - {username}</h2> |
| |
| <div>{chat_html}</div> |
| |
| <form action="/send/{username}" method="post"> |
| <input name="message"> |
| <button>Send</button> |
| </form> |
| """ |
|
|
|
|
| @app.post("/send/{username}") |
| def send(username: str, message: str = Form(...)): |
| c.execute("INSERT INTO messages VALUES(?,?)",(username,message)) |
| conn.commit() |
| return RedirectResponse(f"/chat/{username}", status_code=302) |
|
|
|
|
| |
| if __name__ == "__main__": |
| import uvicorn |
| uvicorn.run(app, host="0.0.0.0", port=7860) |