flask消息闪现

对于一个网站来说用户体验是非常重要的.在flask里面消息闪现可以很大程度地提高用户体验.

最近在做一个flask的python web项目,之中就用到了flask消息闪现,下面介绍一下这个知识点.

首先详情见flask官方文档消息闪现这一节,http://docs.jinkan.org/docs/flask/patterns/flashing.html

官方文档我就不说了,先看看我的项目的消息闪现

tag_add.html

{% extends "admin/admin.html" %}

{% block content %}
    

电影网站后台管理系统

添加标签

{% for msg in get_flashed_messages(category_filter=["ok"]) %}

操作成功!

{{ msg }}
{% endfor %} {% for msg in get_flashed_messages(category_filter=["error"]) %}

操作失败!

{{ msg }}
{% endfor %}
{{ form.name }} {% for err in form.name.errors %}
{{ err }}
{% endfor %}
{% endblock %} {% block js %} {% endblock %}

views.py 

# coding=utf-8
from . import admin
from flask import render_template, redirect, url_for, flash, session, request
from app.admin.forms import LoginForm,TagForm
from app.models import Admin,Tag
from functools import wraps
from app import db

# 装饰器,访问控制
def admin_login_req(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if "admin" not in session:
            return redirect(url_for("admin.login"))
        return f(*args, **kwargs)

    return decorated_function
# 标签添加
@admin.route("/tag/add/",methods=["GET","POST"])
@admin_login_req
def tag_add():
    form = TagForm()
    if form.validate_on_submit():
        data = form.data
        tag = Tag.query.filter_by(name=data["name"]).count()
        if tag == 1:
            # 消息闪现
            flash("标签名称已经存在! ","error")
            return redirect(url_for('admin.tag_add'))
        tag = Tag(
            name = data["name"]
        )
        db.session.add(tag)
        db.session.commit()
        flash("添加标签成功! ","ok")
        redirect(url_for('admin.tag_add'))
    return render_template("admin/tag_add.html",form=form)

 forms.py

# coding=utf-8
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired, ValidationError
from app.models import Admin

class TagForm(FlaskForm):
    name = StringField(
        label="名称",
        validators=[
            DataRequired("请输入标签! ")
        ],
        description="标签",
        render_kw={
            "class": "form-control",
            "id": "input_name",
            "placeholder": "请输入标签名称!"
        }
    )
    submit = SubmitField(
        '添加',
        render_kw={
            "class": "btn btn-primary",
        }
    )

 models.py

# coding=utf-8
from datetime import datetime
from app import db

# 标签
class Tag(db.Model):
    __tablename__ = "tag"
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 标题
    addtime = db.Column(db.DateTime, index=True, default=datetime.now)  # 添加时间
    # movies = db.relationship("Movie", backref='tag')  # 电影外键关联

    def __repr__(self):
        return "" % self.name

__init__.py 

 

# coding=utf-8
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import pymysql

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:19981028@localhost:3306/movie?charset=utf8'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SECRET_KEY'] = '2e798784ab164b89a3bbd69683332e18'
app.debug = True
db = SQLAlchemy(app)  # 实例化

from app.home import home as home_blueprint
from app.admin import admin as admin_blueprint

app.register_blueprint(home_blueprint)
app.register_blueprint(admin_blueprint, url_prefix="/admin")


# 404出错页面
@app.errorhandler(404)
def page_not_found(error):
    return render_template("home/404.html"), 404

flask消息闪现_第1张图片

flask消息闪现_第2张图片

你可能感兴趣的:(python项目,Flask知识总结)