Exemplo n.º 1
0
class RouteOutputSchema(JSONAPISchema):
    id = fields.UUID()
    origin = fields.Dict()
    origin_name = fields.String()
    destination = fields.Dict()
    destination_name = fields.String()
    polyline = fields.Dict()
    bounds = fields.Dict()
    created = fields.DateTime()

    class Meta:
        type_ = 'routes'
        strict = True
        inflect = dasherize

    @pre_dump(pass_many=True)
    def convert_geojson_to_dict(self, data, many):
        fields = ['origin', 'destination', 'polyline']
        if many:
            for item in data:
                for field in fields:
                    item[field] = escape.json_decode(item[field])
        else:
            for field in fields:
                data[field] = escape.json_decode(data[field])
        return data
Exemplo n.º 2
0
class PokemonSchema(Schema):
    class Meta:
        type_ = 'pokemon'
        self_view = 'pokemon_one'
        self_view_kwargs = {'id': '<id>'}
        self_view_many = 'pokemon_many'

    id = fields.Integer()
    dex_num = fields.Integer()
    name = fields.Str(required=True)
    type1 = fields.Str()
    type2 = fields.Str()
    sprite = fields.Str()
    type_values = fields.Dict()
    weaknesses = fields.Dict()
Exemplo n.º 3
0
class BundleSchema(Schema):
    id = fields.String(validate=validate_uuid, attribute='uuid')
    uuid = fields.String(attribute='uuid')  # for backwards compatibility
    bundle_type = fields.String(
        validate=validate.OneOf({bsc.BUNDLE_TYPE
                                 for bsc in BUNDLE_SUBCLASSES}))
    command = fields.String(allow_none=True)
    data_hash = fields.String()
    state = fields.String()
    owner = fields.Relationship(include_resource_linkage=True,
                                type_='users',
                                attribute='owner_id')
    is_anonymous = fields.Bool()
    metadata = fields.Dict()
    dependencies = fields.Nested(BundleDependencySchema, many=True)
    children = fields.Relationship(include_resource_linkage=True,
                                   type_='bundles',
                                   id_field='uuid',
                                   many=True)
    group_permissions = fields.Relationship(include_resource_linkage=True,
                                            type_='bundle-permissions',
                                            id_field='id',
                                            many=True)
    host_worksheets = fields.Relationship(include_resource_linkage=True,
                                          type_='worksheets',
                                          id_field='uuid',
                                          many=True)
    args = fields.String()

    # Bundle permission of the authenticated user for convenience, read-only
    permission = fields.Integer()
    permission_spec = PermissionSpec(attribute='permission')

    class Meta:
        type_ = 'bundles'
Exemplo n.º 4
0
class TableBlockSchema(WorksheetBlockSchema):
    mode = fields.Constant(BlockModes.table_block)
    bundles_spec = fields.Nested(BundlesSpecSchema, required=True)
    status = fields.Nested(FetchStatusSchema, required=True)

    header = fields.List(fields.String(), required=True)
    rows = fields.List(fields.Dict(), required=True)
Exemplo n.º 5
0
class ItemSchema(Schema):

    id = fields.String(dump_only=True)
    name = fields.String(required=True,
                         validator=ma.validate.Length(min=3, max=20))
    description = fields.String()
    tags = fields.List(fields.String())
    upc = fields.String()
    color = fields.String()
    size = fields.String()
    weight = fields.String()
    dimension = fields.String()
    category = fields.String()
    image = fields.URL()

    manufactory = fields.String()
    meta = fields.Dict()

    status = fields.String(requred=True, default='deactive')

    created_date = fields.DateTime(dump_only=True)
    updated_date = fields.DateTime(dump_only=True)

    class Meta:
        type_ = 'items'
        strict = True
        inflect = common.dasherize
Exemplo n.º 6
0
class DirectionsSchema(JSONAPISchema):
    id = fields.String()
    route = fields.Dict()

    class Meta:
        type_ = 'directions'
        strict = True
        inflect = dasherize
