zoukankan      html  css  js  c++  java
  • flask flash消息

    请求完成,让用户知道状态发生了变化,可以使用flash确认消息

    示例:

    xx.py

    from flask import Flask,render_template,request,redirect,url_for,flash
    from werkzeug.utils import secure_filename
    import os
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = os.urandom(24)
    
    ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg', 'gif'])
    
    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
    
    
    @app.route('/')
    def hello_world():
        return 'Hello World!'
    
    
    @app.route('/upload/',methods=['GET','POST'])
    def upload():
        if request.method == 'POST':
            f = request.files['file']
            print (f)
            if f and allowed_file(f.filename):
                app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(__file__),'static/uploads')
                print(app.config['UPLOAD_FOLDER'])
                if not os.path.exists(app.config['UPLOAD_FOLDER']):
                    os.makedirs(app.config['UPLOAD_FOLDER'])
                upload_file_name = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
                print(secure_filename(f.filename))
                f.save(upload_file_name)
                flash("文件上传成功", 'ok')
                return redirect(url_for('upload'))
            flash("文件上传失败,无效的格式 %s" % f.filename.rsplit('.', 1)[1],'err')
            return redirect(url_for('upload'))
        return render_template('upload.html')
    
    
    if __name__ == '__main__':
        app.run(debug=True)

    前端展示

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h2>文件上传示例</h2>
        <form action="" enctype='multipart/form-data' method='POST'>
            <input type="file" name="file">
            <input type="submit" value="上传">
        </form>
        {% for v in get_flashed_messages(category_filter=['err']) %}
            <p style="color:red;">{{ v }}</p>
        {% endfor %}
        {% for v in get_flashed_messages(category_filter=['ok']) %}
            <p style="color:green;">{{ v }}</p>
        {% endfor %}
    </body>
    </html>
  • 相关阅读:
    IIS7下设置AD单点登录
    数据库日志学习
    用AOP改善javascript代码
    NOPI使用手册
    数据库相关常用查询语句
    SQL事务+异常
    IIS文件上传大小修改配置说明
    VB&XML的增删改查
    python--多线程&多进程
    python-经典类和新式类区别
  • 原文地址:https://www.cnblogs.com/FRESHMANS/p/8559039.html
Copyright © 2011-2022 走看看