Example #1
0
class PackRecipientsSchema(Schema):
    """Packed recipients schema."""

    enc = fields.Constant("xchacha20poly1305_ietf", required=True)
    typ = fields.Constant("JWM/1.0", required=True)
    alg = fields.Str(required=True)
    recipients = fields.List(fields.Nested(PackRecipientSchema()), required=True)
Example #2
0
class EmptyLineSchema(LineBaseSchema):
    prefix = fields.Constant("")
    content = fields.Constant([])

    @post_load
    def make_line(self, data, **kwargs) -> EmptyLine:
        return EmptyLine()
Example #3
0
 class __marshmallow__(Schema):
     debtor_id = fields.Integer()
     creditor_id = fields.Constant(ROOT_CREDITOR_ID)
     ts = fields.DateTime()
     seqnum = fields.Integer()
     negligible_amount = fields.Constant(HUGE_NEGLIGIBLE_AMOUNT)
     config_data = fields.String()
     config_flags = fields.Integer()
Example #4
0
    class Meta:
        """Marshmallow meta class."""

        include = {
            "@context":
            fields.Constant("http://iiif.io/api/image/2/context.json"),
            "@id": fields.String(attribute="links.iiif_info"),
            "profile":
            fields.Constant("http://iiif.io/api/image/2/level1.json"),
        }
Example #5
0
    class Meta:
        """Marshmallow meta class."""

        include = {
            "@context":
            fields.Constant("http://iiif.io/api/presentation/2/context.json"),
            # "@id": fields.String(attribute="links.iiif_annotation"), TODO
            "@type":
            fields.Constant("oa:Annotation"),
        }
Example #6
0
    class Meta:
        """Marshmallow meta class."""

        include = {
            "@context":
            fields.Constant("http://iiif.io/api/presentation/2/context.json"),
            "@type":
            fields.Constant("sc:Manifest"),
            "@id":
            fields.String(attribute="links.self_iiif_manifest"),
        }
Example #7
0
 class __marshmallow__(Schema):
     coordinator_type = fields.String(default=CT_ISSUING)
     coordinator_id = fields.Integer(attribute='debtor_id', dump_only=True)
     coordinator_request_id = fields.Integer()
     min_locked_amount = fields.Integer(attribute='amount', dump_only=True)
     max_locked_amount = fields.Integer(attribute='amount', dump_only=True)
     debtor_id = fields.Integer()
     creditor_id = fields.Constant(ROOT_CREDITOR_ID)
     recipient = fields.String()
     inserted_at = fields.DateTime(data_key='ts')
     max_commit_delay = fields.Constant(MAX_INT32)
     min_interest_rate = fields.Constant(-100.0)
class Elevations(Schema):
    """Main class for Elevations API schema

    Data Fields:

    :ivar version: A string containing v and an integer that specifies
        the version of the Bing Maps REST Services.
          - default: v1
    :ivar restApi: A part of the URL path that identifies the REST
        API.
          - default: 'Elevation' (for Elevations API services)
    :ivar resourcePath: A part of the URL path that specifies a
        resource, such as an address or landmark.

    This schema helps in creating the main parameters of all types of
    elevations API based services (List, Polyline, SeaLevel, Bounds). The
    above mentioned data fields make up the main parameters of the
    url.

    Example:
        The below example can show you a typical example for how the main URL
        parameters can be passed in as a dictionary
        ::

            >>> data = {'version': 'v1',
            ...         'restApi': 'Elevation',
            ...         'resourcePath': ''}

        When you dump an empty dictionary, the class helps you in filling the
        dictionary with default values. You can see the same behaviour in the
        below example:

        ::

            >>> data = {}
            >>> schema = Elevations()
            >>> schema.dump(data).data
            OrderedDict([('version', 'v1'), ('restApi', 'Elevation')])

    .. note:: Elevations class is common for all the elevations based services
        with the same default data.
    """
    version = fields.Constant('v1')
    restApi = fields.Constant('Elevation')
    resourcePath = fields.Str()

    class Meta:
        """Meta class helps in ordering all the fields in the specified order
        """
        fields = ('version', 'restApi', 'resourcePath')
        ordered = True
Example #9
0
class AttackResponseSerializer(Schema):
    type = fields.Constant('attack', dump_only=True)
    success = fields.Boolean()
    actor = fields.Nested(ActorSerializer)
    defender = fields.Nested(ActorSerializer)
    defender_alive = fields.Boolean()
    damage = fields.Integer()
class DollarLineSchema(LineBaseSchema):
    prefix = fields.Constant("$")
    content = fields.Function(
        lambda obj:
        [OneOfTokenSchema().dump(ValueToken.of(f" {obj.display_value}"))],
        lambda value: value,
    )
