Esempio n. 1
0
class HistoryApiAttrs(ObjectAttrs):
    action = fields.Str()
    change_timestamp = fields.DateTime()
    change_user_id = fields.Str()
    difference = fields.Method('get_difference')
    message = fields.Str()
    new_value = fields.Method('get_new_value')
    row_id = fields.Int()
    table_name = fields.Str()

    class Meta:
        strict = True
        ordered = True
        object_type = 'history'
        api_path = '/histories'
        url_template = '{api_url}/histories/{ident}'
        model = 'histories.History'

    def get_difference(self, obj):
        difference = json.loads(obj.difference) or {}
        if 'values_changed' in difference:
            if "root['password']" in difference['values_changed']:
                difference['values_changed']["root['password']"][
                    'new_value'] = "********"
                difference['values_changed']["root['password']"][
                    'old_value'] = "********"
        return difference

    def get_new_value(self, obj):
        new_value = obj.new_value if isinstance(
            obj.new_value, dict) else json.loads(obj.new_value)
        if new_value and 'password' in new_value:
            new_value['password'] = "******"
        return new_value
class CreateUserScheduleItemAttrs(ObjectAttrs):
    institution = fields.Str(attribute='organization_name', required=True, validate=validate.Length(min=1))
    institution_unit = fields.Str(attribute='organization_unit')
    dataset_title = fields.Str(required=True, validate=validate.Length(min=1))
    format = fields.Str(required=True, validate=validate.Length(min=1))
    is_new = fields.Bool(required=True)
    is_openness_score_increased = fields.Bool()
    is_quality_improved = fields.Bool()
    description = fields.Str()

    class Meta:
        object_type = 'user_schedule_item'
        strict = True
        ordered = True

    @validates_schema
    def validate_data(self, data, **kwargs):
        is_new = data.get('is_new')
        is_openness_score_increased = data.get('is_openness_score_increased')
        is_quality_improved = data.get('is_quality_improved')
        if is_new:
            if 'is_openness_score_increased' in data:
                del data['is_openness_score_increased']
            if 'is_quality_improved' in data:
                del data['is_quality_improved']
        if is_new is False and is_openness_score_increased is None and is_quality_improved is None:  # False is ok.
            raise ValidationError(
                _('is_openness_score_increased or is_quality_improved is required if value of is_new is False!'))
class UserSchemaMixin(object):
    state = fields.Str(
        required=True,
        faker_type='userstate',
        example='active',
        description="Allowed values: 'active', 'inactive' or 'blocked'")
    email = fields.Email(required=True,
                         faker_type='email',
                         example='*****@*****.**')
    fullname = fields.Str(missing=None,
                          faker_type='name',
                          example='Jan Kowalski')
    about = fields.Str(missing=None,
                       faker_type='sentence',
                       example='I am a very talented programmer.')
    created = fields.Date()
    subscriptions_report_opt_in = fields.Boolean()
    rodo_privacy_policy_opt_in = fields.Boolean()
    count_datasets_created = fields.Int()
    count_datasets_modified = fields.Int()

    @post_dump
    def prepare_data(self, data, **kwargs):
        data['subscriptions_report_opt_in'] = True if data.get(
            'subscriptions_report_opt_in') is not None else False
        data['rodo_privacy_policy_opt_in'] = True if data.get(
            'rodo_privacy_policy_opt_in') is not None else False
        return data
class ReportSchema(ObjectAttrs):
    type = fields.Str()
    download_url = fields.Str()
    link = fields.Str()

    class Meta:
        ordered = True
