Example #1
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:51'
""" 演示 pre-request 框架验证字符串包含测试
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定contains数组,则要求入参必须包含指定子串
contains_params = {"p1": Rule(contains=["a", "b", "c"])}


@app.route("/contains", methods=["GET", "POST"])
@pre.catch(contains_params)
def example_contains_handler(params):
    return str(params)


def example_contains_filter():
    """ 演示contains包含函数
    """
    resp = client.get("/contains", data={"p1": "abc"})
    print(resp.data)

Example #2
0
# !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-19 13:07'
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()


fields = {
    "age": Rule(type=int, enum=[1, 2]),
    "name": Rule(gt=6, lt=12),
    "email": Rule(email=True),
    "mobile": Rule(mobile=True),
    "empty": Rule(required=False, default="sssss_empty"),
    "range": Rule(direct_type=int, gt=10, lt=30),
    "reg": Rule(reg=r'^h\w{3,5}o$', key_map="reg_exp"),
    "trim": Rule(trim=True, json=True),
    "call": Rule(direct_type=int, callback=lambda x: x+100)
}


fields2 = {
    "tot": Rule(required=False, default="hello")
}
Example #3
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-19 11:14'
""" 演示 pre-request 框架如何使用参数字段映射
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定key_map,框架会将参数变更为 key_map 指定的key
map_params = {"params": Rule(key_map="key")}


@app.route("/map", methods=["GET", "POST"])
@pre.catch(map_params)
def example_map_handler(params):
    return str(params)


def example_map_filter():
    """ 演示邮箱验证
    """
    resp = client.get("/map", data={"params": "*****@*****.**"})
    print(resp.data)

Example #4
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:53'
""" 演示 pre-request 框架验证字符串是否符合ipv4规则
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# ipv4,框架将验证入参是否符合ipv4规则
ipv4_params = {"p1": Rule(ipv4=True)}


@app.route("/ipv4", methods=["GET", "POST"])
@pre.catch(ipv4_params)
def example_ipv4_handler(params):
    return str(params)


def example_ipv4_filter():
    """ 演示ipv4格式判断能力
    """
    resp = client.get("/ipv4", data={"p1": "127.0.0.1"})
    print(resp.data)

Example #5
0
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-19 10:49'
""" 演示 pre-request 框架如何使用长度校验,仅针对字符串有效
"""
import json

from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定email=True,此时框架会自动判断用户入参是否符合email正则
length_params = {"params": Rule(gt=2, lt=4)}


@app.route("/length", methods=["GET", "POST"])
@pre.catch(length_params)
def example_length_handler(params):
    return str(params)


def example_length_filter():
    """ 演示字符串长度验证
    """
    resp = client.get("/length", data={"params": "abc"})
    print(resp.data)

    resp = client.get("/length", data={"params": "a"})
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:54'
""" 演示 pre-request 框架验证字符串是否符合地理经度坐标
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# longitude,框架将验证入参是否符合地理纬度规则
longitude_params = {"p1": Rule(longitude=True)}


@app.route("/longitude", methods=["GET", "POST"])
@pre.catch(longitude_params)
def example_longitude_handler(params):
    return str(params)


def example_longitude_filter():
    """ 演示latitude格式判断能力
    """
    resp = client.get("/longitude", data={"p1": "116.3860159600"})
    print(resp.data)

Example #7
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:52'
""" 演示 pre-request 框架验证字符串小写测试
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定lower,字符串将被转换成小写
lower_params = {"p1": Rule(lower=True)}


@app.route("/lower", methods=["GET", "POST"])
@pre.catch(lower_params)
def example_lower_handler(params):
    return str(params)


def example_lower_filter():
    """ 演示lower字符串后缀能力
    """
    resp = client.get("/lower", data={"p1": "TEST"})
    print(resp.data)

Example #8
0
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-19 11:02'
""" 演示 pre-request 框架如何使用正则表达式验证
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定 reg 可以自定义正则表达式
regexp_params = {
    "params":
    Rule(reg=r"^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$")
}


@app.route("/regexp", methods=["GET", "POST"])
@pre.catch(regexp_params)
def example_regexp_handler(params):
    return str(params)


def example_regexp_filter():
    """ 演示邮箱验证
    """
    resp = client.get("/regexp", data={"params": "2019-09-01"})
    print(resp.data)
Example #9
0
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-27 15:44'
""" 演示 pre-request 框架如何使用等于、不等于判断
"""
import json