Example #11
0
    class Meta:
        """Marshmallow meta class."""

        include = {
            "@id": fields.String(attribute="links.iiif_api"),
            "@type": fields.Constant("dctypes:Image"),
        }
Example #12
0
    class Meta:
        """Marshmallow meta class."""

        include = {
            "@id": fields.String(attribute="links.self_iiif_sequence"),
            "@type": fields.Constant("sc:Sequence"),
        }
Example #13
0
class AnatTagsSchema(BaseSchema):
    datatype = fields.Constant("anat")

    suffix = fields.Str(validate=validate.OneOf(["T1w"]))
    extension = fields.Str(validate=validate.OneOf(["nii", "nii.gz"]))

    subject = fields.Str()
Example #14
0
    class Route(Schema):
        class Attributes(RouteSchema):
            pass

        id = fields.Str(required=True)
        attributes = fields.Nested(Attributes, required=True)
        type = fields.Constant('rule_chain')
Example #15
0
class ScholarlyArticle(CreativeWork):
    """Marshmallow schema for schema.org/ScholarlyArticle."""

    # TODO: Investigate if this should be the same as title
    headline = SanitizedUnicode(attribute='metadata.title')
    image = fields.Constant(
        'https://zenodo.org/static/img/logos/zenodo-gradient-round.svg')
class RelativeDeltaSchema(Schema):
    """Relative delta schema"""

    objectType = fields.Constant("RelativeDelta", data_key="__type")
    years = fields.Integer()
    months = fields.Integer()
    days = fields.Integer()
    leapdays = fields.Integer()
    hours = fields.Integer()
    minutes = fields.Integer()
    seconds = fields.Integer()
    microseconds = fields.Integer()
    year = fields.Integer()
    month = fields.Integer()
    day = fields.Integer()
    hour = fields.Integer()
    minute = fields.Integer()
    second = fields.Integer()
    microsecond = fields.Integer()

    @marshmallow.post_load
    def make_relative_delta(self, data, **kwargs):
        """Create relative delta based on data"""
        if "objectType" in data:
            del data["objectType"]

        return relativedelta.relativedelta(**data)
Example #17
0
class SNMPCommunity(BaseSchema):
    cast_to_dict = True

    type = _fields.Constant(constant="v1_v2_community")
    community = _fields.String(
        description="SNMP community (SNMP Versions 1 and 2c)", )

    @post_load
    def to_checkmk_str(self, data, **kwargs):
        return data["community"]

    @pre_dump
    def from_tuple(self, data, **kwargs):
        """

        v1 'community'
        v3 ('noAuthNoPriv', 'sicherheitsname')
        v3 ('authNoPriv', 'SHA-512', 'sicherheitsname', 'passwort')
        v3 ('authPriv', 'SHA-512', 'sicherheitsname', 'passwort', 'DES', 'privacypasswort')

           Args:
               data:
               **kwargs:

           Returns:

        """
        if isinstance(data, str):
            return {
                "type": "v1_v2_community",
                "community": data,
            }
Example #18
0
class CountsSchema(Schema):
    counts = fields.List(fields.Nested(CountSchema))
    version = fields.Constant(constant=SCHEMA_VERSION)

    @post_load
    def make_counts(self, data, **kwargs) -> Counts:
        return Counts(**data)
Example #19
0
class JSONLDBaseSchema(BaseSchema):
    id_key = "@id"
    # Serialization fields
    context = fields.Constant({"@vocab": "http://neurostore.org/nimads/"},
                              data_key="@context",
                              dump_only=True)
    _type = fields.Function(lambda model: model.__class__.__name__,
                            data_key="@type",
                            dump_only=True)

    # De-serialization fields
    id = fields.Method(None, "_extract_id", data_key=id_key, load_only=True)

    def _extract_id(self, iri):
        return iri.strip("/").split("/")[-1]

    @post_dump(pass_original=True)
    def process_jsonld(self, data, original, **kwargs):
        if isinstance(original, (list, tuple)):
            return data
        method = request.args.get("process", "compact")
        context = {"@context": {"@vocab": "http://neurostore.org/nimads/"}}
        if method == "flatten":
            return jsonld.flatten(data, context)
        elif method == "expand":
            return jsonld.expand(data)
        else:
            return jsonld.compact(data, context)
Example #20
0
class EventPaymentSentFailedSchema(EventPaymentSchema):
    event = fields.Constant("EventPaymentSentFailed")
    reason = fields.Str()
    target = AddressField()

    class Meta:
        fields = ("block_number", "event", "reason", "target", "log_time", "token_address")