class AgentImplementedUserScheduleItemAttrs(ObjectAttrs):
    is_resource_added = fields.Bool(required=True)
    is_resource_added_notes = fields.Str()
    resource_link = fields.Str()

    class Meta:
        object_type = 'user_schedule_item'
        strict = True
        ordered = True

    @validates('resource_link')
    def validate_resource_link(self, value):
        if value:
            validate.URL()(value)

    @validates_schema
    def validate_data(self, data, **kwargs):
        is_resource_added = data.get('is_resource_added')
        is_resource_added_notes = data.get('is_resource_added_notes')
        resource_link = data.get('resource_link')
        obj = self.context.get('obj')
        if obj:
            if obj.is_accepted:
                if is_resource_added and not resource_link:
                    raise ValidationError('This field is required!', field_name='resource_link')
                if not is_resource_added and not is_resource_added_notes:
                    raise ValidationError('This field is required!', field_name='is_resource_added_notes')
            else:
                data.pop('is_resource_added', None)
                data.pop('is_resource_added_notes', None)
                data.pop('resource_link', None)
class MeetingFileSchema(ObjectAttrs):
    id = fields.Int()
    download_url = fields.Str()
    name = fields.Str()

    class Meta:
        ordered = True
Esempio n. 7
0
class CreateSubmissionAttrs(ObjectAttrs):
    applicant_email = core_fields.Email(required=False, default=None)
    author = core_fields.Str(required=False, default=None)
    title = core_fields.Str(required=True,
                            faker_type='application title',
                            example='Some App')
    url = core_fields.Url(required=True)
    notes = core_fields.Str(required=True)
    image = core_fields.Base64String(required=False,
                                     default=None,
                                     max_size=settings.IMAGE_UPLOAD_MAX_SIZE)
    datasets = core_fields.List(core_fields.Int(), required=False, default=[])
    external_datasets = core_fields.Nested(ExternalResourceSchema,
                                           required=False,
                                           default={},
                                           many=True)
    keywords = core_fields.List(core_fields.Str(), default='', required=False)
    comment = core_fields.String(required=False,
                                 description='Comment body',
                                 example='Looks unpretty',
                                 default='')

    class Meta:
        strict = True
        ordered = True
        object_type = 'application-submission'
Esempio n. 8
0
class RegistrationApiAttrs(UserUpdateApiAttrs):
    email = fields.Email(required=True, default=None)
    password1 = fields.Str(required=True)
    password2 = fields.Str(required=True)

    class Meta:
        strict = True
        ordered = True
        object_type = 'user'

    @validates_schema
    def validate_data(self, data, **kwargs):
        if 'password1' in data:
            try:
                validate_password(data['password1'])
            except DjangoValidationError as e:
                raise ValidationError(e.error_list[0].message,
                                      field_name='password1',
                                      code=e.error_list[0].code,
                                      field_names=[
                                          'password1',
                                      ])
            if 'password2' in data and data['password1'] != data['password2']:
                raise ValidationError(_('Passwords not match'),
                                      field_name='password1',
                                      field_names=['password1', 'password2'])

    @post_load
    def prepare_data(self, data, **kwargs):
        data = super().prepare_data(data)
        data['password'] = data['password1']
        data.pop('password1')
        data.pop('password2')
        data.pop('subscriptions_report_opt_in', None)
        return data
Esempio n. 9
0
class LogEntryApiAttrs(ObjectAttrs):
    action = fields.Str(attribute='action_name')
    change_timestamp = fields.DateTime()
    change_user_id = fields.Str()
    difference = fields.Method('get_difference')
    message = fields.Str()
    new_value = fields.Method('get_new_value')
    row_id = fields.Int()
    table_name = fields.Str()

    class Meta:
        strict = True
        ordered = True
        object_type = 'history'
        api_path = '/histories'
        url_template = '{api_url}/histories/{ident}'
        model = 'histories.LogEntry'

    def get_difference(self, obj):
        try:
            data = json.loads(obj.difference)
        except ValueError:
            data = {}
        if obj.action_name == 'INSERT':
            for key, val in data.items():
                if isinstance(val, list) and len(val) == 2:
                    data[key] = val[1]
        return data

    def get_new_value(self, obj):
        return self.get_difference(obj)
