示例#1
0
class LicenseSchema(StructSchema):
    _STRUCT_CLS = data_structs.LicenseStruct
    open_access = fields.Boolean(default=True)
    title = fields.String()
    url = fields.URL()
    version = fields.String()
    type = fields.String()
class MapLayerSchema(Schema):
    """ Schema of map layers in UI campaign config
    """
    name = fields.Str(required=True)
    url = fields.URL(required=True)
    attribution = fields.Nested(AttributionSchema)
    presets = fields.List(fields.Str())
示例#3
0
class UserSchema(Schema):
    """User marshmallow schema"""
    _id = ObjectId()
    name = fields.Str(required=True,
                      validate=validate.Length(
                          min=1, error="User name cannot be empty."))
    surname = fields.Str(required=True,
                         validate=validate.Length(
                             min=1, error="User surname cannot be empty."))
    uid = fields.Str(required=True)
    location = fields.Nested(LocationSchema, required=True)
    email = fields.Email(required=True)
    facebook = fields.Str()
    google = fields.Str()
    photo = fields.URL()
    member_since = fields.Str()
    last_login = fields.Str()
    points = fields.Int()
    purchases = fields.Int()
    metadata = fields.Nested(UserMetadataSchema)

    @post_load
    def make_user(self, data):
        """Deserializes data into a User object"""
        return User(**data)
示例#4
0
class ImportV1DatasetSchema(Schema):
    # pylint: disable=no-self-use, unused-argument
    @pre_load
    def fix_extra(self, data: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]:
        """
        Fix for extra initially beeing exported as a string.
        """
        if isinstance(data.get("extra"), str):
            data["extra"] = json.loads(data["extra"])

        return data

    table_name = fields.String(required=True)
    main_dttm_col = fields.String(allow_none=True)
    description = fields.String(allow_none=True)
    default_endpoint = fields.String(allow_none=True)
    offset = fields.Integer()
    cache_timeout = fields.Integer(allow_none=True)
    schema = fields.String(allow_none=True)
    sql = fields.String(allow_none=True)
    params = fields.Dict(allow_none=True)
    template_params = fields.Dict(allow_none=True)
    filter_select_enabled = fields.Boolean()
    fetch_values_predicate = fields.String(allow_none=True)
    extra = fields.Dict(allow_none=True)
    uuid = fields.UUID(required=True)
    columns = fields.List(fields.Nested(ImportV1ColumnSchema))
    metrics = fields.List(fields.Nested(ImportV1MetricSchema))
    version = fields.String(required=True)
    database_uuid = fields.UUID(required=True)
    data = fields.URL()
示例#5
0
class PromptMessageSchema(Schema):
    text = fields.String(required=True, allow_none=True)
    media_url = fields.URL(allow_none=True)

    @post_load
    def make_prompt_message(self, data, **kwargs):
        return PromptMessage(**data)
示例#6
0
class LinksSchema(ma.SQLAlchemySchema):

    class Meta:
        model = Links
        load_instance = True

    id = ma.auto_field()
    long_url = fields.URL()
    short_postfix = fields.String(validate = validate.Regexp("^[{}]+$".format(digit_set)))
    count = ma.auto_field()
    short_link = AbsoluteUrlFor("linksresource", values=dict(short_postfix='<short_postfix>'))


    @pre_load
    def pre_process_postfix(self, data, **kwarg):
        if "short_postfix" in data and not "id" in data:
            if not match("^[{}]+$".format(digit_set), data['short_postfix']):
                raise  ValidationError("malformed url")
            id = BaseN.BaseNToDec(data['short_postfix'], digit_set)
            data['id'] = id
        return data

    @pre_dump
    def pre_dump_postfix(self, link, **kwargs):
        if not link.short_postfix and link.id:
            link.short_postfix = BaseN.DecToBaseN(link.id, digit_set)
        return link
示例#7
0
class PartySchema(BaseSchema):
    """
    Party schema mapped onto Party() class attributes
    """
    party_id = fields.Integer(dump_only=True, attribute='id')
    party_name = fields.String(
        required=True,
        validate=[
            validate.Length(
                min=4,
                error="Party name does not meet minimum length of 4 letters."),
            validate.Regexp(r'[a-zA-Z]',
                            error="Party name cannot contain number(s).")
        ])
    hq_address = fields.String(
        required=True,
        validate=[
            validate.Length(min=1,
                            error="Please provide party Headquarters address.")
        ])
    logo_url = fields.URL(required=True)

    @pre_load
    def lower_cased(self, data):
        """return the input names as lower case

        Args:
            data (dict): data list to get the input field

        Returns:
            dict: input field party name in lower case
        """

        data["party_name"] = data["party_name"].lower()
        return data
