Пример #1
0
    class _Schema(Schema):
        n_classes = fields.Int(required=True,
                               description='Number of classes',
                               example=2)
        learning_rate = fields.Float(
            missing=None,
            description='Learning rate used in training.',
            example=0.01)
        loss = fields.String(missing='cross_entropy',
                             description='Loss function used for training.',
                             validate=OneOf(segmentation_losses.keys()))
        metrics = fields.List(
            fields.String,
            missing=['accuracy', 'iou'],
            description='List of metrics used for evaluation.',
            validate=ContainsOnly(segmentation_metrics.keys()))

        class_weights = fields.Dict(
            missing=None,
            description='Dictionary mapping class id with weight. '
            'If key for some labels is not specified, 1 is used.')

        prediction_visualization = fields.Bool(
            missing=False,
            description='Record prediction visualization summaries.')
        prediction_visualization_num = fields.Int(
            missing=5,
            description='Number of images used for prediction visualization.')
Пример #2
0
class AccountSchema(BaseSchema):
    username = fields.Str(
        required=True,
        validate=[
            Range(
                min=USERNAME_MIN,
                max=USERNAME_MAX,
                error='Got: {input} as input, should be between {min} - {max}.'
            ),
            Regexp(regex=USERNAME_REGEX,
                   error="'{input}' not matching to '{regex}'")
        ])

    password = fields.Str(
        required=True,
        validate=[
            Range(
                min=USERNAME_MIN,
                max=USERNAME_MAX,
                error='Got: {input} as input, should be between {min} - {max}.'
            ),
            Regexp(regex=PASSWORD_REGEX,
                   error="'{input}' not matching to '{regex}'")
        ])

    firstName = fields.Str(
        required=True,
        validate=[
            Range(
                min=FIRSTNAME_MIN,
                max=FIRSTNAME_MAX,
                error='Got: {input} as input, should be between {min} - {max}.'
            ),
            Regexp(regex=FIRSTNAME_REGEX,
                   error="'{input}' not matching to '{regex}'")
        ])

    lastName = fields.Str(
        required=True,
        validate=[
            Range(
                min=LASTNAME_MIN,
                max=LASTNAME_MAX,
                error='Got: {input} as input, should be between {min} - {max}.'
            ),
            Regexp(regex=LASTNAME_REGEX,
                   error="'{input}' not matching to '{regex}'")
        ])

    email = fields.Email(required=True, error='Email not valid')
    dateOfBirth = fields.Date(
        required=True,
        error='Not valid date. Provide ISO8601-formatted date string.')
    acceptTermsOfService = fields.Bool(required=True,
                                       validate=[ContainsOnly(choices='True')])
Пример #3
0
class UserLoginSchema(Schema):
    """用户登录表单"""

    CATEGORY_FACE = 1
    CATEGORY_CARD = 2

    username = fields.String(
        required=True
    )  # required表示这个字段必须要有,然后会先转换对应的类型,再通过validate函数验证。required, 默认为False。
    password = fields.String(required=True, validate=lambda x: len(x) > 0)

    phone = fields.Method('get_prefix_phone_code')  # 直接通过方法
    prefix_phone_code = fields.Function(convert_prefix_phone_code)  # 也可以通过函数

    val1 = fields.Integer(
        required=False, missing=5,
        allow_none=True)  # 如果没有出现在表单里,则给它默认值 5;以及允许None值, missing用于load。
    val2 = fields.Integer(required=True, validate=OneOf([5, 10,
                                                         20]))  # 值要在这个里面
    val3 = fields.Integer(required=False,
                          default=5)  # 使用dump时,默认值是用default表示; missing 用于load.

    created_at = fields.DateTime(format='iso')  # 或者是iso格式的时间
    end_at = fields.DateTime(format='%Y-%m-%d %H:%M:%S')  # 或者是标准时间格式

    platform_ids = fields.List(fields.Integer(), required=True)  # 还可以是list
    # 对于list类型,要求只能包含哪些内容
    category_id = fields.List(
        fields.Integer(),
        required=True,
        validate=ContainsOnly(choices=(
            CATEGORY_FACE,
            CATEGORY_CARD,
            # CATEGORY_IMAGE, CATEGORY_BODY,
            # CATEGORY_FACE_V2, CATEGORY_CARD_V2
        )))

    # 如果是load时,则参数会是原来传进来的dict
    # 如果是dump时,则参数会是传进来的object
    def get_prefix_phone_code(self, obj):
        return convert_prefix_phone_code(obj.parent_end_user)

    @post_load
    def post_load_func(self, data):
        """这个修饰器很好用,表示格式化之后,调用这个函数"""
        data.val1 = 2333
        return data