from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

equal_params = {
    "p1": Rule(direct_type=int, eq=8),
    "p2": Rule(direct_type=int, neq=8)
}


@app.route("/equal", methods=["GET", "POST"])
@pre.catch(equal_params)
def example_equal_handler(params):
    return str(params)


def example_equal_filter():
    """ 演示等于、不等于判断
    """
    resp = client.get("/equal", data={"p1": 8, "p2": 9})
    print(resp.data)
Example #10
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-19 11:04'
""" 演示 pre-request 框架如何使用trim参数自动去除字符串首尾空格
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# trim=True,此时框架会自动将参数字符串首尾空格去除
trim_params = {"params": Rule(trim=True)}


@app.route("/trim", methods=["GET", "POST"])
@pre.catch(trim_params)
def example_trim_handler(params):
    return str(params)


def example_trim_filter():
    """ 演示去空格验证
    """
    resp = client.get("/trim", data={"params": " [email protected] "})
    print(resp.data)

# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:52'
""" 演示 pre-request 框架验证指定字符串前缀测试
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定contains数组,则要求入参必须包含指定子串
startswith_params = {"p1": Rule(startswith="abc")}


@app.route("/startswith", methods=["GET", "POST"])
@pre.catch(startswith_params)
def example_contains_handler(params):
    return str(params)


def example_startswith_filter():
    """ 演示startswith字符串前缀能力
    """
    resp = client.get("/startswith", data={"p1": "abcTest"})
    print(resp.data)

    resp = client.get("/startswith", data={"p1": "acTest"})
Example #12
0
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:51'
""" 演示skip忽略请求参数功能,pre-request仅尝试将key和value添加到params参数字典中
"""

from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定skip=True, pre-request将不应用任何规则,仅将数据添加到结果字典中
skip_params = {
    "params": Rule(skip=True, type=float, default=1, required=False)
}


@app.route("/skip", methods=["GET", "POST"])
@pre.catch(skip_params)
def example_skip_handler(params):
    return str(params)


def example_skip_filter():
    """ 演示skip验证
    """
    resp = client.get("/skip", data={"params": 123})
    print(resp.data)
Example #13
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:52'
""" 演示 pre-request 框架验证字符串任意包含测试
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定 contains_any 数组,则要求入参包含任意指定子串
contains_any_params = {"p1": Rule(contains_any=["a", "c"])}


@app.route("/contains/any", methods=["GET", "POST"])
@pre.catch(contains_any_params)
def example_contains_any_handler(params):
    return str(params)


def example_contains_any_filter():
    """ 演示contains_any包含函数
    """
    resp = client.get("/contains/any", data={"p1": "bef"})
    print(resp.data)

Example #14
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:53'
""" 演示 pre-request 框架验证字符串是否符合mac硬件地址格式
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# mac,框架将验证入参是否符合mac规则
mac_params = {"p1": Rule(mac=True)}


@app.route("/mac", methods=["GET", "POST"])
@pre.catch(mac_params)
def example_mac_handler(params):
    return str(params)


def example_mac_filter():
    """ 演示mac格式判断能力
    """
    resp = client.get("/mac", data={"p1": "34:29:8f:98:16:e4"})
    print(resp.data)

Example #15
0
from flask import make_response, Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True


def json_resp(result):
    result = json.dumps(result)
    resp = make_response(result)
    resp.headers['Content-Type'] = 'application/json'
    return resp


# 指定email=True,此时框架会自动判断用户入参是否符合email正则
args = {"params": Rule(email=True)}


@app.route("/fuzzy", methods=["GET", "POST"])
@pre.catch(args)
def example_fuzzy_handler(params):
    return json_resp(params)


class TestStoreKey:
    def test_store_key(self):
        pre.fuzzy = True

        resp = app.test_client().get("/fuzzy",
                                     data={"params": "wudong@@eastwu.cn"})
Example #16
0
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:52'
""" 演示 pre-request 框架验证字符串禁止包含测试
"""
from flask import Flask
from pre_request import pre, Rule


app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()


# 指定excludes数组,则要求入参必须禁止包含指定子串
excludes_params = {
    "p1": Rule(excludes=["a", "b", "c"])
}


@app.route("/excludes", methods=["GET", "POST"])
@pre.catch(excludes_params)
def example_excludes_handler(params):
    return str(params)


def example_excludes_filter():
    """ 演示contains包含函数
    """
    resp = client.get("/excludes", data={
        "p1": "aoe"
    })
