How to use the marshmallow.fields.Method function in marshmallow

To help you get started, we’ve selected a few marshmallow examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github indico / indico / indico / modules / rb / schemas.py View on Github external
end_dt = DateTime()


class ReservationOccurrenceSchema(mm.ModelSchema):
    reservation = Nested(ReservationSchema)
    state = EnumField(ReservationState)
    start_dt = NaiveDateTime()
    end_dt = NaiveDateTime()

    class Meta:
        model = ReservationOccurrence
        fields = ('start_dt', 'end_dt', 'is_valid', 'reservation', 'rejection_reason', 'state')


class ReservationOccurrenceSchemaWithPermissions(ReservationOccurrenceSchema):
    permissions = Method('_get_permissions')

    class Meta:
        fields = ReservationOccurrenceSchema.Meta.fields + ('permissions',)

    def _get_permissions(self, occurrence):
        methods = ('can_cancel', 'can_reject')
        admin_permissions = None
        user_permissions = {x: getattr(occurrence, x)(session.user, allow_admin=False) for x in methods}
        if rb_is_admin(session.user):
            admin_permissions = {x: getattr(occurrence, x)(session.user) for x in methods}
        return {'user': user_permissions, 'admin': admin_permissions}


class ReservationConcurrentOccurrenceSchema(ReservationOccurrenceSchema):
    reservations = Nested(ReservationSchema, many=True)
github inspirehep / inspire-next / inspirehep / modules / records / serializers / schemas / latex / __init__.py View on Github external
from __future__ import absolute_import, division, print_function

from marshmallow import Schema, fields
from inspire_utils.name import format_name
from ...fields_export import get_best_publication_info

import datetime


class LatexSchema(Schema):
    arxiv_eprints = fields.Raw()
    authors = fields.Method('get_author_names')
    citations = fields.Method('get_citations', default=0)
    collaborations = fields.Method('get_collaborations')
    dois = fields.Raw()
    publication_info = fields.Method('get_publication_info')
    report_numbers = fields.Raw()
    titles = fields.Raw()
    texkeys = fields.Method('get_texkey')
    today = fields.Method('get_current_date')

    def get_citations(self, data):
        citations = data.get('citation_count')

        if citations is None:
            return data.get_citations_count()

        return citations

    def get_author_names(self, data):
        authors = data.get("authors")
github zenodo / zenodo / zenodo / modules / records / serializers / schemas / legacyjson.py View on Github external
'dump_publication_type',
        attribute='resource_type.subtype',
        validate=validate.OneOf(
            choices=ObjectType.get_subtypes('publication')),
    )
    image_type = fields.Method(
        'dump_image_type',
        attribute='resource_type.subtype',
        validate=validate.OneOf(choices=ObjectType.get_subtypes('image')),
    )
    openaire_type = fields.Method(
        'dump_openaire_type',
        attribute='resource_type.openaire_subtype'
    )

    license = fields.Method('dump_license', 'load_license')
    communities = fields.Method('dump_communities', 'load_communities')
    grants = fields.Method('dump_grants', 'load_grants')

    prereserve_doi = fields.Method('dump_prereservedoi', 'load_prereservedoi')

    journal_title = SanitizedUnicode(attribute='journal.title')
    journal_volume = SanitizedUnicode(attribute='journal.volume')
    journal_issue = SanitizedUnicode(attribute='journal.issue')
    journal_pages = SanitizedUnicode(attribute='journal.pages')

    conference_title = SanitizedUnicode(attribute='meeting.title')
    conference_acronym = SanitizedUnicode(attribute='meeting.acronym')
    conference_dates = SanitizedUnicode(attribute='meeting.dates')
    conference_place = SanitizedUnicode(attribute='meeting.place')
    conference_url = SanitizedUrl(attribute='meeting.url')
    conference_session = SanitizedUnicode(attribute='meeting.session')
