如何使用flask跨网页显示Flash消息?

问题描述 投票:0回答:1

我正在尝试在网站中输入用户操作的闪现消息。但由于某种原因,闪现消息没有显示。这是存储库。我多次检查了端点,逻辑似乎运行良好。我将附上下面的部分代码,但对于完整版本,您可能必须访问存储库。

标题代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% if title %}
    <title>{{ title }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {% endif %}
    {% if description %}
    <meta name="description" content="{{ description }}">
    {% endif %}
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">

    <link rel="stylesheet" href="{{ url_for('static', filename='prism.css') }}">
    {% block css%}{% endblock %}
</head>
<style>
    .alert {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px;
  margin: 0 auto;
  width: 90%;
  max-width: 400px;
  text-align: center;
  font-size: 16px;
  line-height: 1.5;
  border-radius: 4px;
}
    .h1{
        color: #FFFFFF;
    }
</style>
<div class = "container">
<header class="p-3 mb-3 border-bottom fixed-top" style="width: 100%; display: flex; justify-content: space-between; background-color: #000000;">
  <div class="d-flex align-items-center">
    <a href="/" class="d-flex align-items-center mb-2 mb-lg-0 link-body-emphasis text-decoration-none">
      <img src="https://icons.veryicon.com/png/o/education-technology/educational-icon/physics-4.png" alt="" width="100" height="100">
        <h1  class="ms-3 mb-0" style="color:#FFFFFF;">Phy6hub</h1><h4 style="color:#FFFFFF";>Connect with the cosmos</h4>
    </a>
  </div>
  <div class="d-flex align-items-center">
    <ul class="nav me-3">
      <li class="nav-item">
        <a class="nav-link link-secondary" href="/dashboard"><img src="../static/home_icon.png"></a>
      </li>
        <li class="nav-item">
        <a class="nav-link link-body-emphasis" href="/my_profile"> <img src="../static/profile_icon.png"></a>
      </li>
    </ul>
    <div class="d-flex" style = "padding-right: 30px">
     <a href = "/new_post"><button type="button" class="btn btn-primary me-2 btn-lg" style="background-color: #39FF14; border: #39FF14">New Post</button></a>
        <a href="/logout"><button type="button" class="btn btn-danger btn-lg">Logout</button></a>
    </div>
  </div>
</header>
</div>
<body style="background-color: black">
{% with messages = get_flashed_messages() %}
      {% if messages %}
        {% for message in messages %}
          <div class="alert alert-{{ message[1] }} alert-dismissible fade show" role="alert">
            <strong>{{ message[0] }}</strong>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
          </div>
        {% endfor %}
      {% endif %}
      {% endwith %}
<div style="margin-top: 140px;">
{% block content%}{% endblock %}
</div>
</body>
<footer class="footer mt-auto py-3 bg-dark" style="background-color: #212529">
  <div class="container" style="background-color: #212529">
    <div class="row" style="color: white">
      <div class="col-md-6" style="color: white">
            {% if message %}
          <div class="mb-3" >
          <span class="text-secondary">Currently logged in as {{ username }}</span>
        </div>
            {% endif %}
        <div class="mb-3">
          <span class="text-secondary">Made by Thumula Karunaratne</span>
        </div>
        <div class="mb-3">
          <span class="text-secondary">Phy6hub for ISAK&copy; 2023</span>
        </div>
      </div>
    </div>
  </div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-qKXV1j0HvMUeCBQ+QVp7JcfGl760yU08IQ+GpUo5hlbpg51QRiuqHAJz8+BrxE/N"
        crossorigin="anonymous"></script>
<script src="{{ url_for('static', filename='prism.js') }}"></script>

</html>

首页代码:

{% extends "base_template.html" %}


{% block css %}
    <style>
        body {
            background-color: black;
            font-family: "Source Code Pro", sans-serif;
            font-size: 16px;
            color: #FFFFFF;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            box-sizing: border-box;
        }
        .post {
            border: 2px solid #39ff14;
            padding: 20px;
            margin-bottom: 20px;
            position: relative;
        }

        .post .title{
            font-weight: bold;
            font-size: 25px;
        }

        .post .user_and_datetime {
            font-style: italic;
            margin-bottom: 10px;
        }
        .post .content {
            margin-bottom: 20px;
        }
        .post .like-button {
            background-color: #39ff14;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 5px;
            cursor: pointer;
            position: absolute;
            top: 10px;
            right: 10px;
        }

        .post .dislike-button {
            background-color: red;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 5px;
            cursor: pointer;
            position: absolute;
            top: 10px;
            right: 100px;
        }
        .post .likes-count {
            position: absolute;
            top: 15px;
            right: 60px;
            font-size: 14px;
        }
    </style>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-aFq/bzH65dt+w6FI2ooMVUpc+21e0SRygnTpmBvdBgSdnuTN7QbdgL+OapgHtvPp" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
</head>
{% endblock %}

{% block content%}
<body style="background-color: black">

        <div class="container" style="margin-top: 40px;">
            <div class="input-group rounded">
                <form method="get">
                  <input type="search" class="form-control bg-dark text-white" placeholder="Search" aria-describedby="search-addon" name = "search"/>
                    <button><i class="bi bi-search"></i></button>
                </form>
            </div>
            <a href="?sort_by="></ahref><button type="button" class="btn btn-dark"> Remove sort</button></a>
            <a href="?sort_by=time"><button type="button" class="btn btn-dark"> Sort by date</button></a>
            <a href="?sort_by=like"><button type="button" class="btn btn-dark">Sort by likes</button></a>
            <div class="row justify-content-between">
                <div class="">
                    <h1>Welcome Back {{ username }}!</h1>
                </div>
            </div>
    {% for post in posts %}
        <div class="post">
            <div class="title" style="color: white">{{ post.title }}</div>
            <div class="user_and_datetime" style="color: white">Posted by {{ post.user }} at {{ post.time }}</div>
            <div class="content" style="color: white">{{ post.content }}</div>
            <p style="color: white"> <i>What should we do to this question's velocity towards the IB students?</i></p>
            <a href="/add_accl/{{post.id}}"><button formmethod="get" class="btn btn-outline-success btn-sm w-auto">Accelerate</button></a>
            <span class="badge bg-secondary">{{ post.likes }}</span>
            <a href="/add_dece/{{post.id}}"><button formmethod="get" class="btn btn-outline-danger btn-sm w-auto">Decelerate</button></a>
        </div>
    {% endfor %}
    </div>
</body>
{% endblock %}

端点代码:

from flask import Flask, render_template, request, redirect, url_for, flash, session
from datetime import datetime
import os
from jinja2 import Environment

from token_manager import generate_token, get_username_from_token, check_token
from db_handler import database_handler as dbh
from password_handler import *
from validations import validate_email, validate_password

app = Flask(__name__)
db = dbh("networking.db")

app.jinja_env.filters['strfttime'] = datetime.strftime
env = Environment()
env.filters['strftime'] = datetime.strftime
secret_key = os.urandom(32)
app.secret_key = secret_key


def error_handler():
    flash(("User timed out. Please try again", "danger"))
    return redirect(url_for("login"))


@app.route("/dashboard", methods=["GET"])
def dashboard():
    try:
        token = session["token"]
        username = get_username_from_token(token)
        # Defining the variable 'sort_by'
        sort_by = request.args.get('sort_by', default="", type=str)
        # Run only when the user is given an input
        if request.method == "GET":
            search_in = request.args.get("search")
            # To avoid running into an error when querying
            if search_in is None:
                # To avoid running into an error when querying
                search_in = ""
            posts = db.search_posts_by_x(sort_by, search_in)
            return render_template("post_template.html",username = username, posts = posts)

    except KeyError:
        flash(("User timed out. Please try again", "danger"))
        return redirect(url_for("login"))


@app.route('/')
def landing_check():  # Redirection to the login page
    try:
        # To make sure that there's no token created
        token = session['token']
        username = get_username_from_token(token)
        return redirect(url_for('dashboard'))
    except KeyError:
        return redirect(url_for('login'))


@app.route("/login", methods=['GET', 'POST'])
def login():
    print(request.method)
    result = ""
    if request.method == 'POST':
        uname = request.form["username"]
        password = request.form["password"]
        uname_check = db.username_exists(uname)
        if uname_check:
            db_object = db.get_user(uname)
            db_password = db_object.password
            pass_state = check_password(password, db_password)
            if pass_state:  # If the password is correct
                uname = db_object.username
                flash("Logged in successfully", "success")
                user = db.get_user(uname)
                session["token"] = generate_token(user.username, 120)
                return redirect(url_for('dashboard', username=user.username))

            else:
                flash(("Wrong password", "danger"))
                return redirect(url_for('login'))

        else:
            flash(("User does not exist", "danger"))
            return redirect(url_for('login'))

    else:
        return render_template("login.html")


@app.route("/registration", methods=["GET", "POST"])
def registration():
    message = ""
    print(request.method)
    if request.method == "POST":  # Register button pressed
        email = request.form["email"]
        password = request.form["psw"]
        password2 = request.form["psw-repeat"]
        username = request.form["username"]

        if validate_email(email): # Email validation
            if not db.username_exists(username): # Check if username exists in the database
                print(db.email_exists(email))
                if not db.email_exists(email):
                    if validate_password(password):
                        if password == password2:
                            hashed_pwd = hash_password(password)
                            db.insert_user(email, username, hashed_pwd)
                            flash(("User created successfully", "success"))
                            return redirect(url_for("login"))

                        else:
                            flash(("Passwords do not match", "danger"))
                            return redirect(url_for("registration"))
                    else:
                        flash(("The password has to be between 8 and 32 characters", "danger"))
                        return redirect(url_for("registration"))
                else:
                    flash(("Email already exists", "danger"))
                    return redirect(url_for("registration"))
            else:
                flash(("The username already exists", "danger"))
                return redirect(url_for("registration"))
        else:
            print("why?")
            flash(("Please enter a valid email address", "danger"))
            return redirect(url_for("registration"))
    else:
        return render_template("registration.html")


@app.route("/new_post", methods=["GET", "POST"])
def new_post():
    try:
        token = session["token"]
        username = get_username_from_token(token)
        if request.method == "POST":
            title = request.form["title"]
            content = request.form["content"]
            if title.strip() != "":
                if content.strip() != "":
                    temp_result = db.insert_post(username, title, content)
                    if not temp_result:
                        flash(("The title already exists", "danger"))
                        return redirect(url_for("new_post"))
                    else:
                        flash(("Post added successfully", "success"))
                        return redirect(url_for("my_profile", username=username))
                else:
                    flash(("The content cannot be empty", "danger"))
            else:
                flash(("The title cannot be empty", "danger"))

        elif request.method == "GET":
            return render_template("new_post.html", username=username)

    except KeyError:
        return error_handler()


@app.route("/my_profile")
def my_profile():
    try:
        token = session["token"]
        username = get_username_from_token(token)
        user = db.get_user(username)
        posts = db.get_own_posts(username)
        return render_template("profile.html", posts=posts, username=username, user=user)

    except KeyError:
        return error_handler()


@app.route("/change_password", methods=["POST", "GET"])
def change_password():
    try:
        token = session["token"]
        username = get_username_from_token(token)
        if check_token(token):
            if request.method == "POST":
                user = db.get_user(username)
                old_pw = request.form["old_pw"]
                new_pw_1 = request.form["new_pw_1"]
                new_pw_2 = request.form["new_pw_2"]
                if check_password(old_pw, user.password):
                    if validate_password(new_pw_1):
                        if new_pw_1 == new_pw_2:
                            temp_pass = hash_password(new_pw_1)
                            db.change_pswd(username, temp_pass)
                            flash(("Password changed successfully", "success"))
                            return redirect(url_for("dashboard"))

                        else:
                            flash(("New passwords do not match", "danger"))
                            return redirect(url_for("change_password"))
                    else:
                        flash(("The new password must be between 8-32 characters", "danger"))
                        return redirect(url_for("change_password"))
                else:
                    print("stuck at here")
                    flash(("Wrong password", "danger"))
                    return redirect(url_for("change_password"))

            elif request.method == "GET":
                return render_template("change_password.html", username = username)



    except KeyError:
        return error_handler()


@app.route('/logout')
def logout():
    session.pop('token', None)
    return redirect(url_for('login'))


@app.route("/add_accl/<int:post_id>")
def add_like(post_id):
    try:
        token = session['token']
        if check_token(token):
            db.add_like_or_dislike(post_id, "like")
            return redirect(request.referrer)
        else:
            return error_handler()
    except KeyError:
        return error_handler()


@app.route("/add_dece/<int:post_id>")
def add_dislike(post_id):
    try:
        token = session['token']
        if check_token(token):
            db.add_like_or_dislike(post_id, "dislike")
            return redirect(request.referrer)
        else:
            return error_handler()
    except KeyError:
        return error_handler()


@app.route("/delete/<int:post_id>")
def delete_post(post_id):
    try:
        token = session["token"]
        if check_token(token):
            db.delete_post(post_id)
            return redirect(request.referrer)
            flash(("Post was deleted successfully", "success"))
        else:
            return error_handler()
    except KeyError:
        return error_handler()



if __name__ == "__main__":
    app.debug = True  # setting the debugging option for the application instance
    app.run()

谢谢!

我使用 pycharm 运行 Flask 文件,除了显示 Flask 消息之外,它运行顺利。

python python-3.x flask jinja2
1个回答
0
投票

要显示分类的消息,文档中有一个单独的部分。

您将由消息和类别组成的元组传递给

flash
命令。
但是,在这种情况下,该命令需要两个单独的参数。首先是消息,然后是类别。

flash("User timed out. Please try again", "danger")

此外,类别嵌入如下。

{% with messages = get_flashed_messages(with_categories=true) %}
   {% if messages %}
     {% for category, message in messages %}
       <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
         <strong>{{ message }}</strong>
         <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
       </div>
     {% endfor %}
   {% endif %}
{% endwith %}

请再次检查您的 HTML 结构。

body
标签仅供一次性使用,并包含页面的整个可显示部分。

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- title, styles, etc. -->
  </head>
  <body>
    <!-- content of the page -->
  </body>
</html>

这是使用 Flask 和 Bootstrap 5 显示消息的简化示例。

from flask import (
    Flask, 
    flash, 
    render_template, 
)

app = Flask(__name__)
app.secret_key = 'your secret here'

@app.route('/')
def index():
    flash('A simple primary alert—check it out!', 'primary')
    flash('A simple secondary alert—check it out!', 'secondary')
    flash('A simple success alert—check it out!', 'success')
    flash('A simple danger alert—check it out!', 'danger')
    flash('A simple warning alert—check it out!', 'warning')
    flash('A simple info alert—check it out!', 'info')
    flash('A simple light alert—check it out!', 'light')
    flash('A simple dark alert—check it out!', 'dark')
    return render_template('index.html')
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Index</title>
    <link 
        href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
        rel="stylesheet" 
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" 
        crossorigin="anonymous">
</head>
<body>
    <main class="container my-2">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
                    <strong>{{ message }}</strong>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                {% endfor %}
            {% endif %}
        {% endwith %}
    </main>

    <script 
        src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" 
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" 
        crossorigin="anonymous"></script>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.