Exemplo n.º 7
0
class BundlesSpecSchema(PlainSchema):
    uuid_spec_type = 'uuid_spec'

    spec_types = uuid_spec_type

    # Fields
    spec_type = fields.String(validate=validate.OneOf(set(spec_types)))
    bundle_infos = fields.List(fields.Dict())
    fetch_status = fields.Nested(FetchStatusSchema, required=True)
Exemplo n.º 8
0
class SampleSchema(SlydSchema):
    id = fields.Str(dump_only=True)
    name = fields.Str()
    url = fields.Str(required=True)
    page_id = fields.Str()
    page_type = fields.Str(default='item')
    scrapes = fields.Str()
    extractors = fields.Dict(default={})
    project = fields.Relationship(
        related_url='/api/projects/{project_id}',
        related_url_kwargs={'project_id': '<project_id>'},
        type_='projects', include_resource_linkage=True
    )
    spider = fields.Relationship(
        related_url='/api/projects/{project_id}/spiders/{spider_id}',
        related_url_kwargs={'project_id': '<project_id>',
                            'spider_id': '<spider_id>'},
        type_='spiders', include_resource_linkage=True
    )
    original_body = fields.Relationship(
        related_url='/api/projects/{project_id}/spider/{spider_id}/samples/'
                    '{sample_id}/original_body',
        related_url_kwargs={'project_id': '<project_id>',
                            'spider_id': '<spider_id>',
                            'sample_id': '<id>'},
        type_='html', include_resource_linkage=False
    )
    rendered_body = fields.Relationship(
        related_url='/api/projects/{project_id}/spider/{spider_id}/samples/'
                    '{sample_id}/rendered_body',
        related_url_kwargs={'project_id': '<project_id>',
                            'spider_id': '<spider_id>',
                            'sample_id': '<id>'},
        type_='html', include_resource_linkage=False
    )
    items = fields.Relationship(
        related_url='/api/projects/{project_id}/spider/{spider_id}/samples/'
                    '{sample_id}/items',
        related_url_kwargs={'project_id': '<project_id>',
                            'spider_id': '<spider_id>',
                            'sample_id': '<id>'},
        type_='items', many=True, include_resource_linkage=True
    )

    def dump(self, obj, many=None, update_fields=True, **kwargs):
        many = self.many if many is None else bool(many)
        if many:
            for o in obj:
                o.setdefault('items', [])
        else:
            obj.setdefault('items', [])
        return super(SampleSchema, self).dump(obj, many, update_fields,
                                              **kwargs)

    class Meta:
        type_ = 'samples'
Exemplo n.º 9
0
class SubstanceSchema(Schema):
    id = fields.Str()
    identifiers = fields.Dict()  # Swagger does not render this if it's Raw

    class Meta:
        model = Substance
        type_ = "substance"
        self_view = "substance_detail"
        self_view_kwargs = {"id": "<id>"}
        self_view_many = "substance_list"
Exemplo n.º 10
0
class DocumentSchema(Schema):

    id = fields.Integer(dump_only=True)
    created = fields.DateTime(dump_only=True)
    doc = fields.Dict()

    class Meta:
        type_ = 'documents'
        #self_url = '/documents/{id}'
        #self_url_kwargs = {'id': '<id>'}
        strict = True
Exemplo n.º 11
0
    class StringJsonAttributePersonSchema(Schema):
        class Meta:
            type_ = "string_json_attribute_person"
            self_view = "api.string_json_attribute_person_detail"
            self_view_kwargs = {"person_id": "<id>"}

        id = fields.Integer(as_string=True, attribute="person_id")
        name = fields.Str(required=True)
        birth_date = fields.DateTime()
        address = fields.Nested(address_schema, many=False)
        tags = fields.List(fields.Dict())
