Beispiel #1
0
class TourSchema(Schema):
    id = Integer(required=True)
    name = String(required=True)
    is_active = Boolean(data_key='isActive', required=True)
    description = String(required=True)
    city_or_province = String(data_key='cityOrProvince', required=True)
    common_address = String(data_key='commonAddress', required=True)
    duration = Integer(required=True)
    min_size = Integer(data_key='minSize', required=True)
    max_size = Integer(data_key='maxSize', required=True)
    price_per_participant = Integer(data_key='pricePerParticipant',
                                    required=True)
    transportations = Method(serialize='get_transportations')
    images = Method(serialize='get_images')
    organizer_name = String(data_key='organizerName', required=True)
    organizer_email = String(data_key='organizerEmail', required=True)
    organizer_phone_number = String(data_key='organizerPhoneNumber',
                                    required=True)
    organizer_avatar = String(data_key='organizerAvatar', required=True)

    def get_transportations(self, obj):
        transportations = obj.transportations
        if transportations is not None:
            transportations = transportations.split(',')
        return transportations

    def get_images(self, obj):
        images = obj.images
        if images is not None:
            images = images.split(',')
        return images
class UIListSchema(Schema):
    """Schema for dumping extra information in the UI."""
    class Meta:
        """."""

        unknown = INCLUDE

    hits = Method("get_hits")
    aggregations = Method("get_aggs")

    def get_hits(self, obj_list):
        """Apply hits transformation."""
        for obj in obj_list["hits"]["hits"]:
            obj[self.context["object_key"]] = self.context[
                "object_schema_cls"]().dump(obj)
        return obj_list["hits"]

    def get_aggs(self, obj_list):
        """Apply aggregations transformation."""
        aggs = obj_list.get("aggregations")
        if not aggs:
            return missing

        for name, agg in aggs.items():
            vocab = Vocabularies.get_vocabulary(name)
            if not vocab:
                continue

            buckets = agg.get("buckets")
            if buckets:
                apply_labels(vocab, buckets)

        return aggs
class PaperRevisionSchema(mm.SQLAlchemyAutoSchema):
    submitter = Nested(UserSchema)
    judge = Nested(UserSchema)
    spotlight_file = Nested(PaperFileSchema)
    files = List(Nested(PaperFileSchema))
    state = EnumField(PaperRevisionState)
    timeline = PaperRevisionTimelineField()
    judgment_comment_html = Function(lambda revision: escape(revision.judgment_comment))
    reviewer_data = Method('_get_reviewer_data')

    class Meta:
        model = PaperRevision
        fields = ('id', 'submitted_dt', 'judgment_dt', 'submitter', 'judge', 'spotlight_file', 'files',
                  'is_last_revision', 'number', 'state', 'timeline', 'judgment_comment', 'judgment_comment_html',
                  'reviewer_data')

    def _get_reviewer_data(self, revision):
        if not revision.is_last_revision:
            return None

        data = dict(revision.get_reviewer_render_data(self.context.get('user')))
        review_type_schema = PaperReviewTypeSchema()
        for name in ('groups', 'missing_groups', 'reviewed_groups'):
            data[name] = [review_type_schema.dump(item.instance) for item in data[name]]

        reviews = {}
        for key, value in data['reviews'].items():
            reviews[orig_string(key.instance.title)] = paper_review_schema.dump(value)
        data['reviews'] = reviews
        return data
class FileSchema(Schema):
    class Meta:
        model = File
        fields = [
            "id", "name", "is_status", "is_reference", "content_type",
            "primary", "primary_process_id", "workflow_spec_id", "workflow_id",
            "irb_doc_code", "last_modified", "latest_version", "type", "size",
            "data_store", "document", "user_uid", "url"
        ]
        unknown = INCLUDE

    type = EnumField(FileType)
    url = Method("get_url")

    def get_url(self, obj):
        token = 'not_available'
        if obj.id is None:
            return ""  # We can't return a url for a file that isn't stored yet.
        file_url = url_for("/v1_0.crc_api_file_get_file_data_link",
                           file_id=obj.id,
                           _external=True)
        if hasattr(flask.g, 'user'):
            token = flask.g.user.encode_auth_token()
        url = file_url + '?auth_token=' + urllib.parse.quote_plus(token)
        return url
