コード例 #1
0
def vlans(row_num, ws, var, var_value):
    if re.search(',', str(var_value)):
        vlan_split = var_value.split(',')
        for x in vlan_split:
            if re.search('\\-', x):
                dash_split = x.split('-')
                for z in dash_split:
                    if not validators.between(int(z), min=1, max=4095):
                        print(
                            f'\n-----------------------------------------------------------------------------\n'
                        )
                        print(
                            f'   Error on Worksheet {ws.title}, Row {row_num} {var}. Valid VLAN Values are:'
                        )
                        print(f'   between 1 and 4095.  Exiting....')
                        print(
                            f'\n-----------------------------------------------------------------------------\n'
                        )
                        exit()
            elif not validators.between(int(x), min=1, max=4095):
                print(
                    f'\n-----------------------------------------------------------------------------\n'
                )
                print(
                    f'   Error on Worksheet {ws.title}, Row {row_num} {var}. Valid VLAN Values are:'
                )
                print(f'   between 1 and 4095.  Exiting....')
                print(
                    f'\n-----------------------------------------------------------------------------\n'
                )
                exit()
    elif re.search('\\-', str(var_value)):
        dash_split = var_value.split('-')
        for x in dash_split:
            if not validators.between(int(x), min=1, max=4095):
                print(
                    f'\n-----------------------------------------------------------------------------\n'
                )
                print(
                    f'   Error on Worksheet {ws.title}, Row {row_num} {var}. Valid VLAN Values are:'
                )
                print(f'   between 1 and 4095.  Exiting....')
                print(
                    f'\n-----------------------------------------------------------------------------\n'
                )
                exit()
    elif not validators.between(int(var_value), min=1, max=4095):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(
            f'   Error on Worksheet {ws.title}, Row {row_num} {var}. Valid VLAN Values are:'
        )
        print(f'   between 1 and 4095.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #2
0
ファイル: lw2fabtotum.py プロジェクト: pisuke/lw2fabtotum
def main():

    show_title()

    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v",
                       "--verbose",
                       action="store_true",
                       default=False,
                       help="increase the verbosity level")
    parser.add_argument("-d",
                        "--debug",
                        action="store_true",
                        default=False,
                        help="print debug information")
    parser.add_argument("-i",
                        "--input",
                        default="input.gcode",
                        help="input gcode file name from LaserWeb")
    parser.add_argument("-o",
                        "--output",
                        default="output.gcode",
                        help="output gcode file name for the FABtotum")
    parser.add_argument(
        "-s",
        "--speed",
        default="500",
        help=
        "speed rate for laser head movement, it must be a number between 1 and 20000"
    )
    parser.add_argument(
        "-p",
        "--power",
        default="255",
        help="laser head power, it must be a number between 1 and 255")

    args = parser.parse_args()

    if args.verbose:
        print("program arguments:")
        print(args)
        print()

    if not validators.between(int(args.speed), min=1, max=20000):
        print("laser head speed must be between 1 and 20000")
        exit(1)

    if not validators.between(int(args.power), min=1, max=255):
        print("laser head power must be between 1 and 255")
        exit(1)

    lw2fabtotum(args.input, args.output, args.speed, args.power, args.verbose,
                args.debug)

    print()
コード例 #3
0
def hgt(val):
    height, units = int(val[:-2]), val[-2:]

    if units == "cm":
        return between(height, 150, 193)

    elif units == "in":
        return between(height, 59, 76)

    else:
        return False
コード例 #4
0
    def mutate_and_get_payload(self, root, info, **input):
        user = info.context.user
        require_login_and_permission(user, 'costasiella.add_financetaxrate')

        errors = []
        if not len(input['name']):
            print('validation error found')
            raise GraphQLError(_('Name is required'))

        # if not input['percentage'] and not input['percentage'] == 0:
        #     raise GraphQLError(_('Percentage is required'))

        if not validators.between(input['percentage'], 0, 100):
            raise GraphQLError(_('Percentage has to be between 0 and 100'))

        finance_tax_rate = FinanceTaxRate(
            name=input['name'], 
            percentage=input['percentage'],
            rate_type=input['rateType']
        )
        if input['code']:
            finance_tax_rate.code = input['code']

        finance_tax_rate.save()

        return CreateFinanceTaxRate(finance_tax_rate=finance_tax_rate)