Example #21
0
 class ExceptionSchema(Schema):
     code: fields.Constant = fields.Constant(  # type: ignore
         cls.__name__, example=cls.__name__, description='Код ошибки в PascalCase'
     )
     title = fields.String(
         required=False,
         allow_none=True,
         example=None,
         description='Заголовок ошибки для отображения на клиенте с учетом локализации.',
     )
     message = fields.String(
         required=True, example=cls.message, description='Сообщение об ошибке с учетом локализации.'
     )
     payload = fields.Dict(
         allow_none=True,
         required=True,
         example=None,
         description='Метаданные ошибки, могут содержать любые данные, '
         'необходимые клиенту для корректной обработки ошибки.',
     )
     debug = fields.String(
         required=False,
         allow_none=True,
         example=None,
         description='(необязательное поле) Подробная информация об ошибке, '
         'случившейся в серверном приложении. Приходит на клиент '
         'только в случае, если в серверном приложении включен DEBUG-режим.',
     )
Example #22
0
class RequestSchema(Schema):
    OPTIONS_CLASS = RequestOps

    len_data = fields.Constant(3)
    columns = fields.List(fields.String)
    data = fields.List(
        fields.List(fields.String),
        error_messages={'required': 'Field is mandatory.'})
    req_dict = fields.Method("build_dict", deserialize="build_dict", dump_only=False)
    
    @post_load
    def make_object(self, data):
        print "POST_LOAD", data
        data['as_dict'] = dict(zip(data.get('columns'), data.get('data')[0]))
        return data

    @validates_schema
    def validate_request(self, data):
        if self._unmarshal.errors:
            return
        req_columns = data['columns']
        req_data = data['data']
        if any(len(req_columns) != len(d) for d in req_data):
            raise ValidationError('columns and data must be of same size')

    def build_dict(self, obj):
        print "build_dict", obj
Example #23
0
class IPAddressRange(BaseSchema, CheckmkTuple):
    """

    >>> schema = IPAddressRange()
    >>> rv = schema.dump(('ip_range', ('127.0.0.1', '127.0.0.2')))
    >>> rv
    {'type': 'ip_range', 'from_address': '127.0.0.1', 'to_address': '127.0.0.2'}

    >>> schema.load(rv)
    ('ip_range', ('127.0.0.1', '127.0.0.2'))

    """

    tuple_fields = ("type", ("from_address", "to_address"))
    cast_to_dict = True

    type = _fields.Constant(
        description="A range of addresses.",
        constant="ip_range",
    )
    from_address = String(
        description="The first IPv4 address of this range.",
        validate=ValidateIPv4(),
    )
    to_address = String(
        description="The last IPv4 address of this range.",
        validate=ValidateIPv4(),
    )
Example #24
0
class BaseFuncTagsSchema(BaseSchema):
    datatype = fields.Constant("func")

    subject = fields.Str()
    session = fields.Str()
    run = fields.Str()
    task = fields.Str()
Example #25
0
class CredentialDefinitionSchema(OpenAPISchema):
    """Marshmallow schema for indy cred def."""

    ver = fields.Str(description="Node protocol version", **INDY_VERSION)
    ident = fields.Str(
        description="Credential definition identifier",
        data_key="id",
        **INDY_CRED_DEF_ID,
    )
    schemaId = fields.Str(
        description="Schema identifier within credential definition identifier",
        example=":".join(
            INDY_CRED_DEF_ID["example"].split(":")[3:-1]),  # long or short
    )
    typ = fields.Constant(
        constant="CL",
        description="Signature type: CL for Camenisch-Lysyanskaya",
        data_key="type",
        example="CL",
    )
    tag = fields.Str(
        description="Tag within credential definition identifier",
        example=INDY_CRED_DEF_ID["example"].split(":")[-1],
    )
    value = fields.Nested(
        CredDefValueSchema(),
        description="Credential definition primary and revocation values",
    )
Example #26
0
class AttachmentSchema(mm.SQLAlchemyAutoSchema):
    class Meta:
        model = Attachment
        fields = ('attachment_id', 'folder_id', 'type', 'attachment_type',
                  'title', 'filename', 'event_id', 'contribution_id',
                  'subcontribution_id', 'user', 'url', 'category_id',
                  'category_path', 'modified_dt')

    attachment_id = fields.Int(attribute='id')
    folder_id = fields.Int(attribute='folder_id')
    type = fields.Constant(SearchTarget.attachment.name)
    attachment_type = fields.String(attribute='type.name')
    filename = fields.String(attribute='file.filename')
    event_id = fields.Int(attribute='folder.event.id')
    contribution_id = fields.Method('_contribution_id')
    subcontribution_id = fields.Int(attribute='folder.subcontribution_id')
    user = fields.Nested(PersonSchema)
    category_id = fields.Int(attribute='folder.event.category_id')
    category_path = fields.List(
        fields.Nested(CategorySchema),
        attribute='folder.event.detailed_category_chain')
    url = fields.String(attribute='download_url')

    def _contribution_id(self, attachment):
        if attachment.folder.link_type == LinkType.contribution:
            return attachment.folder.contribution_id
        elif attachment.folder.link_type == LinkType.subcontribution:
            return attachment.folder.subcontribution.contribution_id
        return None
