二手产品经理

二手产品经理

THIS IS RENO

Chat room - 89 days - Learn Python online for 100 days.

Records#

  1. Today is another practice day, writing a chat room, reminiscent of the online romance chat room from N years ago, is it considered nostalgic?
  2. After several days of not coding, I have almost forgotten about db operations, session operations, form operations, and request operations.
  3. I referred to the previous code and completed the exercise. The overall idea is correct, and I didn't debug much.
  4. I got stuck when trying to retrieve the last 5 records, but with the help of chatgpt, I managed to retrieve the 5 records.

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>Online Romance</title>
    <script src="https://replit.com/public/js/repl-auth-v2.js"></script>
  </head>
  <body>
    <h1>Online Romance Chat Room</h1>
    <p><button onclick="LoginWithReplit()"> Login </button>

</p>
    <form action="/" method="post">
      <input type="text" name="message">
      <button>Send</button>
    </form>
    <p>{text}</p>
  </body>
</html>
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.