flask基础(2)模板、消息提示和异常处理

本文详细介绍了Jinja2模板的使用方法,包括基本语法、条件语句、循环语句、模板继承、消息提示及异常处理等内容,适用于Web开发中动态页面的快速构建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、模板的简单使用

使用jinja2模板

  1. templates文件夹下创建.html模板文件
  2. 导入render_template方法
  3. 在相应视图函数中返回渲染的模板
@app.route('/')
def hello_world():
    return render_template('index.html')

使用参数导入

@app.route('/')
def hello_world():
    cotent='Hello World'
    return render_template('index.html',content=cotent)

渲染模板html文件:注意双花括号传入参数

<body>
<h1>{{ content }}</h1>
</body>

2、条件语句

模板代码

<body>
{% if user %}
    hello {{ user.user_name }}
{% else %}
    Hello Strange!
{% endif %}
</body>

视图代码模板

@app.route('/query_user/<user_id>')
def query_user(user_id):
    user=None
    if int(user_id)==1:
        user=User(1,'helloworld')
    return render_template('user_id.html',user=user)

3、循环语句

html代码模板

<body>
{% for user in users %}
    <li>hello{{ user.user_id }}--{{ user.user_name }}</li>
{% endfor %}
</body>

视图函数代码模板

@app.route('/users')
def user_list():
    users=[]
    for i in range(11):
        user=User(i,'helloworld'+str(i))
        users.append(user)
    return render_template('user_list.html',users=users)

4、模板的继承

模板的主题内容不变,不变的部分为基类,变化的部分为子类 基类代码示例——使用{%block}

<div>
    <h1>Header Hello World</h1>
</div>
{% block content%}
{% endblock %}
<div>
    <h1>Footer Hello</h1>
</div>

子类代码——使用{%extends 'base.html'}继承基类

{% extends 'base.html' %}
{% block content %}
    这是第1页
{% endblock %}

 

4、消息提示

使用flash作为消息提示

  • 导入flash
  • 需要配置app.secret_key=' ',flask使用其进行加密
  • 在视图函数中flash('消息提示')
  • 在模板中{{get_flashed_messages()}}获取消息

用户登录作为例子:

@app.route('/login', methods=['Post'])
def login():
    form=request.form
    username=form.get('username')
    password=form.get('password')
    if not username:
        flash('please input username')
        return render_template('index.html')
    if not password:
        flash('please input password')
        return render_template('index.html')
    if username=='zhouzhou' and password=='123456':
        flash('login success')
        return render_template('index.html')
    else:
        flash('username or password is wrong')
        return render_template('index.html')

模板

<body>
<form action="/login" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="Submit">
</form>
<h2>{{ get_flashed_messages()[0] }}</h2>
</body>

5、抛出异常

使用errorhandler()来解决异常,使用abort来抛出异常

@app.errorhandler(404)
def page_notfound(e):
    return render_template('404.html')

模板

<body>
<h1>抱歉页面不存在</h1>
</body>

6、异常处理捕获异常

@app.route('/users/<userid>')
def user(userid):
    if int(userid)==1:
        return render_template('user.html')
    else:
        abort(404)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值