Example #17
0
app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()


def json_resp(result):
    result = json.dumps(result)
    resp = make_response(result)
    resp.headers['Content-Type'] = 'application/json'
    return resp


args = {
    "birthday":
    Rule(type=datetime),
    "happyDay":
    Rule(type=datetime, eq_key="birthday"),
    "publishDate":
    Rule(type=datetime,
         fmt="%Y-%m-%d",
         gte=datetime(2019, 11, 11),
         lte=datetime(2019, 12, 12))
}


@app.route("/datetime", methods=["GET", "POST"])
@pre.catch(args)
def datetime_handler(params):
    return json_resp({})
Example #18
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-05-12 10:03'
from flask import Flask
from pre_request import pre, Rule


app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()


multi_params = {
    "p1": Rule(type=int, split=",", multi=False, required=False, default=None)
}


@app.route("/multi", methods=["GET", "POST"])
@pre.catch(multi_params)
def example_multi_handler(params):
    return str(params)


def example_multi_filter():
    """ 演示手机号验证
    """
    resp = client.get("/multi", data={
        "p1": "1, 2, 3"
    })
Example #19
0
app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()


def json_resp(result):
    result = json.dumps(result)
    resp = make_response(result)
    resp.headers['Content-Type'] = 'application/json'
    return resp


args = {
    "userFirst": {
        "userId": Rule(type=int, required=False),
        "socialInfo": {
            "gender": Rule(type=int, enum=[1, 2], default=1),
            "age": Rule(type=int, gte=18, lt=80),
            "country": Rule(required=True, deep=False)
        }
    },
    "userSecond": {
        "userId": Rule(type=int, required=False, neq_key="userFirst.userId"),
        "socialInfo": {
            "gender": Rule(type=int, enum=[1, 2], default=1, neq_key="userFirst.socialInfo.gender"),
            "age": Rule(type=int, gte=18, lt=80, required_with="userFirst.socialInfo.age"),
            "country": Rule(required=True, deep=False)
        }
    }
}
Example #20
0
""" 演示 pre-request 框架如何使用数字范围校验
"""
import json

from flask import Flask
from pre_request import pre, Rule


app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()


# 指定range范围,则框架会对数字范围作出校验
range_params = {
    "params": Rule(type=int, gt=5, lt=10)
}


@app.route("/range", methods=["GET", "POST"])
@pre.catch(range_params)
def example_range_handler(params):
    return str(params)


def example_range_filter():
    """ 演示邮箱验证
    """
    resp = client.get("/range", data={
        "params": 8
    })
Example #21
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:53'
""" 演示 pre-request 框架验证字符串是否符合ipv6规则
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# ipv6,框架将验证入参是否符合ipv6规则
ipv6_params = {"p1": Rule(ipv6=True)}


@app.route("/ipv6", methods=["GET", "POST"])
@pre.catch(ipv6_params)
def example_ipv6_handler(params):
    return str(params)


def example_ipv6_filter():
    """ 演示ipv6格式判断能力
    """
    resp = client.get("/ipv6",
                      data={"p1": "CDCD:910A:2222:5498:8475:1111:3900:2020"})
    print(resp.data)
Example #22
0
    """ 自定义结果格式化函数

    :param code: 响应码
    :param msg: 响应消息
    """
    return {
        "code": code,
        "msg": "hello",
        "sss": "tt",
    }


app = Flask(__name__)
app.config["TESTING"] = True

filter_params = {"email": Rule(email=True)}


@app.route("/email", methods=['get', 'post'])
@pre.catch(filter_params)
def email_resp_handler(params):
    """ 测试邮件验证
    """
    return str(params)


class TestFormatter:
    def test_formatter(self):
        """ 测试自定义formatter
        """
        pre.add_formatter(custom_formatter)
Example #23
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-19 10:28'
""" 演示 pre-request 框架如何使用枚举校验
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定enum=[10, 20]指定目标枚举值,注意:目前仅支持同数据类型枚举验证
enum_params = {"params": Rule(type=int, enum=[10, 20, 30])}


@app.route("/enum", methods=["GET", "POST"])
@pre.catch(enum_params)
def example_enum_handler(params):
    return str(params)


def example_enum_filter():
    """ 演示枚举验证
    """
    resp = client.get("/enum", data={"params": 7})
    print(resp.json)

Example #24
0
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-27 15:44'
""" 演示 pre-request 框架如何使用等于、不等于判断
"""
import json