Example #27
0
class AlternateIdentifierSchema(Schema):
    def get_pid(self, pids):
        p = [p['value'] for p in pids if p['type'] == 'ePIC_PID']
        return str(p[0])

    alternateIdentifier = fields.Method('get_pid')
    alternateIdentifierType = fields.Constant('ePIC_PID')
Example #28
0
class EventNoteSchema(mm.SQLAlchemyAutoSchema):
    class Meta:
        model = EventNote
        fields = ('note_id', 'type', 'content', 'event_id', 'contribution_id',
                  'subcontribution_id', 'url', 'category_id', 'category_path',
                  'modified_dt', 'user', 'title')

    note_id = fields.Int(attribute='id')
    type = fields.Constant(SearchTarget.event_note.name)
    content = fields.Str(attribute='current_revision.source')
    title = fields.Str(attribute='object.title')
    contribution_id = fields.Method('_contribution_id')
    subcontribution_id = fields.Int()
    category_id = fields.Int(attribute='event.category_id')
    category_path = fields.List(fields.Nested(CategorySchema),
                                attribute='event.detailed_category_chain')
    url = fields.Function(
        lambda note: url_for('event_notes.view', note, _external=False))
    modified_dt = fields.DateTime(attribute='current_revision.created_dt')
    user = fields.Nested(PersonSchema, attribute='current_revision.user')

    def _contribution_id(self, note):
        if note.link_type == LinkType.contribution:
            return note.contribution_id
        elif note.link_type == LinkType.subcontribution:
            return note.subcontribution.contribution_id
Example #29
0
class WizardSchema(BaseSchema):
    xivo_uuid = fields.UUID(dump_only=True)
    admin_username = fields.Constant(constant='root', dump_only=True)
    admin_password = fields.String(validate=Regexp(ADMIN_PASSWORD_REGEX),
                                   required=True)
    license = StrictBoolean(validate=Equal(True), required=True)
    language = fields.String(validate=OneOf(['en_US', 'fr_FR']),
                             missing='en_US')
    entity_name = fields.String(validate=Length(min=3, max=64), required=True)
    timezone = fields.String(validate=Length(max=128), required=True)
    network = fields.Nested(WizardNetworkSchema, required=True)
    context_internal = fields.Nested(WizardContextInternalSchema,
                                     required=True)
    context_outcall = fields.Nested(WizardContextOutcallSchema,
                                    missing=WizardContextOutcallSchema().load(
                                        {}).data)
    context_incall = fields.Nested(WizardContextIncallSchema,
                                   missing=WizardContextIncallSchema().load(
                                       {}).data)

    @validates('entity_name')
    def validate_entity_name(self, entity_name):
        sub_name = ''.join(c for c in entity_name if c.isalnum())
        if len(sub_name) < 3:
            raise ValidationError(
                'Shorter than alphanumeric minimum length 3.')
Example #30
0
class EventPersonSchema(mm.SQLAlchemyAutoSchema):
    class Meta:
        model = EventPerson
        public_fields = ('id', 'identifier', '_title', 'email', 'affiliation',
                         'affiliation_link', 'affiliation_id',
                         'affiliation_meta', 'name', 'first_name', 'last_name',
                         'user_identifier')
        fields = public_fields + ('phone', 'address')

    type = fields.Constant('EventPerson')
    _title = EnumField(UserTitle, data_key='title')
    name = fields.String(attribute='full_name')
    user_identifier = fields.String(attribute='user.identifier')
    last_name = fields.String(required=True)
    email = fields.String(load_default='')
    affiliation_link = ModelField(Affiliation,
                                  data_key='affiliation_id',
                                  load_default=None,
                                  load_only=True)
    affiliation_id = fields.Integer(load_default=None, dump_only=True)
    affiliation_meta = fields.Nested(AffiliationSchema,
                                     attribute='affiliation_link',
                                     dump_only=True)

    @pre_load
    def handle_affiliation_link(self, data, **kwargs):
        # in some cases we get data that's already been loaded by PersonLinkSchema and thus no longer
        # has an affiliation_id but only an affiliation_link...
        data = data.copy()
        if affiliation_link := data.pop('affiliation_link', None):
            data['affiliation_id'] = affiliation_link.id
        return data