【发布时间】:2022-06-28 21:45:07
【问题描述】:
我正在使用 Flask 开发一个聊天网络应用程序。 我在想我会通过将用户消息附加到列表来显示它们,但由于某种原因它不起作用。表单请求似乎有问题,因为当我打印它时它没有显示任何内容。添加占位符消息有效,所以我知道问题出在我附加的部分。 这是 Python 代码:
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.security import check_password_hash, generate_password_hash
from datetime import datetime
from helpers import apology, login_required
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
@app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
@app.route("/")
def index():
"""Chat with other people."""
messages = []
if request.method == "POST":
message = request.form.get("message")
messages.append(message)
else:
return render_template("chat.html", messages=messages)
HTML 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, width=device-width">
<!-- http://getbootstrap.com/docs/5.1/ -->
<link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" rel="stylesheet">
<script crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"></script>
<link href="/static/styles.css" rel="stylesheet">
</head>
<body>
<form method="post" class="position-absolute bottom-0 start-50 translate-middle-x">
<input type="text" id="chat" name="message" id="message" autocomplete="off" class="textbox">
<button class="btn btn-primary" type="submit" id="chat" class="send">send</button>
</form>
<div class="overflow-auto">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
</body>
</html>
【问题讨论】:
标签: python forms flask web chat