Exemplo n.º 12
0
class SchemaBlockSchema(WorksheetBlockSchema):
    """
    Schema for user-defined schemas in worksheets
    """

    mode = fields.Constant(BlockModes.schema_block)
    schema_name = fields.String(required=True)
    header = fields.List(fields.String(), required=True)
    field_rows = fields.List(fields.Dict(), required=True)
    sort_keys = fields.List(fields.Integer())
    ids = fields.List(fields.Integer())
Exemplo n.º 13
0
class TableBlockSchema(WorksheetBlockSchema):
    mode = fields.Constant(BlockModes.table_block)
    bundles_spec = fields.Nested(BundlesSpecSchema, required=True)
    status = fields.Nested(FetchStatusSchema, required=True)

    header = fields.List(fields.String(), required=True)
    rows = fields.List(fields.Dict(), required=True)
    sort_keys = fields.List(fields.Integer())
    first_bundle_source_index = fields.Integer(
    )  # index for the first bundle in source
    using_schemas = fields.List(fields.String())
Exemplo n.º 14
0
class S3ObjectSummarySchema(CamelCaseSchema):
    """ - https://jsonapi.org/
        - https://github.com/marshmallow-code/marshmallow-jsonapi
        - https://marshmallow.readthedocs.io/en/latest/api_reference.html#module-marshmallow.fields
    """
    class Meta:
        type_ = "s3-buckets"

    id = fields.Str(attribute="key")
    e_tag = fields.Str()
    last_modified = fields.DateTime()
    owner = fields.Dict(keys=fields.Str(), values=fields.Str())
    size = fields.Int()
    storage_class = fields.Str()
Exemplo n.º 15
0
class RouteInputSchema(JSONAPISchema):
    id = fields.UUID()
    origin = fields.Nested(GeoJSONSchema, required=True)
    origin_name = fields.String(required=True)
    destination = fields.Nested(GeoJSONSchema, required=True)
    destination_name = fields.String(required=True)
    waypoints = fields.List(fields.Float)
    waypoints_names = fields.List(fields.String)
    polyline = fields.Nested(GeoJSONSchema, required=True)
    bounds = fields.Dict()
    created = fields.DateTime(allow_none=True)

    class Meta:
        type_ = 'routes'
        strict = True
        inflect = dasherize
Exemplo n.º 16
0
class CharacterizationSchema(Schema):
    id = fields.Function(lambda x: '%s(%s, %s)' %
                         (x.quantity.external_ref, x.flow.external_ref, x.flow[
                             'Compartment'][-1]))
    flow = fields.Relationship(related_url='/{flow_link}',
                               related_url_kwargs={'flow_link': '<flow.link>'})
    context = fields.List(fields.Str(), attribute='flow.Compartment')
    quantity = fields.Relationship(
        related_url='/{quantity_link}',
        related_url_kwargs={'quantity_link': '<quantity.link>'})
    value = fields.Dict(keys=fields.Str(),
                        values=fields.Decimal(),
                        attribute='_locations')

    class Meta:
        type_ = 'characterization'
        strict = True
Exemplo n.º 17
0
class PuppySchema(Schema):
    """
    This schema converts our nested database attributes into flat JSONAPI attributes, and vice versa.
    Database attributes: id, description, birthday
    JSONAPI attributes: name, breed, gender (these all get saved to 'description' in the db)
    """
    id = fields.Int()
    # the "load_only" flag means this value will be skipped during serialization:
    description = fields.Dict(load_only=True)
    name = fields.Str()
    breed = fields.Str()
    gender = fields.Str()
    birthday = fields.DateTime()

    @post_load
    def combine_fields_into_description(self, attributes):
        """
        This function is run after deserialization. It combines the incoming "attributes" into the
        nested description property.
        :param attributes: deserialized dictionary
        :return: dictionary where the key is "description", and the value is the dictionary of attributes
        """
        return {'config': attributes}

    @pre_dump
    def flatten_description(self, puppy):
        """
        This function is run before serialization. It flattens the "description" property into the
        attributes listed in PuppySchema.
        :param puppy: the original object
        :return: the processed object to be serialized
        """
        if puppy.description:
            description = json.loads(puppy.description)
            puppy.name = description.get('name')
            puppy.breed = description.get('breed')
            puppy.gender = description.get('gender')
        return puppy

    class Meta:
        type_ = "puppies"
        strict = True