Esempio n. 10
0
class ChangePasswordApiAttrs(ObjectAttrs):
    old_password = fields.Str(required=True)
    new_password1 = fields.Str(required=True)
    new_password2 = fields.Str(required=True)

    class Meta:
        strict = True
        object_type = 'user'
class NewsletterRulesApiAttrs(ObjectAttrs):
    personal_data_processing = fields.Str()
    personal_data_use = fields.Str()
    personal_data_use_rules = fields.Str()

    class Meta:
        object_type = 'newsletter_rules'
        url_template = '{api_url}/auth/newsletter/subscribe/'
class CourseModuleSchema(ObjectAttrs):
    id = fields.Int()
    type = fields.Str()
    type_name = fields.Str()
    start = fields.Date()
    end = fields.Date()

    class Meta:
        ordered = True
class SearchHistoryApiAttrs(ObjectAttrs, HighlightObjectMixin):
    url = fields.Str()
    query_sentence = fields.Str()
    user = fields.Nested(UserAttrs, many=False)
    modified = fields.Str()

    class Meta:
        object_type = 'searchhistory'
        url_template = '{api_url}/searchhistories/{ident}'
        model = 'searchhistories.SearchHistory'
class InstitutionCSVSchema(CSVSerializer):
    id = fields.Integer(data_key=_('id'), required=True)
    title = fields.Str(data_key=_("Title"), default='')
    institution_type = fields.Str(data_key=_("Institution type"), default='')
    datasets_count = fields.Int(data_key=_("The number of datasets"),
                                default=None)

    class Meta:
        ordered = True
        model = 'organizations.Organization'
Esempio n. 15
0
class SparqlApiAttrs(ObjectAttrs):
    result = fields.Str()
    has_previous = fields.Bool()
    has_next = fields.Bool()
    content_type = fields.Str()
    download_url = fields.Url()

    class Meta:
        object_type = 'sparql'
        ordered = True
Esempio n. 16
0
class DatasetCategoryAttr(ExtSchema):
    id = fields.Str()
    title = TranslatedStr()
    code = fields.Str()

    @ma.pre_dump(pass_many=True)
    def prepare_data(self, data, many, **kwargs):
        if isinstance(data, Manager):
            data = data.all()
        return data
class NotificationSerializer(ExtSchema):
    id = fields.Int()
    verb = fields.Str()
    timestamp = fields.DateTime()
    unread = fields.Bool()
    description = fields.Str()
    user_schedule_id = fields.Int()
    user_schedule_item_id = fields.Int()
    schedule_state = fields.Str()
    schedule_id = fields.Int()
Esempio n. 18
0
class ShowcaseApiAttrs(ObjectAttrs, HighlightObjectMixin):
    category = fields.Str()
    category_name = fields.Method('get_category_name')
    slug = TranslatedStr()
    title = TranslatedStr()
    notes = TranslatedStr()
    author = fields.Str(faker_type='firstname')
    url = fields.Str(faker_type='url')
    image_url = fields.Str(faker_type='image_url')
    image_thumb_url = fields.Str(faker_type='image_thumb_url')
    image_alt = TranslatedStr()
    illustrative_graphics_url = fields.Str()
    illustrative_graphics_alt = TranslatedStr()
    followed = fields.Boolean(faker_type='boolean')
    keywords = KeywordsList(TranslatedStr(), faker_type='tagslist')
    views_count = fields.Integer(faker_type='integer')
    modified = fields.Str(faker_type='datetime')
    created = fields.Str(faker_type='datetime')
    has_image_thumb = fields.Bool()
    main_page_position = fields.Int()
    external_datasets = fields.Nested(ExternalDataset, many=True)
    # application showcase fields:
    is_mobile_app = fields.Bool()
    is_mobile_app_name = fields.Method('get_is_mobile_app_name')
    is_desktop_app = fields.Bool()
    is_desktop_app_name = fields.Method('get_is_desktop_app_name')
    mobile_apple_url = fields.URL()
    mobile_google_url = fields.URL()
    desktop_linux_url = fields.URL()
    desktop_macos_url = fields.URL()
    desktop_windows_url = fields.URL()

    license_type = fields.Str()
    license_type_name = fields.Method('get_license_type_name')
    # api use showcase fields:
    file_url = fields.Str()

    class Meta:
        relationships_schema = ShowcaseApiRelationships
        object_type = 'showcase'
        url_template = '{api_url}/showcases/{ident}'
        model = 'showcases.Showcase'
        ordered = True

    def get_is_desktop_app_name(self, obj):
        return str(_('Desktop App')) if obj.is_desktop_app else ''

    def get_is_mobile_app_name(self, obj):
        return str(_('Mobile App')) if obj.is_mobile_app else ''

    def get_category_name(self, obj):
        return str(Showcase.CATEGORY_NAMES.get(obj.showcase_category, ''))

    def get_license_type_name(self, obj):
        return str(Showcase.LICENSE_TYPE_NAMES.get(obj.license_type, ''))