Beispiel #5
0
class BlockingSchema(mm.ModelSchema):
    blocked_rooms = Nested(BlockedRoomSchema, many=True)
    allowed = Nested(BlockingPrincipalSchema, many=True)
    permissions = Method('_get_permissions')
    created_by = Nested(UserSchema,
                        attribute='created_by_user',
                        only='full_name')

    class Meta:
        model = Blocking
        fields = ('id', 'start_date', 'end_date', 'reason', 'blocked_rooms',
                  'allowed', 'created_by', 'permissions')

    def _get_permissions(self, blocking):
        methods = ('can_delete', 'can_edit')
        admin_permissions = None
        user_permissions = {
            x: getattr(blocking, x)(session.user, allow_admin=False)
            for x in methods
        }
        if rb_is_admin(session.user):
            admin_permissions = {
                x: getattr(blocking, x)(session.user)
                for x in methods
            }
        return {'user': user_permissions, 'admin': admin_permissions}
Beispiel #6
0
class ReservationDetailsSchema(mm.SQLAlchemyAutoSchema):
    booked_for_user = Nested(UserSchema, only=('id', 'identifier', 'full_name', 'phone', 'email'))
    created_by_user = Nested(UserSchema, only=('id', 'identifier', 'full_name', 'email'))
    edit_logs = Nested(ReservationEditLogSchema, many=True)
    can_accept = Function(lambda booking: booking.can_accept(session.user))
    can_cancel = Function(lambda booking: booking.can_cancel(session.user))
    can_delete = Function(lambda booking: booking.can_delete(session.user))
    can_edit = Function(lambda booking: booking.can_edit(session.user))
    can_reject = Function(lambda booking: booking.can_reject(session.user))
    permissions = Method('_get_permissions')
    state = EnumField(ReservationState)
    is_linked_to_object = Function(lambda booking: booking.link is not None)
    link = Nested(ReservationLinkSchema)
    start_dt = NaiveDateTime()
    end_dt = NaiveDateTime()

    class Meta:
        model = Reservation
        fields = ('id', 'start_dt', 'end_dt', 'repetition', 'booking_reason', 'created_dt', 'booked_for_user',
                  'room_id', 'created_by_user', 'edit_logs', 'permissions',
                  'is_cancelled', 'is_rejected', 'is_accepted', 'is_pending', 'rejection_reason',
                  'is_linked_to_object', 'link', 'state', 'external_details_url')

    def _get_permissions(self, booking):
        methods = ('can_accept', 'can_cancel', 'can_delete', 'can_edit', 'can_reject')
        admin_permissions = None
        user_permissions = {x: getattr(booking, x)(session.user, allow_admin=False) for x in methods}
        if rb_is_admin(session.user):
            admin_permissions = {x: getattr(booking, x)(session.user) for x in methods}
        return {'user': user_permissions, 'admin': admin_permissions}
Beispiel #7
0
class HotelSchema(Schema):
    id = Integer(required=True)
    name = String(required=True)
    is_active = Boolean(data_key=HotelCamelKey.mapping['is_active'],
                        required=True)
    description = String(required=True)
    city_or_province = String(
        data_key=HotelCamelKey.mapping['city_or_province'], required=True)
    address = String(required=True)
    longitude = Float(required=True)
    latitude = Float(required=True)
    checkin = DateTime(format='%H:%M', required=True)
    checkout = DateTime(format='%H:%M', required=True)
    utilities = Method(serialize='get_utilities')
    room_types = Method(serialize='get_room_types',
                        data_key=HotelCamelKey.mapping['room_types'])
    phone_number = String(data_key=HotelCamelKey.mapping['phone_number'],
                          required=True)
    email = String(required=True)
    image = String(required=True)
    price_standard = Float(data_key=HotelCamelKey.mapping['price_standard'])
    available_room_standard = Integer(
        data_key=HotelCamelKey.mapping['available_room_standard'])
    tax_standard = Float(data_key=HotelCamelKey.mapping['tax_standard'])
    image_standard = String(data_key=HotelCamelKey.mapping['image_standard'])
    price_deluxe = Float(data_key=HotelCamelKey.mapping['price_deluxe'])
    available_room_deluxe = Integer(
        data_key=HotelCamelKey.mapping['available_room_deluxe'],
        allow_none=True)
    tax_deluxe = Float(data_key=HotelCamelKey.mapping['tax_deluxe'])
    image_deluxe = String(data_key=HotelCamelKey.mapping['image_deluxe'])

    def get_utilities(self, obj):
        utilities = obj.utilities
        if utilities is not None:
            utilities = utilities.split(',')
        return utilities

    def get_room_types(self, obj):
        room_types = obj.room_types
        if room_types is not None:
            room_types = room_types.split(',')
        return room_types
Beispiel #8
0
class ReservationLinkedObjectDataSchema(Schema):
    id = Number()
    title = Method('_get_title')
    url = String()
    event_title = Function(lambda obj: obj.event.title)
    event_url = Function(lambda obj: obj.event.url)

    def _get_title(self, object):
        if isinstance(object, SessionBlock):
            return object.full_title
        return object.title