コード例 #5
0
def filter_ports(row_num, ws, var, var_value):
    valid_count = 0
    if re.match(r'\d', var_value):
        if not validators.between(int(var_value), min=1, max=65535):
            valid_count = +1
    elif re.match(r'[a-z]', var_value):
        if not re.search(
                '^(dns|ftpData|http|https|pop3|rtsp|smtp|unspecified)$',
                var_value):
            valid_count = +1
    else:
        valid_count = +1
    if not valid_count == 0:
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(
            f'   Error on Worksheet {ws.title} Row {row_num}. {var} {var_value} did not'
        )
        print(f'   match allowed values. {var} can be:')
        print(f'    - dns')
        print(f'    - ftpData')
        print(f'    - http')
        print(f'    - https')
        print(f'    - pop3')
        print(f'    - rtsp')
        print(f'    - smtp')
        print(f'    - unspecified')
        print(f'    - or between 1 and 65535')
        print(f'   Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #6
0
 def validate_int_range(key, value, min, max):
     """
     Validates if a specifed integer falls in the specified range
     """
     if not validators.between(value, min=min, max=max):
         logger.error(
             "CONFIG: Validation error: {} should be between {} and {}.",
             key, min, max)
         raise ValidationError
コード例 #7
0
def test_get_entry_xelatex():
    """
    Test the get_entry function by reading the `test_input.xlsx` workbook
    reading the first (real) row, and producing an entry. We don't test
    dynamic fields such as date or note (release) exactly since these are prone
    to change, but rather that they are within expected ranges.
    """

    row = pytest.ws.__getitem__('2')
    entry = standardcitations.get_entry(row, True)

    assert entry['number'] == "36.101"
    assert entry['ID'] == '3gpp.{}'.format(entry['number'])
    assert entry['ENTRYTYPE'] == 'techreport'

    assert validators.between(int(entry['year']), min=2010)
    assert validators.between(int(entry['month']), min=1, max=12)
    assert validators.between(int(entry['day']), min=1, max=31)
コード例 #8
0
def send_server_information(ip, port, spread=True):
    # Validates the ip or domain (syntax only)
    if validators.domain(ip) is not True:
        if validators.ip_address.ipv4(ip) is not True:
            if validators.ip_address.ipv6(ip) is not True:
                print(
                    f"Failed to validate ip or domain: {ip}. Check for typing mistakes."
                )
                return False

    # Validates port number
    if validators.between(port, min=1, max=65535) is not True:
        print(f"Invalid port number: {port} is not between 1 and 65535")
        return False

    if not registry.exists(settings.ADDRESS_ID_REGISTRY):
        print(
            f"Address ID was not found in the registry! (Location: {settings.ADDRESS_ID_REGISTRY})"
        )
        return False
    if not registry.exists(settings.RSA_PRIVATE_REGISTRY):
        print(
            f"RSA Private Key was not found in the registry! (Location: {settings.RSA_PRIVATE_REGISTRY})"
        )
        return False
    address_id = registry.get_value(settings.ADDRESS_ID_REGISTRY)

    # Creates server message
    server_update_dict = dict(
        type=MessageType.SERVER_UPDATE,
        signature=0,
        address_id=address_id +
        1,  # Increases the address id, to indicate the information is new and up to date.
        address_size=len(ip),
        address=ip.encode("ascii"),
        port=port,
        spread=spread)

    # Calculate signature of message
    try:
        server_update_message = messages.SERVER_UPDATE_MESSAGE.build(
            server_update_dict)

        # Update signature
        server_update_dict["signature"] = messages.sign_message(
            server_update_message)
        server_update_message = messages.SERVER_UPDATE_MESSAGE.build(
            server_update_dict)
    except construct.ConstructError as e:
        # Should never occur
        print(f"Failed to build server update message: {e.args}")
        return False

    # Sends server information update (should also update local server information)
    updater.send_broadcast(server_update_message)
    print("Server information was sent to services!")
    return True
コード例 #9
0
 def validate_pages(self):
     if not self.args.pages:
         return Result.failure('Heri, provide please pages'
                               ' parameter or use --help ;)')
     for page in self.args.pages.split(','):
         if not validators.between(int(page), min=1, max=settings.MAX_PAGE):
             return Result.failure(f"{page} page out of range,"
                                   f" max is {settings.MAX_PAGE}")
     return Result.success()
コード例 #10
0
ファイル: environ.py プロジェクト: mkurnikov/typed-env
    def get_port(self, var, default=NOTSET):
        # type: (str, Union[int, NotSetType]) -> int
        value = self.get_int(var, default=default)
        
        if value == default:
            return value
        
        if not validators.between(value, min=0, max=65535):
            raise VariableTypeError('Environment variable {var} with value {val} is not a valid port.')

        return value
コード例 #11
0
def vpc_id(line_count, vpc_id):
    if not validators.between(int(vpc_id), min=1, max=1000):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(f'   Error on Row {line_count}. vpc_id "{vpc_id}" is invalid.')
        print(f'   A valid VPC ID is between 1 and 1000.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #12
0
def node_id(line_count, node_id):
    if not validators.between(int(node_id), min=101, max=4001):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(f'   Error on Row {line_count}. node_id "{node_id}" is invalid.')
        print(f'   A valid Node ID is between 101 and 4000.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #13
0
def port(line_count, port):
    if not validators.between(int(port), min=1, max=65535):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(f'   Error on Row {line_count}. Port {port} is invalid.')
        print(f'   A valid Port Number is between 1 and 65535.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #14
0
ファイル: recon-ape.py プロジェクト: maxpowersi/APE-ST
def validateParameters(parameters):
    if not validators.domain(parameters.target):
        print("The argument -t (target) is invalid, it must be a domain")
        sys.exit()
    if not os.path.exists(parameters.outputDir):
        print(
            "The argument -o (output dir) is invalid, it must be a valid path")
        sys.exit()
    if not validators.between(int(parameters.threads), min=1, max=50):
        print("The argument -q (queued) is invalid, min 1, max 500")
        sys.exit()
コード例 #15
0
def bgp_as(line_count, bgp_as):
    bgp_as = int(bgp_as)
    if not validators.between(int(bgp_as), min=1, max=4294967295):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(f'   Error on Row {line_count}. BGP AS "{bgp_as}" is invalid.')
        print(f'   A valid BGP AS is between 1 and 4294967295.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #16
0
ファイル: builtins.py プロジェクト: ffaraone/interrogatio
 def validate(self, value, context=None):
     try:
         if (
             value is not None and value != ''
             and validators.between(
                 value,
                 max=self.max,
             ) is not True
         ):
             raise ValidationError(message=self.message)
     except (TypeError, AssertionError):
         raise ValidationError(message=self.message)
コード例 #17
0
def retry(line_count, retry):
    if not validators.between(int(retry), min=1, max=5):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(f'   Error on Row {line_count}, The Retry shold be')
        print(
            f'   between 1 and 5.  "{retry}" does not meet this.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #18
0
ファイル: views.py プロジェクト: vycontrol/vycontrol
def instance_edit(request, hostname):

    if not validators.domain(hostname) and not validators.ipv4(hostname):
        return redirect('config:instances')

    vinfo = viewinfo.prepare(request, "Instance edit " + hostname)

    try:
        instance = Instance.objects.get(hostname=hostname)
    except Instance.DoesNotExist:
        return redirect('config:instances')

    if len(request.POST) > 0:
        error = False

        instance.alias = request.POST.get('alias').strip()
        instance.hostname = request.POST.get('hostname').strip()
        instance.port = request.POST.get('port').strip()
        try:
            port_number = int(instance.port)
        except:
            port_number = 0
        instance.key = request.POST.get('key').strip()

        if 'https' in request.POST:
            instance.https = True
        else:
            instance.https = False

        if not validator_letters_numbers(instance.alias):
            error = True
            vinfo.msg.add_error("Alias need to be letters and numbers only")
        if not validators.domain(instance.hostname) and not validators.ipv4(
                instance.hostname):
            error = True
            vinfo.msg.add_error("Hostname need to be only domain or ipv4")
        if not validator_letters_numbers(instance.key):
            error = True
            vinfo.msg.add_error("Key need to be letters and numbers only")
        if not validators.between(port_number, 1, 65535):
            error = True
            vinfo.msg.add_error("Port need to be between 1 and 65535")

        if error == False:
            instance.save()

    context = viewinfo.context(vinfo)
    localcontext = {
        'instance': instance,
    }
    context.update(localcontext)

    return render(request, 'config/instance_edit.html', context)
コード例 #19
0
def pod_id(line_count, name, pod_id):
    if not validators.between(int(pod_id), min=1, max=12):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(
            f'   Error on Row {line_count}. {name} pod_id {pod_id} is invalid.'
        )
        print(f'   A valid Pod ID is between 1 and 12.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #20
0
def node_id_apic(line_count, name, node_id):
    if not validators.between(int(node_id), min=1, max=7):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(
            f'   Error on Row {line_count}. APIC node_id "{node_id}" is invalid.'
        )
        print(f'   A valid Node ID is between 1 and 7.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #21
0
def inb_vlan(line_count, inb_vlan):
    if not validators.between(int(inb_vlan), min=2, max=4094):
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(
            f'   Error on Row {line_count}. Inband Vlan "{inb_vlan}" is invalid.'
        )
        print(f'   A valid Inband Vlan is between 2 and 4094.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #22
0
def site_group(row_num, ws, var, var_value):
    if re.search('Grp_', var_value):
        if not re.search('Grp_[A-F]', var_value):
            print(
                f'\n-----------------------------------------------------------------------------\n'
            )
            print(
                f'   Error on Worksheet {ws.title}, Row {row_num} {var}, Site_Group "{var_value}"'
            )
            print(
                f'   is invalid.  A valid Group Name is Grp_A thru Grp_F.  Exiting....'
            )
            print(
                f'\n-----------------------------------------------------------------------------\n'
            )
            exit()
    elif re.search(r'\d+', var_value):
        if not validators.between(int(var_value), min=1, max=12):
            print(
                f'\n-----------------------------------------------------------------------------\n'
            )
            print(
                f'   Error on Worksheet {ws.title}, Row {row_num} {var}, Site_Group "{var_value}"'
            )
            print(
                f'   is invalid.  A valid Site ID is between 1 and 12.  Exiting....'
            )
            print(
                f'\n-----------------------------------------------------------------------------\n'
            )
            exit()
    else:
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(
            f'   Error on Worksheet {ws.title}, Row {row_num} {var}, Site_Group "{var_value}"'
        )
        print(
            f'   is invalid.  A valid Site_Group is either 1 thru 12 or Group_A thru Group_F.'
        )
        print(f'   Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #23
0
def checkValueRange(rangeType, minValue, maxValue, database, table, field):
    """
    值域校验: 数值区间,字符in,日期范围,
    :param database: 校验数据库
    :param table: 校验数据表
    :param field: 校验列
    :return:
    """
    db = database
    tb = table
    fd = field
    accordValueRangeNum = 0
    sql = "SELECT " + fd + " from " + db + "." + tb
    dfData = pd.read_sql(sql, conn, chunksize=2000)
    # print(minValue,maxValue)

    # 检验该列数据的值域
    if rangeType == 'valueRange':
        for df in dfData:
            for d in df[fd]:
                if between(d, min=np.float(minValue), max=np.float(maxValue)):
                    accordValueRangeNum = accordValueRangeNum + 1
        return str(accordValueRangeNum)
    # 字符枚举
    elif rangeType == 'charIn':
        for df in dfData:
            for d in df[fd]:
                if d in [minValue, maxValue]:
                    accordValueRangeNum = accordValueRangeNum + 1
        return str(accordValueRangeNum)
    # 时间区间
    elif rangeType == 'dateIn':
        mindate = datetime.strptime(minValue, '%Y-%m-%d %H:%M:%S')
        maxdate = datetime.strptime(maxValue, '%Y-%m-%d %H:%M:%S')
        for df in dfData:
            for d in df[fd]:
                if mindate < d < maxdate:
                    accordValueRangeNum = accordValueRangeNum + 1
        return str(accordValueRangeNum)


# 访问示例127.0.0.1:5000/app03/checkValueRange/charIn/beijing/shanghai/datagovernance/testdata/address
# 访问示例127.0.0.1:5000/app03/checkValueRange/dateIn/2019-03-01 11:13:58/2019-04-04 11:13:58/datagovernance/testdata/dtime
# @app03.route('/')
# def show():
#     return 'app03.hello'
コード例 #24
0
ファイル: recon-ape.py プロジェクト: nh0va/APE
def parseArgs():
    parser = argparse.ArgumentParser(description="", version="0.12b")
    parser.add_argument('-t',
                        action="store",
                        dest="target",
                        help="the target to perform recon",
                        required=True)
    parser.add_argument('-o',
                        action="store",
                        dest="outputDir",
                        help="path to place all outputs",
                        required=True)
    parser.add_argument('-ip',
                        action="store",
                        dest="createIpFile",
                        help="resolve subdomains and generate IPs file",
                        required=True)
    parser.add_argument('-q',
                        action="store",
                        dest="threads",
                        help="number of threads to use",
                        required=True)
    parameters = parser.parse_args()

    if not validators.domain(parameters.target):
        print("The argument -t (target) is invalid, it must be a domain")
        sys.exit()

    if not os.path.exists(parameters.outputDir):
        print(
            "The argument -o (output dir) is invalid, it must be a valid path")
        sys.exit()

    if not parameters.createIpFile.lower() in ["true", "false"]:
        print(
            "The argument -ip (createIpFile) is invalid, it must be true or false"
        )
        sys.exit()

    if not validators.between(int(parameters.threads), min=1, max=50):
        print("The argument -q (queued) is invalid, min 1, max 500")
        sys.exit()

    return parameters
コード例 #25
0
ファイル: scan-ape.py プロジェクト: maxpowersi/APE-ST
def validateParameters(parameters):
    regexIP = '''^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)'''

    if not validators.domain(parameters.target) and re.search(
            regexIP, parameters.target) is None:
        print(
            "The argument -t (target) is invalid, it must be a domain, subdomain or IP "
        )
        #sys.exit()

    if not os.path.exists(parameters.outputDir):
        print(
            "The argument -o (output dir) is invalid, it must be a valid folder"
        )
        sys.exit()

    if not validators.between(int(parameters.queued), min=1, max=50):
        print("The argument -q (queued) is invalid, min 1, max 500")
        sys.exit()
コード例 #26
0
    def validate_socket(key, value: str):
        def error():
            message = "CONFIG: Validation error: {} for option {} is not a valid socket definition : <ip/hostname>:<port>"
            logger.error(message, value, key)
            raise ValidationError

        if ':' not in value:
            error()

        elems = value.split(":")
        if len(elems) != 2:
            error()

        ip, port = elems
        if not validators.ipv4(ip) and not validators.domain(
                ip) and ip != "localhost":
            error()

        if not validators.between(int(port), min=1, max=65535):
            error()
コード例 #27
0
def timeout(line_count, proto_timeout):
    timeout_count = 0
    if not validators.between(int(proto_timeout), min=5, max=60):
        timeout_count += 1
    if not (int(proto_timeout) % 5 == 0):
        timeout_count += 1
    if not timeout_count == 0:
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(
            f'   Error on Row {line_count}, Timeout should be between 5 and 60 and'
        )
        print(
            f'   be a factor of 5.  "{proto_timeout}" does not meet this.  Exiting....'
        )
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #28
0
ファイル: scan-ape.py プロジェクト: nh0va/APE
def parseArgs():
    parser = argparse.ArgumentParser(description="", version="0.12b")

    parser.add_argument('-t',action="store", dest="targets", help="list of IPs in scope, in a text file", required=True)
    parser.add_argument('-o', action="store", dest="outputDir", help="path to place all outputs", required=True)
    parser.add_argument('-q', action="store", dest="queued", help="number of queued, each queued will process one resource (IP or subdomain)", required=True)
    parameters = parser.parse_args()

    if not os.path.isfile(parameters.targets):
        print("The argument -t (targets) is invalid, it must be a text file with IPs or subdomains.")
        sys.exit()

    if not os.path.exists(parameters.outputDir):
        print("The argument -o (output dir) is invalid, it must be a valid folder")
        sys.exit()

    if not validators.between(int(parameters.queued), min=1, max=50):
        print("The argument -q (queued) is invalid, min 1, max 500")
        sys.exit()
    
    return parameters
コード例 #29
0
def timeout(row_num, ws, var, var_value):
    timeout_count = 0
    if not validators.between(int(var_value), min=5, max=60):
        timeout_count += 1
    if not (int(var_value) % 5 == 0):
        timeout_count += 1
    if not timeout_count == 0:
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        print(
            f'   Error on Worksheet {ws.title}, Row {row_num} {var}, {var_value}. '
        )
        print(
            f'   {var} should be between 5 and 60 and be a factor of 5.  "{var_value}" '
        )
        print(f'   does not meet this.  Exiting....')
        print(
            f'\n-----------------------------------------------------------------------------\n'
        )
        exit()
コード例 #30
0
    def mutate_and_get_payload(self, root, info, **input):
        user = info.context.user
        require_login_and_permission(user, 'costasiella.change_financetaxrate')

        rid = get_rid(input['id'])

        finance_tax_rate = FinanceTaxRate.objects.filter(id=rid.id).first()
        if not finance_tax_rate:
            raise Exception('Invalid Finance Tax Rate ID!')

        if not validators.between(input['percentage'], 0, 100):
            raise GraphQLError(_('Percentage has to be between 0 and 100'))

        finance_tax_rate.name = input['name']
        finance_tax_rate.percentage = input['percentage']
        finance_tax_rate.rate_type = input['rateType']
        if input['code']:
            finance_tax_rate.code = input['code']
        finance_tax_rate.save(force_update=True)

        return UpdateFinanceTaxRate(finance_tax_rate=finance_tax_rate)
コード例 #31
0
    def _ask(self, msg, default=None, regex=None, mandatory=True):
        """Allow to interact with user in CLI to fill missing values
        """
        while True:
            if default is not None:
                rep = input("{m} [{d}]: ".format(m=msg,d=default))
            else:
                rep = input("{m}: ".format(m=msg))
            
            if len(rep) is 0:
                if (default is None) and mandatory:
                    self.output('Sorry this value is mandatory.', level="ERROR")
                    continue
                rep = default
            
            # Do not check anything while fuzzing
            if (not self._fuzz) and (regex is not None):
                if (regex.lower() == 'domain') and not validators.domain(rep):
                    self.output('Sorry this value is invalid.', level="ERROR")
                    continue
                elif (regex.lower() == 'email') and not validators.email(rep):
                    self.output('Sorry this value is invalid.', level="ERROR")
                    continue
                elif (regex.lower() == 'ipv4') and not validators.ipv4(rep):
                    self.output('Sorry this value is invalid.', level="ERROR")
                    continue
                elif (regex.lower() == 'ipv6') and not validators.ipv6(rep):
                    self.output('Sorry this value is invalid.', level="ERROR")
                    continue
                elif (regex.lower() == 'port') and not validators.between(rep, min=1,max=65535):
                    self.output('Sorry this value is invalid.', level="ERROR")
                    continue
                elif (not re.match(regex, rep)):
                    self.output('Sorry this value is invalid.', level="ERROR")
                    continue

            break

        return rep
コード例 #32
0
 def setup_method(self, method):
     self.obj = validators.between(3, min=4, max=5)
コード例 #33
0
ファイル: x_validator.py プロジェクト: xiazhujie/x_validator
def arg_validator(arg, vlist=None):
    """
    检查数据,可对同一个数据进行多种检查

    arg : 字符串,要验证的参数
    vlist :  列表,验证列表,每个元素包含两项.
            第一个项是检查类型(字符串),第二项是可选参数字典,类似:
            [
                ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}),
                ("检查类型",{"可选参数1":参数值,"可选参数2":参数值...}),
            ...
            ]
    返回: 双元组,第一项为True 或 False,第二项为验证失败的类型(第一项为True的话第二项就留空)

    注意:
    vlist 列表的第一项可以是字符串 "required",用于表示是必填项:
        如果第一项不是,而且要验证的 arg 为空,会直接返回 True,不是的继续验证。
        如果第一项是,就完全按照 vlist[1:] 的要求验证
    vlist 的元素如果是验证整数/小数/email等不需要附加参数的可以直接传入验证类型字符串即可

    用例(使用args_validator函数的,看这里vdict每个键值对的形式):
    vdict = {
            "token": ["required", "uuid"],
            "username": ["required", ("length", {"min": 4, "max": 30}), "safe_str"],
            "password": ["required", ("length", {"min": 4, "max": 20}), "safe_str"],
            "captcha": ["required", ("length", {"min": 4, "max": 8}), "safe_str"],
        }
    form = args_validator(self.request.arguments, vdict)

    """
    if not any((isinstance(vlist, list), isinstance(vlist, tuple))):
        einfo = "不支持的数据类型!应使用列表或元组,但输入的是{}".format(type(vlist))
        raise ValueError(einfo)

    if vlist[0] == "required":
        # 第一项不是 required 的,把第一项的 "required" 去掉
        vlist = vlist[1:]
    else:
        # 第一项不是 required 的,如果 arg 是空的,直接返回 True,不是的继续验证
        if not arg:
            return True, None

    # 待返回的验证结果
    verification = None
    failed_type = None        # 验证失败的类型

    # 开始检查,有一个不通过就返回 False
    for i in vlist:
        local_verification = None
        if isinstance(i, str):  # 如果是字符串的话就改为元组
            i = (i, {})

        if len(i) == 1:         # 只有一个元素的,添加一个空字典
            i = (i[0], {})

        vtype = i[0]        # 检查类型是第一项
        vdict = i[1]        # 检查类型所需的可选参数字典

        # 在 validators 之外添加的
        # 没有空白
        if vtype == "no_space":
            if not re.search(r"\s", arg):
                local_verification = True
        # 安全字符串,只包含 0-9a-zA-Z-空格和下划线
        elif vtype == "safe_str":
            if re.match(r"^[0-9a-zA-Z-_ ]+$", arg, flags=re.U):
                local_verification = True

        # 是否包含
        elif vtype == "in":
            # 迭代 vdict 的键值(所以键名无所谓)
            for v in vdict.values():
                if arg not in v:
                    local_verification = False
                    break
        elif vtype == "not_in":
            # 迭代 vdict 的键值(所以键名无所谓)
            for v in vdict.values():
                if arg in v:
                    local_verification = False
                    break

        # 字符串形式的数字
        elif vtype == "str_number":
            if re.match(r"[+-]?\d+$", arg, flags=re.U) or \
                    re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U):
                local_verification = True
        elif vtype == "str_int":
            if re.match(r"[+-]?\d+$", arg, flags=re.U):
                local_verification = True
        elif vtype == "str_float":
            if re.match(r"[+-]?\d+\.\d+$", arg, flags=re.U):
                local_verification = True

        # 数字
        elif vtype == "number":     # 整数或浮点数都可以
            local_verification = isinstance(arg, int) or isinstance(arg, float)
        elif vtype == "int":
            local_verification = isinstance(arg, int)
        elif vtype == "float":
            local_verification = isinstance(arg, float)

        # 直接调用 validators的
        elif vtype == "length":
            local_verification = validators.length(arg, **vdict)
        elif vtype == "url":
            local_verification = validators.url(arg, **vdict)
        elif vtype == "email":
            local_verification = validators.email(arg, **vdict)
        elif vtype == "ip":       # ipv4 或 ipv6都可以
            local_verification = any((validators.ipv4(arg, **vdict),
                                      validators.ipv6(arg, **vdict)))
        elif vtype == "between":
            local_verification = validators.between(arg, **vdict)
        elif vtype == "uuid":
            local_verification = validators.uuid(arg, **vdict)
        elif vtype == "ipv4":
            local_verification = validators.ipv4(arg, **vdict)
        elif vtype == "ipv6":
            local_verification = validators.ipv6(arg, **vdict)
        elif vtype == "mac_address":
            local_verification = validators.mac_address(arg, **vdict)
        elif vtype == "iban":
            local_verification = validators.iban(arg, **vdict)
        elif vtype == "slug":
            local_verification = validators.slug(arg, **vdict)
        elif vtype == "truthy":
            local_verification = validators.truthy(arg, **vdict)

        # 对于验证不为真或没有验证的
        # 不为真的时候返回的是: ValidationFailure(......)
        if not local_verification:
            verification = False
            failed_type = vtype
            break                           # 有一条不为 True, 直接返回 False
        else:
            verification = True
    # 处理返回值
    if verification not in(False, True):
        verification = False
    if not verification:
        return verification, failed_type
    else:
        return True, None
コード例 #34
0
ファイル: test_between.py プロジェクト: adamchainz/validators
def test_returns_failed_validation_on_invalid_range(value, min, max):
    result = validators.between(value, min=min, max=max)
    assert isinstance(result, validators.ValidationFailure)
コード例 #35
0
ファイル: test_between.py プロジェクト: adamchainz/validators
def test_returns_true_on_valid_range(value, min, max):
    assert validators.between(value, min=min, max=max)
コード例 #36
0
ファイル: test_between.py プロジェクト: adamchainz/validators
def test_raises_assertion_error_for_invalid_args(value, min, max):
    with pytest.raises(AssertionError):
        assert validators.between(value, min=min, max=max)