Exemplo n.º 18
0
class PlotSchema(JsonApiSchema):
    """
    Data that can be used to generate a plot.
    """
    class Meta:
        type_ = "plots"
        unknown = INCLUDE

    id = f.String(dump_only=True)
    type = f.String()
    x = f.List(f.Raw())
    y = f.List(f.Raw())
    text = f.List(f.Raw())
    hoverinfo = f.Str()
    line = f.Dict()
    mode = f.String()
    name = f.String()
    fill = f.String()
    fillcolor = f.String()
    showlegend = f.Bool()
Exemplo n.º 19
0
class SessionSchema(SoftDeletionSchema):
    """
    Api schema for Session Model
    """
    class Meta:
        """
        Meta class for Session Api Schema
        """

        type_ = 'session'
        self_view = 'v1.session_detail'
        self_view_kwargs = {'id': '<id>'}
        inflect = dasherize

    @validates_schema(pass_original=True)
    def validate_fields(self, data, original_data):
        if 'id' in original_data['data']:
            try:
                session = Session.query.filter_by(
                    id=original_data['data']['id']).one()
            except NoResultFound:
                raise ObjectNotFound({'parameter': '{id}'},
                                     "Session: not found")

            if 'starts_at' not in data:
                data['starts_at'] = session.starts_at

            if 'ends_at' not in data:
                data['ends_at'] = session.ends_at

            if 'event' not in data:
                data['event'] = session.event_id

        if data['starts_at'] and data['ends_at']:
            if data['starts_at'] >= data['ends_at']:
                raise UnprocessableEntity(
                    {'pointer': '/data/attributes/ends-at'},
                    "ends-at should be after starts-at",
                )
            if datetime.timestamp(data['starts_at']) <= datetime.timestamp(
                    datetime.now()):
                raise UnprocessableEntity(
                    {'pointer': '/data/attributes/starts-at'},
                    "starts-at should be after current date-time",
                )

        if 'state' in data:
            if data['state'] not in ('draft', 'pending'):
                if not has_access('is_coorganizer', event_id=data['event']):
                    return ForbiddenException(
                        {'source': ''}, 'Co-organizer access is required.')

        if 'track' in data:
            if not has_access('is_coorganizer', event_id=data['event']):
                return ForbiddenException({'source': ''},
                                          'Co-organizer access is required.')

        if 'microlocation' in data:
            if not has_access('is_coorganizer', event_id=data['event']):
                return ForbiddenException({'source': ''},
                                          'Co-organizer access is required.')

        validate_complex_fields_json(self, data, original_data)

    id = fields.Str(dump_only=True)
    title = fields.Str(required=True)
    subtitle = fields.Str(allow_none=True)
    level = fields.Str(allow_none=True)
    short_abstract = fields.Str(allow_none=True)
    long_abstract = fields.Str(allow_none=True)
    comments = fields.Str(allow_none=True)
    starts_at = fields.DateTime(allow_none=True)
    ends_at = fields.DateTime(allow_none=True)
    language = fields.Str(allow_none=True)
    slides_url = fields.Url(allow_none=True)
    video_url = fields.Url(allow_none=True)
    audio_url = fields.Url(allow_none=True)
    signup_url = fields.Url(allow_none=True)
    state = fields.Str(
        validate=validate.OneOf(
            choices=["pending", "accepted", "confirmed", "rejected", "draft"]),
        allow_none=True,
        default='draft',
    )
    created_at = fields.DateTime(dump_only=True)
    deleted_at = fields.DateTime(dump_only=True)
    submitted_at = fields.DateTime(allow_none=True)
    is_mail_sent = fields.Boolean()
    is_locked = fields.Boolean(default=False)
    last_modified_at = fields.DateTime(dump_only=True)
    send_email = fields.Boolean(load_only=True, allow_none=True)
    average_rating = fields.Float(dump_only=True)
    complex_field_values = fields.Dict(allow_none=True)
    microlocation = Relationship(
        attribute='microlocation',
        self_view='v1.session_microlocation',
        self_view_kwargs={'id': '<id>'},
        related_view='v1.microlocation_detail',
        related_view_kwargs={'session_id': '<id>'},
        schema='MicrolocationSchema',
        type_='microlocation',
    )
    track = Relationship(
        attribute='track',
        self_view='v1.session_track',
        self_view_kwargs={'id': '<id>'},
        related_view='v1.track_detail',
        related_view_kwargs={'session_id': '<id>'},
        schema='TrackSchema',
        type_='track',
    )
    session_type = Relationship(
        attribute='session_type',
        self_view='v1.session_session_type',
        self_view_kwargs={'id': '<id>'},
        related_view='v1.session_type_detail',
        related_view_kwargs={'session_id': '<id>'},
        schema='SessionTypeSchema',
        type_='session-type',
    )
    event = Relationship(
        attribute='event',
        self_view='v1.session_event',
        self_view_kwargs={'id': '<id>'},
        related_view='v1.event_detail',
        related_view_kwargs={'session_id': '<id>'},
        schema='EventSchemaPublic',
        type_='event',
    )
    feedbacks = Relationship(
        attribute='feedbacks',
        self_view='v1.session_feedbacks',
        self_view_kwargs={'id': '<id>'},
        related_view='v1.feedback_list',
        related_view_kwargs={'session_id': '<id>'},
        schema='FeedbackSchema',
        many=True,
        type_='feedback',
    )
    speakers = Relationship(
        attribute='speakers',
        many=True,
        self_view='v1.session_speaker',
        self_view_kwargs={'id': '<id>'},
        related_view='v1.speaker_list',
        related_view_kwargs={'session_id': '<id>'},
        schema='SpeakerSchema',
        type_='speaker',
    )
    creator = Relationship(
        attribute='user',
        self_view='v1.session_user',
        self_view_kwargs={'id': '<id>'},
        related_view='v1.user_detail',
        related_view_kwargs={'session_id': '<id>'},
        schema='UserSchemaPublic',
        type_='user',
    )
