记录#
- 今天又是练习日,写一个聊天室,想起了 N 年之前的网络情缘聊天室,算是怀旧吗?
- 多日不写代码,对 db 操作、session 操作、from 操作、request 操作忘记的快差不多了。
- 参考之前的代码把练习完成了,思路基本是正确的,没怎么调试。
- 在读取最后 5 条记录的时候卡住了,在 chatgpt 帮助下完成了 5 条记录的获取。
CODE#
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()"> Login </button>
</p>
<form action="/" method="post">
<input type="text" name="message">
<button>发送</button>
</form>
<p>{text}</p>
</body>
</html>