Esempio n. 19
0
class DatasetCSVSchema(CSVSerializer):
    id = fields.Integer(data_key=_('id'), required=True)
    uuid = fields.Str(data_key=_("uuid"), default='')
    title = fields.Str(data_key=_("title"), default='')
    notes = fields.Str(data_key=_("notes"), default='')
    url = fields.Str(data_key=_("url"), default='')
    update_frequency = fields.Str(data_key=_("Update frequency"), default='')
    institution = fields.Str(data_key=_("Institution"),
                             attribute='organization.id',
                             default='')
    category = fields.Str(data_key=_("Category"), default='')
    status = fields.Str(data_key=_("Status"), default='')
    is_licence_set = fields.Boolean(data_key=_("Conditions for re-use"),
                                    default=None)
    created_by = fields.Int(attribute='created_by.id',
                            data_key=_("created_by"),
                            default=None)
    created = fields.DateTime(data_key=_("created"), default=None)
    modified_by = fields.Int(attribute='modified_by.id',
                             data_key=_("modified_by"),
                             default=None)
    modified = fields.DateTime(data_key=_("modified"), default=None)
    followers_count = fields.Str(data_key=_("The number of followers"),
                                 default=None)

    class Meta:
        ordered = True
        model = 'datasets.Dataset'
class NotificationApiAttrs(ObjectAttrs):
    _type = fields.Str(data_key='type', attribute='type')
    status = fields.Str()
    notification_type = fields.Str()
    created = fields.DateTime()
    ref_value = fields.Str(default='')

    class Meta:
        relationships_schema = NotificationApiRelationships
        object_type = 'notification'
        url_template = '{api_url}/auth/notifications/{ident}'
Esempio n. 21
0
class SparqlNamespaceApiAttrs(ObjectAttrs):
    prefix = fields.Str()
    url = fields.Str()

    class Meta:
        object_type = 'namespace'
        ordered = True

    @staticmethod
    def self_api_url(data):
        return None
class CreateNotificationsAttrs(ObjectAttrs):
    message = fields.Str(required=True, validate=validate.Length(min=1, max=60))
    notification_type = fields.Str(
        required=True, validate=validate.OneOf(
            choices=['all', 'late'],
            error=_('Unsupported notification type. Supported are: %(types)s') % {'types': 'all, late'})
    )

    class Meta:
        object_type = 'notification'
        strict = True
        ordered = True
Esempio n. 23
0
class SubscriptionAttrs(schemas.ExtSchema):
    enable_notifications = fields.Boolean()
    created = fields.DateTime()
    modified = fields.DateTime()
    name = fields.Str(attribute='display_name')
    object_name = fields.Str(attribute='watcher.object_name')
    object_url = fields.Method('get_object_url')
    customfields = fields.Dict()

    def get_object_url(self, obj):
        if obj.watcher.watcher_type == 'model':
            instance = obj.watcher.obj
            return instance.api_url
        return ''
