Flask-消息提示与异常处理

作者:chen_h
微信号 & QQ:862251340
微信公众号:coderpai


1. 消息提示

flask 中提供了消息闪现机制,方便我们消息提示,所使用的模块是 flash 模块。在我们使用 flash 时,我们需要调用 app.secret_key 字段,该字段会对消息进行加密。具体代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask, render_template, flash

app = Flask(__name__)
app.secret_key = '123456'


@app.route('/')
def hello_world():
    flash('hello flash')
    return render_template("index.html")


if __name__ == "__main__":
    app.run()

之后,我们编写 index.html 页面。在该页面中,我们使用 get_flashed_messages() 函数来得到flash中的内容,但注意,这个返回的是一个数组,因为我们只有一条消息,所以我们只取第一个元素,具体代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
<h1>Hello</h1>

<h2>{{ get_flashed_messages()[0] }}</h2>
</body>
</html>

接下来,我们来模拟网页用户登录时的一些消息提示,如果你还不了解如何处理表单,可以查看这篇博客

首先,我们先查看一下我们文件的结构树,如下:

192:test ming$ tree
.
├── app.py
├── static
└── templates
    ├── index.html
    └── login.html

2 directories, 3 files

首先,我们来编写 login.html 文件,如下:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    <div align="center">
    <h1>User Management</h1>
    {% if get_flashed_messages() %}
        {{ get_flashed_messages()[0] }}
    {% endif %}
    <form action="/check" method="post">
        Username: {{ form.username }} <br />
        Password: {{ form.password }} <br />
        <input type="submit" value="Submit" />
        <input type="reset" value="Reset" />
    </form>
    </div>
</body>
</html>

然后,我们来编写 app.py 文件,如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask, render_template, flash
from wtforms import Form, TextField, PasswordField, validators
from flask import request
from flask import url_for, redirect

app = Flask(__name__)
app.secret_key = '123456'

class LoginForm(Form):
    username = TextField("username", [validators.Required()])
    password = PasswordField("password", [validators.Required()])

@app.route('/')
def index():

    return render_template('index.html')

@app.route('/login')
def login():

    myForm = LoginForm(request.form)

    return render_template("login.html", form = myForm)

@app.route('/check', methods=["POST"])
def check():
    myForm = LoginForm(request.form)

    username = myForm.username.data
    password = myForm.password.data

    if not username:
        flash('please input username')
        return redirect(url_for('login'))
    if not password:
        flash('please input password')
        return redirect(url_for('login'))

    if username == 'admin' and password == 'admin':
        flash('login success')
        return redirect(url_for('index'))
    else:
        flash('username or password is wrong')
        return redirect(url_for('login'))


if __name__ == "__main__":
    app.run()

最后,为了查看效果,我们来编写一个简单的 index.html 文件,如下:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    {% if get_flashed_messages()[0] == 'login success' %}
        {{ get_flashed_messages()[0] }}
    {% endif %}
    <h1> 这是主页 </h1>
</body>
</html>

至此,你应该已经学会了一些基础的消息提示操作吧。

2. 异常处理

接下来,我们来学习 flask 中的异常处理。

当我们访问一个网站的时候,有时候我们会输入一个 URL 不存在的网站,这时候如果跳出来一个 404 的界面,那么用户体验是非常不好的。而这一节就是来处于 404 界面的问题。

那么,在 flask 中提供了一个这样的装饰器 errorhandler,专门来处理一些http错误。比如,我们在 app.py 文件中加入下列代码:

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

之后运行这个程序,在浏览器中随便输入一个网站,可以得到如下界面:

这样,就能比较友好的处理 404 错误。

接下来,举一个比较实用的例子。比如,我们需要判断用户是否存在。在 app.py 代码中,我们可以加入如下代码:

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


@app.route('/users/<user_id>')
def users(user_id):
    if int(user_id) == 1:
        return render_template('users.html', user = user_id)
    else:
        abort(404)

然后编写 users.html 页面,如下:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
User ID: {{ user}}
</body>
</html>

最后,你运行该程序之后,当你访问 http://localhost:5000/users/1 时,可以得到如下正确访问页面:

但是当你访问 http://localhost:5000/users/2 时,你将得到 404 页面,如下:

至此,我们学习完了异常处理。

猜你喜欢

转载自blog.csdn.net/CoderPai/article/details/80506614