github infobyte / faraday / faraday / server / api / modules / vulns.py View on Github external
class VulnerabilitySchema(AutoSchema):
    _id = fields.Integer(dump_only=True, attribute='id')

    _rev = fields.String(dump_only=True, default='')
    _attachments = fields.Method(serialize='get_attachments', deserialize='load_attachments', default=[])
    owned = fields.Boolean(dump_only=True, default=False)
    owner = PrimaryKeyRelatedField('username', dump_only=True, attribute='creator')
    impact = SelfNestedField(ImpactSchema())
    desc = fields.String(attribute='description')
    description = fields.String(dump_only=True)
    policyviolations = fields.List(fields.String,
                                   attribute='policy_violations')
    refs = fields.List(fields.String(), attribute='references')
    issuetracker = fields.Method(serialize='get_issuetracker', dump_only=True)
    parent = fields.Method(serialize='get_parent', deserialize='load_parent', required=True)
    parent_type = MutableField(fields.Method('get_parent_type'),
                               fields.String(),
                               required=True)
    tags = PrimaryKeyRelatedField('name', dump_only=True, many=True)
    easeofresolution = fields.String(
        attribute='ease_of_resolution',
        validate=OneOf(Vulnerability.EASE_OF_RESOLUTIONS),
        allow_none=True)
    hostnames = PrimaryKeyRelatedField('name', many=True, dump_only=True)
    service = fields.Nested(ServiceSchema(only=[
        '_id', 'ports', 'status', 'protocol', 'name', 'version', 'summary'
    ]), dump_only=True)
    host = fields.Integer(dump_only=True, attribute='host_id')
    severity = SeverityField(required=True)
    status = fields.Method(
        serialize='get_status',
        validate=OneOf(Vulnerability.STATUSES + ['opened']),
github zenodo / zenodo / zenodo / modules / records / serializers / schemas / csl.py View on Github external
type = fields.Method('get_type')
    title = fields.Str(attribute='metadata.title')
    abstract = fields.Str(attribute='metadata.description')
    author = fields.List(fields.Nested(AuthorSchema),
                         attribute='metadata.creators')
    issued = fields.Method('get_issue_date')
    language = fields.Str(attribute='metadata.language')
    version = fields.Str(attribute='metadata.version')
    note = fields.Str(attribute='metadata.notes')

    DOI = fields.Str(attribute='metadata.doi')
    ISBN = fields.Str(attribute='metadata.imprint.isbn')
    ISSN = fields.Method('get_issn')

    container_title = fields.Method('get_container_title')
    page = fields.Method('get_pages')
    volume = fields.Str(attribute='metadata.journal.volume')
    issue = fields.Str(attribute='metadata.journal.issue')

    publisher = fields.Method('get_publisher')
    publisher_place = fields.Str(attribute='metadata.imprint.place')

    def get_journal_or_part_of(self, obj, key):
        """Get journal or part of."""
        m = obj['metadata']
        journal = m.get('journal', {}).get(key)
        part_of = m.get('part_of', {}).get(key)

        return journal or part_of or missing

    def get_container_title(self, obj):
        """Get container title."""
github CERNDocumentServer / cds-videos / cds / modules / records / serializers / schemas / project.py View on Github external
description = fields.Str()
    category = fields.Str(required=True)
    type = fields.Str(required=True)
    note = fields.Str()

    recid = fields.Number()
    _access = fields.Nested(AccessSchema)
    _buckets = fields.Nested(BucketSchema)
    _oai = fields.Nested(OaiSchema)
    _eos_library_path = fields.Str()
    contributors = fields.Nested(ContributorSchema, many=True, required=True)
    doi = DOI()
    keywords = fields.Nested(KeywordsSchema, many=True)
    license = fields.Nested(LicenseSchema, many=True)
    schema = fields.Str(attribute='$schema', dump_to='$schema')
    videos = fields.Method(deserialize='get_videos_refs')
    translations = fields.Nested(TranslationsSchema, many=True)
    report_number = fields.List(fields.Str, many=True)
    publication_date = fields.Str()
    external_system_identifiers = fields.Nested(
        ExternalSystemIdentifiersField, many=True)


    @post_load(pass_many=False)
    def post_load(self, data):
        """Post load."""
        data['$schema'] = current_jsonschemas.path_to_url(Project._schema)
        return data

    def get_videos_refs(self, obj):
        """Get videos references."""
        return [Project.build_video_ref(
github zenodo / zenodo / zenodo / modules / records / serializers / schemas / marc21.py View on Github external
lambda o: dict(copyright_status=o['metadata'].get('access_right')))

    publication_distribution_imprint = fields.Method(
        'get_publication_distribution_imprint')

    funding_information_note = fields.Function(
        lambda o: [dict(
            text_of_note=v.get('title'),
            grant_number=v.get('code')
        ) for v in o['metadata'].get('grants', [])])

    other_standard_identifier = fields.Method('get_other_standard_identifier')

    added_entry_meeting_name = fields.Method('get_added_entry_meeting_name')

    main_entry_personal_name = fields.Method('get_main_entry_personal_name')

    added_entry_personal_name = fields.Method('get_added_entry_personal_name')

    summary = fields.Function(
        lambda o: dict(summary=o['metadata'].get('description')))

    host_item_entry = fields.Method('get_host_item_entry')

    dissertation_note = fields.Function(
        lambda o: dict(name_of_granting_institution=o[
            'metadata'].get('thesis', {}).get('university')))

    language_code = fields.Function(
        lambda o: dict(language_code_of_text_sound_track_or_separate_title=\
                       o['metadata'].get('language')))
github CERNDocumentServer / cds-videos / cds / modules / records / serializers / schemas / datacite.py View on Github external
title = fields.Str(attribute='title')


class DateSchema(Schema):
    """Date schema."""

    date = fields.Str(attribute='date')
    dateType = fields.Str(attribute='type')


class DataCiteSchemaV1(Schema):
    """DataCite schema v1."""

    creators = fields.Method('get_creators')
    dates = fields.Method('get_dates')
    descriptions = fields.Method('get_descriptions')
    identifier = fields.Nested(IdentifierSchema, attribute='metadata.doi')
    language = fields.Str(attribute='metadata.language')
    publicationYear = fields.Method('get_publication_year')
    publisher = fields.Constant('CERN')
    resourceType = fields.Method('get_resource_type')
    subjects = fields.Method('get_subjects')
    titles = fields.List(
        fields.Nested(TitleSchema), attribute='metadata.title')

    def get_resource_type(self, obj):
        """Get resource type."""
        return {
            'resourceType': None,
            'resourceTypeGeneral': 'Audiovisual',
        }
github cernanalysispreservation / analysispreservation.cern.ch / cap / modules / records / serializers / schemas / common.py View on Github external
class CommonRecordSchema(Schema, StrictKeysMixin):
    """Base record schema."""

    id = fields.Str(attribute='pid.pid_value', dump_only=True)

    schema = fields.Method('get_schema', dump_only=True)

    experiment = fields.Str(attribute='metadata._experiment', dump_only=True)
    status = fields.Str(attribute='metadata._deposit.status', dump_only=True)
    created_by = fields.Method('get_created_by', dump_only=True)
    is_owner = fields.Method('is_current_user_owner', dump_only=True)

    metadata = fields.Method('get_metadata', dump_only=True)

    links = fields.Raw(dump_only=True)
    files = fields.Method('get_files', dump_only=True)

    access = fields.Method('get_access', dump_only=True)

    created = fields.Str(dump_only=True)
    updated = fields.Str(dump_only=True)

    revision = fields.Integer(dump_only=True)

    def is_current_user_owner(self, obj):
        user_id = obj['metadata']['_deposit'].get('created_by')
        if user_id and current_user:
            return user_id == current_user.id
        return False

    def get_files(self, obj):
        return obj['metadata'].get('_files', [])
github cernanalysispreservation / analysispreservation.cern.ch / cap / modules / records / serializers / schemas / json.py View on Github external
from invenio_jsonschemas import current_jsonschemas
from marshmallow import Schema, fields

from cap.modules.deposit.api import CAPDeposit
from cap.modules.deposit.permissions import (AdminDepositPermission,
                                             UpdateDepositPermission)
from cap.modules.records.permissions import (AdminRecordPermission,
                                             UpdateRecordPermission)

from . import common


class RecordSchema(common.CommonRecordSchema):
    """Schema for records v1 in JSON."""
    type = fields.Str(default='record')
    can_update = fields.Method('can_user_update', dump_only=True)
    can_admin = fields.Method('can_user_admin', dump_only=True)

    draft_id = fields.String(attribute='metadata._deposit.id', dump_only=True)

    def can_user_update(self, obj):
        deposit = CAPDeposit.get_record(obj['pid'].object_uuid)
        return UpdateRecordPermission(deposit).can()

    def can_user_admin(self, obj):
        deposit = CAPDeposit.get_record(obj['pid'].object_uuid)
        return AdminRecordPermission(deposit).can()


class RecordFormSchema(RecordSchema):
    """Schema for records v1 in JSON."""