class SubscriptionApiAttrs(ObjectAttrs):
    newsletter_subscription_info = fields.Str(attribute='info')

    class Meta:
        object_type = 'subscription'
        url_template = '{api_url}/auth/subscriptions/{ident}'
        fields = ['email', 'is_active', 'newsletter_subscription_info']
class UserScheduleApiAttrs(ObjectAttrs):
    email = fields.Email(attribute='user.email')
    institution = fields.Str()
    items_count = fields.Int()
    is_ready = fields.Bool()
    is_blocked = fields.Bool()
    recommended_items_count = fields.Int()
    implemented_items_count = fields.Int()
    state = fields.Str()

    class Meta:
        relationships_schema = UserScheduleApiRelationships
        object_type = 'user_schedule'
        url_template = '{api_url}/auth/user_schedules/{ident}'
        ordered = True
        model = 'schedules.UserSchedule'
class CreateNotificationsApiAttrs(ObjectAttrs):
    result = fields.Str()
    success = fields.Bool()

    class Meta:
        object_type = 'result'
        ordered = True
Esempio n. 27
0
class CommentAttrs(ObjectAttrs):
    comment = fields.Str(required=True, example='Looks unpretty')

    class Meta:
        object_type = 'comment'
        url_template = '{api_url}/resources/{data.resource.id}/comments/{ident}'
        relationships_schema = CommentApiRelationships
Esempio n. 28
0
class REQData(schemas.ExtSchema):
    _type = fields.Str(data_key='type', attribute='type', required=True)

    def __init__(
            self, only=None, exclude=(), many=False, context=None,
            load_only=(), dump_only=(), partial=False, unknown=None,
    ):
        super().__init__(only=only, exclude=exclude, many=many, context=context,
                         load_only=load_only, dump_only=dump_only,
                         partial=partial, unknown=unknown)

        _meta = getattr(self, 'Meta', None)

        rel_cls = getattr(_meta, 'relationships_cls', DummyRelationship)
        self.fields['attributes'] = fields.Nested(
            getattr(_meta, 'attrs_cls', DummyAttributes), name='attributes')
        if 'relationships' not in self.fields:
            self.fields['relationships'] = fields.Nested(rel_cls, name='relationships')

        _type = getattr(_meta, '_type', None)

        if _type:
            self.fields['_type'] = fields.Str(required=True, missing=_type,
                                              default=_type, data_key='type')

    @pre_dump(pass_many=False)
    def prepare_attributes(self, data):
        setattr(data, 'attributes', data)
        return data
Esempio n. 29
0
    def __init__(
            self, only=None, exclude=(), many=False, context=None,
            load_only=(), dump_only=(), partial=False, unknown=None,
    ):
        super().__init__(only=only, exclude=exclude, many=many, context=context,
                         load_only=load_only, dump_only=dump_only,
                         partial=partial, unknown=unknown)

        _meta = getattr(self, 'Meta', None)

        rel_cls = getattr(_meta, 'relationship_cls', DummyRelationship)
        links_cls = getattr(_meta, 'links_cls', BaseLinks)
        meta_cls = getattr(_meta, 'meta_cls', BaseMeta)

        _attr_cls = 'attr_short_cls' if many else 'attr_cls'
        self.fields['attributes'] = fields.Nested(
            getattr(_meta, _attr_cls, DummyAttributes), name='attributes')
        if 'relationships' not in self.fields:
            self.fields['relationships'] = fields.Nested(rel_cls, name='relationships')

        self.fields['links'] = fields.Nested(links_cls, name='links')
        self.fields['meta'] = fields.Nested(meta_cls, name='meta')
        _type = getattr(_meta, '_type', None)

        if _type:
            self.fields['_type'] = fields.Str(required=True, missing=_type,
                                              default=_type, data_key='type')
class CreateCommentAttrs(ObjectAttrs):
    text = fields.Str(required=True, validate=validate.Length(min=1))

    class Meta:
        object_type = 'comment'
        strict = True
        ordered = True