記錄#
- 今天又是練習日,寫一個聊天室,想起了 N 年之前的網絡情緣聊天室,算是懷舊嗎?
- 多日不寫代碼,對 db 操作、session 操作、from 操作、request 操作忘記的快差不多了。
- 參考之前的代碼把練習完成了,思路基本是正確的,沒怎麼調試。
- 在讀取最後 5 條記錄的時候卡住了,在 chatgpt 幫助下完成了 5 條記錄的獲取。
代碼#
main.py#
from flask import Flask, request, redirect, session
from replit import db
import os
from datetime import datetime
app = Flask(__name__)
app.secret_key = os.environ['sission_key']
@app.route("/", methods=["GET"])
def index():
f = open("index.html", "r")
page = f.read()
f.close()
text1 = ''
record_keys = list(db.keys())
last_5_keys = record_keys[-5:]
if last_5_keys:
for key in last_5_keys:
if session.get("user") == "DengLe":
login = f"<a href='/del?id={key}'>X</a>"
else:
login = ""
ms = db[key]
text = f"""
<p><span>{ms["user"]}:</span><span>{ms["message"]}</span><span>{login}</span></p>
"""
text1 += text
page = page.replace("{text}", text1)
return page
@app.route("/", methods=["POST"])
def message():
form = request.form
message = form["message"]
vuser = request.headers["X-Replit-User-Name"]
session["user"] = vuser
timestamp = datetime.now().timestamp()
db[timestamp] = {"message": message, "user": vuser}
return redirect("/")
@app.route("/del")
def delmessage():
form = request.args
del db[form['id']]
return redirect("/")
app.run(host='0.0.0.0', port=81)
HTML#
<html>
<head>
<title>網絡情緣</title>
<script src="https://replit.com/public/js/repl-auth-v2.js"></script>
</head>
<body>
<h1>網絡情緣聊天室</h1>
<p><button onclick="LoginWithReplit()"> 登錄 </button>
</p>
<form action="/" method="post">
<input type="text" name="message">
<button>發送</button>
</form>
<p>{text}</p>
</body>
</html>