示例#8
0
class GithubRepoSchema(Schema):
    id = fields.Int(required=True)
    repo_name = fields.Str()
    full_name = fields.Str()
    language = fields.Str()
    description = fields.Str()
    repo_url = fields.URL()
示例#9
0
class EntitySchema(Schema):
    entity_registry_id = mfields.String(default=None, allow_none=True)
    registry_id = mfields.String(default=None, allow_none=True)
    archive_reason = mfields.Dict(allow_none=True)
    id = mfields.String()
    name = mfields.String(required=True, allow_none=False)
    created_at = mfields.String(load_only=True)
    modified_at = mfields.String(load_only=True)
    creator = mfields.Dict()
    custom_fields = mfields.Dict()
    fields = mfields.Dict(allow_none=False)
    schema = mfields.Nested("EntitySchemaSchema", allow_none=True)
    schema_id = mfields.Method("get_schema_id")
    aliases = mfields.List(mfields.String())
    folder_id = mfields.String(required=True, allow_none=True)
    # schema = mfields.Dict(allow_none=True)
    # schema
    # entity
    # archive_record
    # mfields
    # custommfields
    web_url = mfields.URL()

    class Meta:
        unknown = INCLUDE
        additional = ("id",)

    def get_schema_id(self, obj):
        if hasattr(obj, "schema_id") and obj.schema_id:
            return obj.schema_id
        elif hasattr(obj, "schema") and obj.schema:
            return obj.schema["id"]
示例#10
0
class MetadataSchemaV1(InvenioRecordMetadataSchemaV1Mixin,
                       DCObjectSchemaV1Mixin, StrictKeysMixin):
    """Schema for the record metadata."""
    ALLOWED_SCHEMAS = ACL_ALLOWED_SCHEMAS
    PREFERRED_SCHEMA = ACL_PREFERRED_SCHEMA

    owners = fields.List(fields.Int(), dump_only=True)
    abstract = MultilingualStringSchemaV1(required=True)
    description = MultilingualStringSchemaV1(required=True)
    contributors = SanitizedUnicode(required=False)
    event = fields.Nested(EventSchemaV1(), required=False)
    difficulty = SanitizedUnicode(required=True)
    license = SanitizedUnicode(required=True)
    formats = fields.Nested(FormatSchemaV1(many=True),
                            many=True,
                            required=False)
    source = fields.URL()

    @pre_load
    def set_owners(self, in_data, **kwargs):
        if current_user.is_authenticated:
            in_data['owners'] = [current_user.get_id()]
        return in_data

    class Meta:
        unknown = INCLUDE
示例#11
0
class EntrySchema(GenericSchema):
    category_id = fields.Integer()
    name = fields.String()
    author = fields.String()
    headline = fields.String()
    description = fields.String()
    url = fields.URL()
示例#12
0
class SCEPPayload(Payload):
    URL = fields.URL(attribute='url')
    Name = fields.String(attribute='name')
    # Subject = fields.Nested()
    Challenge = fields.String(attribute='challenge')
    Keysize = fields.Integer(attribute='key_size')
    CAFingerprint = fields.String(attribute='ca_fingerprint')
    KeyType = fields.String(attribute='key_type')
    KeyUsage = EnumField(KeyUsage, attribute='key_usage', by_value=True)
    # SubjectAltName = fields.Dict(attribute='subject_alt_name')
    Retries = fields.Integer(attribute='retries')
    RetryDelay = fields.Integer(attribute='retry_delay')

    @post_dump(pass_many=False)
    def wrap_payload_content(self, data: dict) -> dict:
        """SCEP Payload is silly and double wraps its PayloadContent item."""
        inner_content = {
            'URL': data.pop('URL', None),
            'Name': data.pop('Name'),
            'Challenge': data.pop('Challenge'),
            'Keysize': data.pop('Keysize'),
            'CAFingerprint': data.pop('CAFingerprint'),
            'KeyType': data.pop('KeyType'),
            'KeyUsage': data.pop('KeyUsage'),
            'Retries': data.pop('Retries'),
            'RetryDelay': data.pop('RetryDelay'),
        }

        data['PayloadContent'] = inner_content
        return data

    @post_load
    def make_payload(self, data: dict) -> models.SCEPPayload:
        return models.SCEPPayload(**data)
