• flask 模版语言及信息传递


    if语句

    格式:

    {% if command %}
    {% elif %}
    {% else %}
    {% endif %}

    代码示例

    flask_one.py

    #encoding:utf-8
    from flask import Flask,url_for,redirect,render_template
    
    app = Flask(__name__)
    
    @app.route('/<is_login>')
    def index(is_login):
    
        if is_login == "1":        #模拟1为登陆成功
            user = {
                "aa":"test",
                'bbb':'注销',
                'age':"11"
            }
            return render_template('index.html',users=user)
        else:
            return render_template('index.html')
    
    
    if __name__ == '__main__':
        app.run(debug=True)

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        {% if users and users.age >10 %}        #这里的users为py文件里传递的user字典,users.age为py文件user字典里的age
            <a href="#">{{ users.aa }}</a>
            <a href="#">{{  users.bbb}}</a>
        {% else %}
            <a href="#">登陆</a>
            <a href="#">注册</a>
        {% endif %}
    </body>
    </html>

    url入口:127.0.0.1/{1,0..}

    for语句

    格式:

    {% for .. %}
    {% endfor %}

    代码实现:

    flask_one.py

    #encoding:utf-8
    from flask import Flask,url_for,redirect,render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        users = {
            'username':'tsdf',
            'age':11
        }
        return render_template('index.html',user=users)
    if __name__ == '__main__': app.run(debug=True)

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        {% for k,v in user.items() %}        #for语句
            <p>{{ k }}----{{ v }}</p>
        {% endfor %}
    </body>
    </html>

    redirect 传数据到模板语言(flash)

    from flask import redirect,flash
    
    @app.route('/register',methods=['GET','POST'])
    def register():
        if request.method == 'GET':
            return render_template('register.html')
        else:
            phone = request.form.get('phone')
            uname = request.form.get('username')
            pwd = request.form.get('password')
            pwd1 = request.form.get('password1')
    
            user = User.query.filter(User.phone == phone).first()
    
            if user is not None:
                return "用户已经存在"
            else:
                if phone == "" or uname == "":
                    flash('手机号或者用户名不能为空')
                    return redirect(url_for('register'))
    
                elif pwd != pwd1:
                    flash('两次输入的密码不匹配')
                    return redirect(url_for('register'))
                else:
                    user = User(phone=phone,username=uname,password=pwd)
                    db.session.add(user)
                    db.session.commit()
                    # user = User.query.filter(User.phone == phone).first()
                    # print (user)
                    return redirect(url_for('login'))

    模板语言:

    {% extends 'common.html' %}
    {% block title %}
        注册
    {% endblock %}
    
    {% block head %}
        <link rel="stylesheet" href="{{ url_for('static',filename='css/login_regist.css') }}">
    {% endblock %}
    
    {% block body %}
    <div class="form-container">
        <h4 style="text-align: center">注册</h4>
        <form action="" method="POST">
    
          <div class="form-group">
            <span><input type="text" class="form-control" id="exampleInputEmail1" placeholder="手机号" name="phone"></span>
          </div>
          <div class="form-group">
            <span><input type="text" class="form-control" id="exampleInputEmail1" placeholder="用户名" name="username"></span>
          </div>
          <div class="form-group">
            <span><input  type="password" class="form-control" id="exampleInputPassword1" placeholder="密码" name="password"></span>
          </div>
          <div class="form-group">
            <span><input  type="password" class="form-control" id="exampleInputPassword1" placeholder="重复密码" name="password1"></span>
          </div>
    
          <button type="submit" class="btn btn-block" onclick="tj()">立即注册</button>
        </form>
        <p>
            {% for message in get_flashed_messages() %}
                {{ message }}
            {% endfor %}
        </p>
    </div>
    
    {% endblock %}

    代码示例:

    flask_one.py

    #encoding:utf-8
    from flask import Flask,url_for,redirect,render_template
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        books = [
            {'name':'西游记','author':'吴承恩','price':111},
            {'name': '红楼梦', 'author': '曹雪芹', 'price': 121},
            {'name': '水浒传', 'author': '施耐庵', 'price': 131},
            {'name': '三国演义', 'author': '罗贯中', 'price': 141}
        ]
        return render_template('index.html',book=books)
    
    
    if __name__ == '__main__':
        app.run(debug=True)

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
        <table border="1">
            <thead>
                <th>书名</th>
                <th>作者</th>
                <th>价格</th>
            </thead>
            <tbody>
                {% for book in book %}        #for循环列表并打印字典里的内容
                    <tr>
                        <td>{{ book.name }}</td>
                        <td>{{ book.author }}</td>
                        <td>{{ book.price }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    
    </body>
    </html>

     自定义错误信息

    @app.errorhandler(404)
    def page_noe_found(error):
        return render_template('home/404.html'),404
    
    @app.errorhandler(500)
    def page_noe_found(error):
        return render_template('home/500.html'),500
  • 相关阅读:
    工作单元(UnitOfWork) 模式 (2) .NET Core
    工作单元(UnitOfWork) 模式 (1)
    WebAPI规范设计——违RESTful
    ASP.NET MVC / WebAPI 路由机制详解
    C#封装HttpClient工具类库(.NET4.5以上)
    centos7多网卡配置bond0 (mode6无需交换机做配置)
    linux windows 格式化一块大于2 TiB硬盘
    war包安装jenkins
    redis(一主两从三哨兵模式搭建)记录
    nginx + keepalived 主从模式
  • 原文地址:https://www.cnblogs.com/FRESHMANS/p/8428565.html
Copyright © 2020-2023  润新知