Beispiel #9
0
class CommentSchema(ma.Schema):
    id = String(dump_only=True)
    post_id = Integer(dump_only=True)
    user_id = Integer(dump_only=True)
    content = String(required=True)
    parent_comment = String(load_only=True)
    comments = Method("get_comments")

    def get_comments(self, obj):
        print(obj.comments)
        return obj.comments
Beispiel #10
0
class GammaCounterRunSchema(BaseSchema):
    class Meta(BaseSchema.Meta):
        model = GammaCounterRun

    gamma_counter = Nested(GammaCounter.Schema, many=False, dump_only=True)
    calibrations = Nested(CalibrationSchema, many=False, dump_only=True)
    custom_calibration = Nested(CustomCalibrationSchema, many=False, dump_only=True)
    vials = Method('vials_count')

    def vials_count(self, obj):
        return len(obj.vials)
Beispiel #11
0
class ReservationLinkedObjectDataSchema(mm.Schema):
    id = Number()
    title = Method('_get_title')
    event_title = Function(lambda obj: obj.event.title)
    event_url = Function(lambda obj: obj.event.url)
    own_room_id = Number()
    own_room_name = Function(lambda obj: (obj.own_room.name if obj.own_room else obj.own_room_name) or None)

    def _get_title(self, obj):
        if isinstance(obj, SessionBlock):
            return obj.full_title
        return obj.title
Beispiel #12
0
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 DataSourceSerializer(Schema):
    source_type = Str()
    url = URL()
    title = Str()
    last_import_timestamp = DateTime()
    update_frequency = Method('get_update_frequency')

    def get_update_frequency(self, obj):
        translations = {}
        for lang in settings.MODELTRANS_AVAILABLE_LANGUAGES:
            with override(lang):
                translations[lang] = str(obj.get_frequency_in_days_display())
        return translations
Beispiel #14
0
class UIListSchema(Schema):
    """Schema for dumping extra information in the UI."""
    class Meta:
        """."""

        unknown = INCLUDE

    hits = Method("get_hits")
    aggregations = Method("get_aggs")

    def get_hits(self, obj_list):
        """Apply hits transformation."""
        for obj in obj_list["hits"]["hits"]:
            obj[self.context["object_key"]] = self.context[
                "object_schema_cls"]().dump(obj)
        return obj_list["hits"]

    def get_aggs(self, obj_list):
        """Apply aggregations transformation."""
        aggs = obj_list.get("aggregations")
        if not aggs:
            return missing

        return aggs
Beispiel #15
0
class ReservationLinkedObjectDataSchema(Schema):
    id = Number()
    title = Method('_get_title')
    event_title = Function(lambda obj: obj.event.title)
    event_url = Function(lambda obj: obj.event.url)
    own_room_id = Number()
    own_room_name = Function(lambda obj: (obj.own_room.name if obj.own_room else obj.own_room_name) or None)

    class Meta:
        strict = True  # TODO: remove with marshmallow 3

    def _get_title(self, obj):
        if isinstance(obj, SessionBlock):
            return obj.full_title
        return obj.title
Beispiel #16
0
class AnalysisSystemInstanceSchema(BaseSchema):
    url = URLFor('.analysis_system_instance_detail',
                 uuid='<uuid>',
                 _external=True)
    analysis_system = ForeignReferenceField(endpoint='.analysis_system_detail',
                                            queryset=AnalysisSystem.objects(),
                                            query_parameter='identifier_name')
    is_online = Boolean()
    scheduled_analyses_count = Method("get_scheduled_analyses_count")

    class Meta(BaseSchema.Meta):
        model = AnalysisSystemInstance
        dump_only = ['id', '_cls', 'last_seen', 'scheduled_analyses_count']

    def get_scheduled_analyses_count(self, obj):
        analyses_count = ScheduledAnalysis.objects(
            analysis_system_instance=obj).count()
        return analyses_count
class PaperReviewSchema(mm.SQLAlchemyAutoSchema):
    score = Decimal(places=2, as_string=True)
    user = Nested(UserSchema)
    visibility = Nested(PaperCommentVisibilitySchema)
    proposed_action = Nested(PaperAction)
    ratings = Nested(PaperRatingSchema, many=True)
    group = Nested(PaperReviewTypeSchema, attribute='group.instance')
    comment_html = Function(lambda review: escape(review.comment))
    can_edit = Method('_can_edit_review')

    class Meta:
        model = PaperReview
        fields = ('id', 'score', 'created_dt', 'user', 'comment', 'comment_html', 'modified_dt', 'visibility',
                  'proposed_action', 'group', 'ratings', 'can_edit')

    def _can_edit_review(self, review):
        user = self.context.get('user')
        cfp = review.revision.paper.cfp
        return review.can_edit(user, check_state=True) and is_type_reviewing_possible(cfp, review.type)