示例#13
0
class WebhookSchema(Schema):
    webhook_url = fields.URL(required=True)
    webhook_type = fields.Integer(validate=validate.OneOf(
        Webhook.HOOK_TYPES, error='invalid webhook type'))
    event_list = fields.List(
        fields.String(validate=validate.OneOf(
            action_types.action_map, error='not a valid event type'), ))
示例#14
0
class LocationArgs(mm.Schema):
    class Meta:
        rh_context = ('location', )

    name = fields.String(required=True)
    room_name_format = fields.String(required=True)
    map_url_template = fields.URL(schemes={'http', 'https'},
                                  allow_none=True,
                                  missing='')

    @validates('name')
    def _check_name_unique(self, name):
        location = self.context['location']
        query = Location.query.filter(
            ~Location.is_deleted,
            func.lower(Location.name) == name.lower())
        if location:
            query = query.filter(Location.id != location.id)
        if query.has_rows():
            raise ValidationError(_('Name must be unique'))

    @validates('room_name_format')
    def _check_room_name_format_placeholders(self, room_name_format):
        missing = {
            x
            for x in ('{building}', '{floor}', '{number}')
            if x not in room_name_format
        }
        if missing:
            # validated client-side, no i18n needed
            raise ValidationError('Missing placeholders: {}'.format(
                ', '.join(missing)))
示例#15
0
class StandardUpdatesSchema(Schema):
    uuid = fields.UUID()
    identification = fields.Str(example="ISO 9001:2015")
    publication_date = fields.Date()
    title = fields.Str()
    description = fields.Str()
    link = fields.URL()
    synchronized = fields.Bool()
示例#16
0
class SubappSchema(Schema):
    subappid = fields.Int(dump_only=True)
    subappsid = fields.Str(required=True, validate=validate.Length(equal=3))
    subappurl = fields.URL(required=False)
    subappdesc = fields.Str(required=False,
                            validate=validate.Length(min=3, max=255))
    createdAt = fields.DateTime(dump_only=True)
    updatedAt = fields.DateTime(dump_only=True)
示例#17
0
class CategorySchema(BaseSchema):
    __model__ = Category

    id = fields.Integer()
    name = fields.String(required=True, allow_none=False)
    image_url = fields.URL(required=False, allow_none=True)

    folders = fields.Nested(FolderSchema, many=True, dump_only=True)
示例#18
0
class SocialSchema(Schema):
    email = fields.Email()
    fan_page = fields.Str()
    instagram = fields.Str()
    line = fields.Str()
    telephone = fields.Str()
    website = fields.URL()
    youtube = fields.Str()
class ScrapeRequestSchema(Schema):
    app_name = fields.Str(required=True)
    app_store_url = fields.URL(required=True)

    @validates('app_store_url')
    def validate_app_store_url(self, value):
        if not value.startswith(u'https://itunes.apple.com/'):
            raise ValidationError(u'only itunes URLs are allowed')
示例#20
0
class VmCustomFieldsSchema(Schema):
    cf_itsop = fields.Str(allow_none=True)
    cf_itsop_url = fields.URL(allow_none=True)
    cf_sync_key = fields.UUID(allow_none=True)

    @post_load
    def make_custom_fields(self, data, **kwargs):
        return VmCustomFields(**data)
示例#21
0
class PeerSchema(NETunnelSchema):
    id = fields.Integer()
    name = fields.String(required=True)
    target_netunnel_url = fields.URL(required=True)
    auth_data = fields.Dict(required=True,
                            keys=fields.String(),
                            values=fields.String())
    static_tunnels = fields.List(fields.Nested(StaticTunnelSchema))
class RespiratorQueryArgsSchema(Schema):
    url = fields.URL(required=False,
                     metadata={"description": "Respirator Site URL"})

    class Meta:
        # This is needed otherwise the schema validation will
        # fail with the pagination parameters
        unknown = EXCLUDE