Пример #4
0
def _load_app_options(env: Env):
    from octokit.utils import get_json_data as octokit_get_json_data

    global APP_NAME, APP_DESCRIPTION, APP_ORGANIZATION, APP_PUBLIC
    global APP_DEFAULT_EVENTS, APP_DEFAULT_PERMISSIONS

    valid_events = octokit_get_json_data("events.json")

    with env.prefixed("APP_"):
        APP_NAME = env.str("NAME", "gh-app")
        APP_DESCRIPTION = env.str("DESCRIPTION", "")
        APP_ORGANIZATION = env.str("ORGANIZATION", None)
        APP_PUBLIC = env.bool("PUBLIC", True)
        with env.prefixed("DEFAULT_"):
            APP_DEFAULT_EVENTS = env.list("EVENTS",
                                          "push",
                                          validate=ContainsOnly(valid_events))
            APP_DEFAULT_PERMISSIONS = env.dict("PERMISSIONS", "metadata=read")
Пример #5
0
class ParamSchema(Schema):
    class Meta:
        unknown = EXCLUDE

    admin_pw = Str(required=True)

    city = Str(required=True)

    country_code = Str(
        validate=[
            Length(2, 2),
            Predicate(
                "isupper",
                error="Non-uppercased characters aren't allowed",
            ),
        ],
        required=True,
    )

    email = Email(required=True)

    hostname = Str(required=True)

    org_name = Str(required=True)

    state = Str(required=True)

    optional_scopes = List(
        Str(),
        validate=ContainsOnly(OPTIONAL_SCOPES),
        missing=[],
    )

    ldap_pw = Str(missing="", default="")

    sql_pw = Str(missing="", default="")

    couchbase_pw = Str(missing="", default="")

    couchbase_superuser_pw = Str(missing="", default="")

    auth_sig_keys = Str(missing="")

    auth_enc_keys = Str(missing="")

    @validates("hostname")
    def validate_fqdn(self, value):
        fqdn = FQDN(value)
        if not fqdn.is_valid:
            raise ValidationError("Invalid FQDN format.")

    @validates("admin_pw")
    def validate_password(self, value, **kwargs):
        if not PASSWD_RGX.search(value):
            raise ValidationError(
                "Must be at least 6 characters and include "
                "one uppercase letter, one lowercase letter, one digit, "
                "and one special character."
            )

    @validates_schema
    def validate_ldap_pw(self, data, **kwargs):
        if "ldap" in data["optional_scopes"]:
            try:
                self.validate_password(data["ldap_pw"])
            except ValidationError as exc:
                raise ValidationError({"ldap_pw": exc.messages})

    @validates_schema
    def validate_ext_persistence_pw(self, data, **kwargs):
        err = {}
        scope_attr_map = [
            ("sql", "sql_pw"),
            ("couchbase", "couchbase_pw"),
        ]

        for scope, attr in scope_attr_map:
            # note we don't enforce custom password validation as cloud-based
            # databases may use password that not conform to our policy
            # hence we simply check for empty password only
            if scope in data["optional_scopes"] and data[attr] == "":
                err[attr] = ["Empty password isn't allowed"]

        if err:
            raise ValidationError(err)
Пример #6
0
class HealthSchema(Schema):
    status = fields.String(validate=ContainsOnly(choices=["ok", "error"]), )