File size: 2,844 Bytes
1855e08 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | from flask import Flask, render_template, request, redirect
from flask_socketio import SocketIO, emit
import sqlite3
from datetime import datetime
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*") # ํฌ๋ก์ค ๋๋ฉ์ธ ํ์ฉ
# -------------------------------
# DB ์ด๊ธฐํ
# -------------------------------
def init_db():
with sqlite3.connect("chat.db") as conn:
c = conn.cursor()
c.execute("""
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
message TEXT NOT NULL,
timestamp TEXT NOT NULL
)
""")
conn.commit()
init_db()
# -------------------------------
# ์ฑํ
๊ธฐ๋ก ๊ด๋ จ ํจ์
# -------------------------------
def get_chat_history(limit=50):
with sqlite3.connect("chat.db") as conn:
c = conn.cursor()
c.execute("SELECT username, message, timestamp FROM messages ORDER BY id DESC LIMIT ?", (limit,))
return c.fetchall()[::-1] # ์ต๊ทผ ๋ฉ์์ง ์ญ์ ์ ๋ ฌ
def save_message(username, message):
with sqlite3.connect("chat.db") as conn:
c = conn.cursor()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
c.execute("INSERT INTO messages (username, message, timestamp) VALUES (?, ?, ?)",
(username, message, timestamp))
conn.commit()
# -------------------------------
# ๋ผ์ฐํธ
# -------------------------------
@app.route("/")
def index():
return render_template("login.html")
@app.route("/chat", methods=["POST"])
def chat():
username = request.form.get("username")
if not username:
return redirect("/")
return render_template("chat.html", username=username)
# -------------------------------
# ์์ผ ์ด๋ฒคํธ
# -------------------------------
@socketio.on("join")
def handle_join(username):
history = get_chat_history()
for user, msg, time in history:
emit("message", {"user": user, "text": msg, "time": time})
emit("message", {"user": "์์คํ
",
"text": f"{username}๋์ด ์
์ฅํ์
จ์ต๋๋ค.",
"time": datetime.now().strftime("%H:%M:%S")},
broadcast=True)
@socketio.on("message")
def handle_message(data):
user = data["user"]
text = data["text"]
time = datetime.now().strftime("%H:%M:%S")
save_message(user, text)
emit("message", {"user": user, "text": text, "time": time}, broadcast=True)
# -------------------------------
# ์คํ
# -------------------------------
if __name__ == "__main__":
# Hugging Face Spaces ํ๊ฒฝ โ ๋ฐ๋์ 0.0.0.0:7860 ์ฌ์ฉ
socketio.run(app, host="0.0.0.0", port=7860, debug=True)
|