示例#23
0
class WordCountSchema(Schema):
    '''Serialize json'''
    word = fields.String(required=True, validate=validate.Regexp('^[a-zA-Z0-9]+$', 0,'Word must be alphanumeric'))
    url = fields.URL(required=True, relative=False, require_tld=False) #check without .

    @post_load
    def create_object(self, data):
        return WordCountModel(**data)
示例#24
0
class ClusterSchema(Schema):
    id = fields.Int()
    name = fields.Str(required=True, validate=validate.Length(min=1, max=100))
    url = fields.URL()

    @post_load
    def make_cluster(self, data, **kwargs):
        return Cluster(**data)
示例#25
0
class LaunchSchema(Schema):
    launch_id = fields.Integer(attribute="id")
    title = fields.String()
    description = fields.String()
    version = fields.String()
    action_title = fields.String()
    action = fields.String()
    launch_image_url = fields.URL()
示例#26
0
class PublishSchema(Schema):
    regex_for_published_date = r"Jan?|Feb?|Mar?|Apr?|May|Jun?|Jul?|Aug?|Sep?|Oct?|Nov?|Dec?\s+\d{1,2}"
    regex_for_path = r"^(.+)\/([^/]+)$"
    user_schema = UserSchema()

    type_of = fields.Str(
        required=True,
        allow_none=False,
    )
    id = fields.Int(
        required=True,
        allow_none=False,
    )
    title = fields.Str(required=True, allow_none=False)
    description = fields.Str(required=True, allow_none=False)
    readable_publish_date = fields.Str(
        required=True,
        allow_none=False,
        validate=validate.Regexp(regex_for_published_date))
    slug = fields.Str(
        required=True,
        allow_none=False,
    )
    path = fields.Str(required=True,
                      allow_none=False,
                      validate=validate.Regexp(regex_for_path))
    url = fields.Str(
        required=True,
        allow_none=False,
        validate=validate.URL(error="Not a valid URL for url field"))
    comments_count = fields.Int(required=True, allow_none=False)
    positive_reactions_count = fields.Int(required=True, allow_none=False)
    collection_id = fields.Int(required=True, allow_none=True)
    published_timestamp = fields.DateTime(required=True, allow_none=False)
    cover_image = fields.URL(required=True, allow_none=True)
    social_image = fields.URL(required=True)
    canonical_url = fields.URL(required=True)
    created_at = fields.DateTime(required=True, allow_none=False)
    edited_at = fields.DateTime(required=True, allow_none=True)
    crossposted_at = fields.DateTime(required=True, allow_none=True)
    published_at = fields.DateTime(required=True, allow_none=False)
    last_comment_at = fields.DateTime(required=True, allow_none=True)
    tag_list = fields.List(fields.Str, required=True, allow_none=True)
    tags = fields.Str(required=True, allow_none=True)
    user = fields.Nested(user_schema)
示例#27
0
class RulingSchema(Schema):
    ruling = fields.Str()
    ruling_slug = fields.Str()
    canonical_ruling_graphic = fields.URL()

    @post_load
    def make_ruling(self, data):
        return Ruling(data['ruling'], data['ruling_slug'],
                      data['canonical_ruling_graphic'])
示例#28
0
class TokenSchema(SchemaBase):
    """Schema class to validate tokens."""
    api_key = fields.Str(description='The token API key - uniquely identifies the token')
    name = fields.Str(description='The token name')
    is_admin = fields.Boolean(description='Is this an admin token?')
    is_blocked = fields.Boolean(description='Is this token blocked?')
    token_uses = fields.Int(description='How many times has this token been used?')
    last_access = fields.DateTime(description='Last time this token was used')
    callback_url = fields.URL(description='A request will be made to this URL every time the token is used')
示例#29
0
class PrimaryIPv4InterfaceSchema(Schema):
    id = fields.Int()
    family = fields.Int()
    url = fields.URL()
    address = IPv4Interface(required=True)

    @post_load
    def make_ipv4(self, data, **kwargs):
        return IPv4Interface(**data)
示例#30
0
class UrlSchema(Schema):
    """URL schema."""
    class Meta:
        """Meta attributes for the schema."""

        unknown = EXCLUDE

    description = MultilingualStringV2()
    value = fields.URL(required=True)