Flask(數據校驗 七)

Flask(數據校驗 七)

數據校驗原因

由於有很多手段可以繞過前端往後端發送數據,所以後端需要對數據進行校驗後纔可以朝數據庫插入

前臺提供數據輸入

寫一個簡單的提交信息的表單頁面

<!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路由數據獲取部分

@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存在

if not phone:
    abort(412)

abort源碼

def abort(status, *args, **kwargs):
    return _aborter(status, *args, **kwargs)


_aborter = Aborter()
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__

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

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

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

校驗數據

所以我們的phone判斷爲

if not phone:
    abort(412, description='phone is empty')
判斷號碼存在

完整:

@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 }}

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

使用abort的第二種用法,返回Response對象

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

也可以寫成

if not phone:
    return render_template('register.html', msg='請輸入電話號碼'), 412, {"content_type": 'text/html;charset=utf-8'}

效果是一樣的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章