Exemplo n.º 20
0
class SpeakerSchema(SoftDeletionSchema):
    """
    Speaker Schema based on Speaker Model
    """
    @validates_schema(pass_original=True)
    def validate_json(self, data, original_data):
        validate_complex_fields_json(self, data, original_data)

    class Meta:
        """
        Meta class for speaker schema
        """
        type_ = 'speaker'
        self_view = 'v1.speaker_detail'
        self_view_kwargs = {'id': '<id>'}
        inflect = dasherize

    id = fields.Str(dump_only=True)
    name = fields.Str(required=True)
    email = fields.Str(required=True)
    photo_url = fields.Url(allow_none=True)
    thumbnail_image_url = fields.Url(allow_none=True)
    small_image_url = fields.Url(allow_none=True)
    icon_image_url = fields.Url(allow_none=True)
    short_biography = fields.Str(allow_none=True)
    long_biography = fields.Str(allow_none=True)
    speaking_experience = fields.Str(allow_none=True)
    mobile = fields.Str(allow_none=True)
    website = fields.Url(allow_none=True)
    twitter = fields.Url(allow_none=True)
    facebook = fields.Url(allow_none=True)
    github = fields.Url(allow_none=True)
    linkedin = fields.Url(allow_none=True)
    organisation = fields.Str(allow_none=True)
    is_featured = fields.Boolean(default=False)
    is_email_overridden = fields.Boolean(default=False)
    position = fields.Str(allow_none=True)
    country = fields.Str(allow_none=True)
    city = fields.Str(allow_none=True)
    gender = fields.Str(allow_none=True)
    heard_from = fields.Str(allow_none=True)
    sponsorship_required = fields.Str(allow_none=True)
    complex_field_values = fields.Dict(allow_none=True)
    event = Relationship(attribute='event',
                         self_view='v1.speaker_event',
                         self_view_kwargs={'id': '<id>'},
                         related_view='v1.event_detail',
                         related_view_kwargs={'speaker_id': '<id>'},
                         schema='EventSchemaPublic',
                         type_='event')
    user = Relationship(attribute='user',
                        self_view='v1.speaker_user',
                        self_view_kwargs={'id': '<id>'},
                        related_view='v1.user_detail',
                        related_view_kwargs={'speaker_id': '<id>'},
                        schema='UserSchemaPublic',
                        type_='user')
    sessions = Relationship(attribute='sessions',
                            self_view='v1.speaker_session',
                            self_view_kwargs={'id': '<id>'},
                            related_view='v1.session_list',
                            related_view_kwargs={'speaker_id': '<id>'},
                            schema='SessionSchema',
                            many=True,
                            type_='session')