Beispiel #18
0
class UserSchema(SQLAlchemyAutoSchema):
    """Schema for user model."""
    class Meta:
        """Options for model schema."""
        model = User
        exclude = ('id', 'created_at')
        load_instance = True

    user_type = Method(deserialize='usertype_name_to_id')

    def usertype_name_to_id(self, user_type_input):
        """Custom method for deserialization of usertype name to id"""

        usertype = UserType.query.filter_by(name=user_type_input).first()

        if usertype is None:
            raise ValidationError(message='user type not supported')

        return usertype.id
Beispiel #19
0
class TemporalSchemaForm(ModelSchema):
    """Form definition for model TemporalCompositionSchema."""
    class Meta:
        """Internal meta information of Form interface."""

        model = TemporalCompositionSchema
        sqla_session = db.session

    id = String(dump_only=True)
    temporal_composite_unit = Method(deserialize='load_temporal_composite')

    def load_temporal_composite(self, value):
        """Validate temporal composite with all supported values."""
        if value in DEFAULT_TEMPORAL_UNITS:
            return value

        raise RuntimeError(
            'Invalid temporal unit. Supported values: {}'.format(
                DEFAULT_TEMPORAL_UNITS))
Beispiel #20
0
    def __new__(mcs, name, bases, attrs):
        parents = [b for b in bases if isinstance(b, JsonApiSerializerMeta)]
        if not parents:
            return super(JsonApiSerializerMeta,
                         mcs).__new__(mcs, name, bases, attrs)

        meta = attrs.pop('Meta', None)

        try:
            model = meta.model
        except AttributeError:
            raise TypeError(
                u"Class '{}' is missing the 'Meta.model' attribute.".format(
                    name))

        schema_type = type_from_model_name(model.__name__)

        meta_bases = (meta, object) if meta else (object, )
        schema_attrs = {
            'Meta':
            type('Meta', meta_bases, {
                'type_': schema_type,
                'inflect': dasherize,
            })
        }

        links = getattr(meta, 'links', {})
        for attrname, field in iteritems(model._fields):
            if isinstance(field, OrmField):
                field_copy = object.__new__(field.__class__)
                field_copy.__dict__ = dict(field.__dict__)
                field_copy.load_from = None
                field_copy.dump_to = None
                schema_attrs[attrname] = field_copy
            elif isinstance(field, BaseRelationship):
                rel_links = links.get(attrname, {})
                rel_many = isinstance(field, HasMany)
                rel_options = {
                    'self_url': rel_links.get('self', ''),
                    'related_url': rel_links.get('related', ''),
                    'many': rel_many
                }
                if not rel_many:
                    rel_options['allow_none'] = True
                if field.polymorphic:
                    schema_attrs[attrname] = PolymorphicRelationship(
                        **rel_options)
                else:
                    schema_attrs[attrname] = Relationship(
                        type_=type_from_model_name(field.model.__name__),
                        id_field='pk',
                        serializer=rel_links.get('serializer'),
                        **rel_options)

        if 'id' not in schema_attrs:
            pk_field = model._fields[model._pk_field]
            schema_attrs['id'] = type(pk_field)(attribute=model._pk_field)

        # we need to access the serialized object to generate the url, but
        # get_resource_links takes the serialized item, so we add a method field
        # to do the work
        schema_attrs['_url'] = Method('get_url')

        attrs.update(schema_attrs)
        cls = super(JsonApiSerializerMeta,
                    mcs).__new__(mcs, name, bases, attrs)

        # add new schema to registry by type
        is_custom = name.replace('Serializer', '') != model.__name__
        key = camel_case_to_dashes(name) if is_custom else schema_type
        schemas[key] = cls
        return cls
Beispiel #21
0
    class Meta:
        # model = Demande
        table = mapper.metadata.tables["v3_demandes"]

        include = {
            # Permissions
            "acces_restreint": Method("get_acces_restreint"),
            "is_editable": Method("get_is_editable"),
            "is_duplicable": Method("get_is_duplicable"),
            "feuille_cout_editable": Method("get_feuille_cout_editable"),
            # Key users
            "contact_labco": Method("get_contact_labco"),
            "porteur": Method("get_porteur"),
            "gestionnaire": Method("get_gestionnaire"),
            "contributeurs": Method("get_contributeurs"),
            # Structure
            "structure": Method("get_structure"),
            # Form
            "form_data": Method("get_form_data"),
            # For tabs
            "pieces_jointes": Method("get_pieces_jointes"),
            "workflow": Method("get_workflow"),
            "workflow_history": Method("get_history"),
            "past_versions": Method("get_past_versions"),
            "is_valid": Method("get_is_valid"),
            "errors": Method("get_errors"),
            "extra_errors": Method("get_extra_errors"),
        }