from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

equal_params = {"p1": Rule(type=int, eq=8), "p2": Rule(type=int, neq=8)}


@app.route("/equal", methods=["GET", "POST"])
@pre.catch(equal_params)
def example_equal_handler(params):
    return str(params)


def example_equal_filter():
    """ 演示等于、不等于判断
    """
    resp = client.get("/equal", data={"p1": 8, "p2": 9})
    print(resp.data)

    resp = client.get("/equal", data={"p1": 9, "p2": 9})
Example #25
0
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()


def json_resp(result):
    result = json.dumps(result)
    resp = make_response(result)
    resp.headers['Content-Type'] = 'application/json'
    return resp


args = {
    "p1": Rule(type=int, split=",", multi=True, required=True),
    "p2": Rule(split=",", trim=True, multi=True, lower=True),
    "p3": Rule(type=int, split=",", multi=True, lte=5)
}


@app.route("/split", methods=["GET", "POST"])
@pre.catch(args)
def split_handler(params):
    return json_resp(params)


class TestSplit:
    def test_split_smoke(self):
        """ 测试字符串分割能力
        """
Example #26
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:52'
""" 演示 pre-request 框架验证指定字符串后缀测试
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定endswith,验证字符串是否包含指定后缀
endswith_params = {"p1": Rule(endswith="abc")}


@app.route("/endswith", methods=["GET", "POST"])
@pre.catch(endswith_params)
def example_endswith_handler(params):
    return str(params)


def example_endswith_filter():
    """ 演示endswith字符串后缀能力
    """
    resp = client.get("/endswith", data={"p1": "Testabc"})
    print(resp.data)

    resp = client.get("/endswith", data={"p1": "Testac"})
Example #27
0
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-03-19 10:28'
""" 演示 pre-request 框架如何使用枚举校验
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定enum=[10, 20]指定目标枚举值,注意:目前仅支持同数据类型枚举验证
enum_params = {"params": Rule(direct_type=int, enum=[10, 20, 30])}


@app.route("/enum", methods=["GET", "POST"])
@pre.catch(enum_params)
def example_enum_handler(params):
    return str(params)


def example_enum_filter():
    """ 演示枚举验证
    """
    resp = client.get("/enum", data={"params": 10})
    print(resp.data)

Example #28
0
from flask import make_response

from pre_request import pre
from pre_request import Rule

app = Flask(__name__)


def json_resp(result):
    result = json.dumps(result)
    resp = make_response(result)
    resp.headers['Content-Type'] = 'application/json'
    return resp


email_params = {"email": Rule(email=True)}


@app.route("/email", methods=['get', 'post'])
@pre.catch(email_params)
def test_email_handler(params):
    """ 测试邮件验证
    """
    return json_resp(params)


g_params = {"email": Rule(email=True)}


@app.route("/g", methods=['get', 'post'])
@pre.catch(g_params)
Example #29
0
# (C) Wu Dong, 2020
# All rights reserved
# @Author: 'Wu Dong <*****@*****.**>'
# @Time: '2020-04-13 10:54'
""" 演示 pre-request 框架验证不同参数联动限制禁止相等
"""
import json
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()

# 指定gte_key, 禁止两个参数相等
gte_key_params = {"p1": Rule(type=int), "p2": Rule(type=int, gte_key="p1")}


@app.route("/gte/key", methods=["GET", "POST"])
@pre.catch(gte_key_params)
def example_gte_key_handler(params):
    return str(params)


def example_gte_key_filter():
    """ 演示gte_key包含函数
    """
    resp = client.get("/gte/key", data={"p1": 15, "p2": 13})
    print(json.loads(resp.data))

    resp = client.get("/gte/key", data={"p1": 15, "p2": 15})
Example #30
0
""" 演示 pre-request 框架如何使用回调函数自定义处理函数
"""
from flask import Flask
from pre_request import pre, Rule

app = Flask(__name__)
app.config["TESTING"] = True
client = app.test_client()


def call_back_handler(value):
    return value + 100


# 指定callback自定义处理函数,注意:此函数的调用在系统处理完之后
callback_params = {"params": Rule(direct_type=int, callback=call_back_handler)}


@app.route("/callback", methods=["GET", "POST"])
@pre.catch(callback_params)
def example_callback_handler(params):
    return str(params)


def example_callback_filter():
    """ 演示回调函数
    """
    resp = client.get("/callback", data={"params": 10})
    print(resp.data)