Exemplo n.º 21
0
class AttendeeSchemaPublic(SoftDeletionSchema):
    """
    Api schema for Ticket Holder Model
    """
    class Meta:
        """
        Meta class for Attendee API Schema
        """
        type_ = 'attendee'
        self_view = 'v1.attendee_detail'
        self_view_kwargs = {'id': '<id>'}
        inflect = dasherize

    @validates_schema(pass_original=True)
    def validate_json(self, data, original_data):
        validate_complex_fields_json(self, data, original_data)

    id = fields.Str(dump_only=True)
    firstname = fields.Str(required=True)
    lastname = fields.Str(required=True)
    email = fields.Str(allow_none=True)
    address = fields.Str(allow_none=True)
    city = fields.Str(allow_none=True)
    state = fields.Str(allow_none=True)
    country = fields.Str(allow_none=True)
    job_title = fields.Str(allow_none=True)
    phone = fields.Str(allow_none=True)
    tax_business_info = fields.Str(allow_none=True)
    billing_address = fields.Str(allow_none=True)
    home_address = fields.Str(allow_none=True)
    shipping_address = fields.Str(allow_none=True)
    company = fields.Str(allow_none=True)
    work_address = fields.Str(allow_none=True)
    work_phone = fields.Str(allow_none=True)
    website = fields.Url(allow_none=True)
    blog = fields.Url(allow_none=True)
    twitter = fields.Url(allow_none=True)
    facebook = fields.Url(allow_none=True)
    github = fields.Url(allow_none=True)
    gender = fields.Str(allow_none=True)
    age_group = fields.Str(validate=validate.OneOf(choices=AGE_GROUP_CHOICES),
                           allow_none=True)
    birth_date = fields.DateTime(allow_none=True)

    ticket_id = fields.Str(allow_none=True)
    is_checked_in = fields.Boolean()
    device_name_checkin = fields.Str(allow_none=True)
    checkin_times = fields.Str(allow_none=True)
    checkout_times = fields.Str(allow_none=True, dump_only=True)
    attendee_notes = fields.Str(allow_none=True)
    is_checked_out = fields.Boolean()
    pdf_url = fields.Url(dump_only=True)
    complex_field_values = fields.Dict(allow_none=True)
    event = Relationship(attribute='event',
                         self_view='v1.attendee_event',
                         self_view_kwargs={'id': '<id>'},
                         related_view='v1.event_detail',
                         related_view_kwargs={'attendee_id': '<id>'},
                         schema='EventSchema',
                         type_='event')
    user = Relationship(attribute='user',
                        self_view='v1.attendee_user',
                        self_view_kwargs={'id': '<id>'},
                        related_view='v1.user_detail',
                        related_view_kwargs={'attendee_id': '<id>'},
                        schema='UserSchemaPublic',
                        type_='user')