7.Flask:数据校验

Flask(数据校验 七)

数据校验原因

由于有很多手段可以绕过前端往后端发送数据,所以后端需要对数据进行校验后才可以朝数据库插入

前台提供数据输入

写一个简单的提交信息的表单页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="{{ url_for('register') }}" method="post">
<label>手机号码:</label><input name="phone">
<label>密码:</label><input name="pwd">
<label>确认密码:</label><input name="confirm_pwd">
<input type="submit">
</form>
</body>
</html>

注册页面

后台接受表单

在写一个后台/register路由数据获取部分

1
2
3
4
5
6
7
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
phone = request.form.get('phone')
pwd = request.form.get('pwd')
confirm_pwd = request.form.get('confirm_pwd')

判断phone存在

1
2
if not phone:
abort(412)

abort源码

1
2
3
4
5
def abort(status, *args, **kwargs):
return _aborter(status, *args, **kwargs)


_aborter = Aborter()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Aborter(object):
def __init__(self, mapping=None, extra=None):
if mapping is None:
mapping = default_exceptions
self.mapping = dict(mapping)
if extra is not None:
self.mapping.update(extra)

def __call__(self, code, *args, **kwargs):
if not args and not kwargs and not isinstance(code, integer_types):
raise HTTPException(response=code)
if code not in self.mapping:
raise LookupError("no exception for %r" % code)
raise self.mapping[code](*args, **kwargs)

可以看到abort其实就是调用了_aborter也就是Aborter__call__

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
mapping = default_exceptions
default_exceptions = {}
__all__ = ["HTTPException"]


def _find_exceptions():
for _name, obj in iteritems(globals()):
try:
is_http_exception = issubclass(obj, HTTPException)
except TypeError:
is_http_exception = False
if not is_http_exception or obj.code is None:
continue
__all__.append(obj.__name__)
old_obj = default_exceptions.get(obj.code, None)
if old_obj is not None and issubclass(obj, old_obj):
continue
default_exceptions[obj.code] = obj


_find_exceptions()
del _find_exceptions

它把上面全部的错误都添加进去了

下面看一下NotFound

1
2
3
4
5
6
7
8
9
10
11
class NotFound(HTTPException):
"""*404* `Not Found`

Raise if a resource does not exist and never existed.
"""

code = 404
description = (
"The requested URL was not found on the server. If you entered"
" the URL manually please check your spelling and try again."
)

我们访问页面出现404的时候它的返回内容就是

code = 404

1
2
3
4
description = (
"The requested URL was not found on the server. If you entered"
" the URL manually please check your spelling and try again."
)

校验数据

所以我们的phone判断为

1
2
if not phone:
abort(412, description='phone is empty')

判断号码存在

完整:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
phone = request.form.get('phone')
pwd = request.form.get('pwd')
confirm_pwd = request.form.get('confirm_pwd')
if not phone:
abort(412, description='phone is empty')
if re.match(r'^1[3,5,7,8,9]\d{9}$', phone):
abort(412, description='phone is error')
if not pwd:
abort(412, description='password is empty')
if len(pwd) < 6:
abort(412, description='password is not safe')
if pwd != confirm_pwd:
abort(412, description='password is not consistent')
return 'hello'

切换为中文

在页面上添加提示信息

<body> <form>之间添加{{ msg }}

1
2
3
<body>
{{ msg }}
<form action="{{ url_for('register') }}" method="post">

使用abort的第二种用法,返回Response对象

1
2
3
4
5
res = Response(render_template('register.html', msg='请输入电话号码'),
status='412',
content_type='text/html;charset=utf-8')
if not phone:
abort(res)

截屏2020-06-25 下午3.20.07

也可以写成

1
2
if not phone:
return render_template('register.html', msg='请输入电话号码'), 412, {"content_type": 'text/html;charset=utf-8'}

效果是一样的

 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
您的支持将鼓励我继续创作!