class ResourceDCATSchema(ResourceMixin, Schema): ext_ident = Str(validate=validate.Length(max=36)) title_pl = Str() title_en = Str(allow_none=True) description_pl = Str(allow_none=True) description_en = Str(allow_none=True) created = DateTime(allow_none=True) modified = DateTime(allow_none=True) link = URL() format = Str() file_mimetype = Str(allow_none=True) @pre_load(pass_many=True) def prepare_multi_data(self, data, **kwargs): for res in data: if res.get('modified') and not res.get('created'): res['created'] = res['modified'] if not res.get('title_pl') and res.get('title_en'): res['title_pl'] = res['title_en'] return data @post_load(pass_many=True) def postprocess_data(self, data, **kwargs): for res in data: if res['created'] is None: res.pop('created') if res['modified'] is None: res.pop('modified') return data class Meta: ordered = True unknown = EXCLUDE
class Product(Schema): class Meta: ordered = True _id = UUID(required=False, allow_none=False, missing=uuid.uuid4) name = String(required=True, description='Nome do produto.', validate=Length(min=1, max=1000)) description = String(required=True, description='Descrição do produto.', validate=Length(min=1, max=1000)) price = Float(required=True, description='Valor do produto.') enabled = Bool(required=False, description='Se o produto está ativado ou desativado.', missing=True) created_at = DateTime(required=False, allow_none=True, description='Criado em.', missing=datetime.now, format=DATETIME_FORMAT) updated_at = DateTime(required=False, allow_none=True, description='Atualizado em.', format=DATETIME_FORMAT) deleted_at = DateTime(required=False, allow_none=True, description='Deletado em.', format=DATETIME_FORMAT)
class IssueSchema(Schema): id = Integer() user = Nested(UserSchema()) user_id = Integer() user_url = Url(relative=True) bike = Nested(BikeSchema(), allow_none=True) bike_identifier = BytesField(as_string=True, allow_none=True) bike_url = Url(relative=True, allow_none=True) opened_at = DateTime() closed_at = DateTime() description = String(required=True) resolution = String(allow_none=True) status = EnumField(IssueStatus, default=IssueStatus.OPEN) @validates_schema def assert_url_included_with_foreign_key(self, data, **kwargs): """ Asserts that when a user_id or bike_id is sent that a user_url or bike_url is sent with it. """ if "user_id" in data and "user_url" not in data: raise ValidationError( "User ID was included, but User URL was not.") if "bike_id" in data and "bike_url" not in data: raise ValidationError( "Bike ID was included, but Bike URL was not.")
class TagSchema(Schema): id = Integer(dump_only=True) created_at = DateTime(dump_only=True) updated_at = DateTime(dump_only=True) author = Function(lambda o: o.user.username) tag = String(strip=True, validate=Length(max=16))
class UserSchema(Schema): id = Integer(required=True) username = String(required=True) email = String(required=True) isActive = Boolean(required=True, attribute='is_active') createdAt = DateTime(attribute='created_at') updatedAt = DateTime(attribute='updated_at')
class LicenseSwitchScheme(BaseModelScheme): user_email = Str(validate=[validate.Length(max=128)]) type = Int() ip = Str(required=True, allow_none=False, validate=[validate.Length(max=16), validate.Regexp(IP_REGEXP)]) switch_port = Int() minute_count = Int() amount = Int() license_switch_uuid = Str(validate=[validate.Length(max=36)]) package_switch_uuid = Str(validate=[ validate.Length(max=36), lambda value: _valid('PackageSwitch', 'package_switch_uuid', value) ]) user_uuid = Str(validate=[ validate.Length( max=36), lambda value: _valid('User', 'user_uuid', value) ]) start_time = DateTime() end_time = DateTime() duration = Choice() ordered_amount = Int() cost = Float() package = Nested('PackageSwitchScheme', many=False) enabled = Bool() switch_uuid = Str(validate=[ validate.Length( max=64), lambda value: _valid('DnlLicenseInfo', 'uuid', value) ]) class Meta: model = model.LicenseSwitch fields = ('package_switch_uuid', 'ip', 'start_time', 'duration', 'switch_uuid')
class UserScheme(BaseModelScheme): user_id = Str() email = Email(required=True, allow_none=False, validate=[ validate.Email(error='Incorrect email address'), lambda value: _valid_unique('User', 'email', value) ]) password = Str(validate=[validate.Length(max=72)]) is_admin = Bool() last_login = DateTime() is_active = Bool() created_on = DateTime() phone = Str(required=True, allow_none=False, validate=[ validate.Regexp(PHONE_REGEXP), lambda value: _valid_unique('User', 'phone', value) ]) logo_file_uuid = FileSchemeField(model.FileModel, 'User', 'logo', required=False) logo = Nested('FileModelScheme', many=False) class Meta: model = model.User fields = ('email', 'passwd', 'is_admin', 'is_active', 'logo_file_uuid')
class TestRunSchema(Schema): id = Integer() name = String(required=True) started_at = DateTime(dump_to='startedAt', load_from='startedAt') ends_at = DateTime(dump_to='endsAt', load_from='endsAt') finished_at = DateTime(required=False, allow_none=True, dump_to='finishedAt', load_from='finishedAt') time_limit = Integer(load_from='timeLimit', dump_to='timeLimit', attribute='time_limit', required=False, allow_none=True) question_answers = List(Nested(TestRunQuestionSchema), dump_to='questionAnswers', load_from='questionAnswers') @post_load def create_class(self, value): return TestRunDto(**value)
class EraseBasic(EventWithOneDevice): start_time = DateTime(required=True, data_key='startTime') end_time = DateTime(required=True, data_key='endTime') secure_random_steps = Integer(validate=Range(min=0), required=True, data_key='secureRandomSteps') clean_with_zeros = Boolean(required=True, data_key='cleanWithZeros') steps = NestedOn('Step', many=True, required=True)
class RoleSchema(Schema): id = Integer(required=True) code = String(required=True) name = String(required=True) isActive = Boolean(required=True, attribute='is_active') createdAt = DateTime(attribute='created_at') updatedAt = DateTime(attribute='updated_at') hasAllPermissions = Boolean(required=True, attribute='has_all_permissions')
class Step(Schema): type = String(description='Only required when it is nested.') start_time = DateTime(required=True, data_key='startTime') end_time = DateTime(required=True, data_key='endTime') secure_random_steps = Integer(validate=Range(min=0), required=True, data_key='secureRandomSteps') clean_with_zeros = Boolean(required=True, data_key='cleanWithZeros') error = Boolean(default=False, description='Did the event fail?')
class ReservationUserEventSchema(Schema): id = Number() title = String() url = String() start_dt = DateTime() end_dt = DateTime() class Meta: strict = True # TODO: remove with marshmallow 3
class XMLResourceSchema(ResourceMixin, Schema): ext_ident = Str(data_key='extIdent', validate=validate.Length(max=36), required=True) int_ident = Int(data_key='intIdent') status = Str(data_key='@status', validate=validate.OneOf(choices=['draft', 'published'])) link = URL(data_key='url') title_pl = Str() title_en = Str() description_pl = Str() description_en = Str() availability = Str(validate=validate.OneOf(choices=['local', 'remote'])) data_date = Date(data_key='dataDate') created = DateTime(data_key='created', allow_none=True) modified = DateTime(data_key='lastUpdateDate', allow_none=True) special_signs = List(Str()) class Meta: ordered = True unknown = EXCLUDE @pre_load def prepare_data(self, data, **kwargs): if 'title' in data and isinstance(data.get('title'), dict): data['title_en'] = data['title'].get('english', '') data['title_pl'] = data['title'].get('polish', '') if 'description' in data and isinstance(data.get('description'), dict): data['description_en'] = data['description'].get('english', '') data['description_pl'] = data['description'].get('polish', '') data['availability'] = data.get('availability', 'local') special_signs = data.pop('specialSigns', {}) if 'specialSign' in special_signs: data['special_signs'] = special_signs['specialSign'] return data @validates_schema def validate_int_ident(self, data, **kwargs): int_ident = data.get('int_ident') dataset_int_ident = self.context.get('dataset_int_ident') organization = self.context['organization'] if int_ident and not dataset_int_ident: raise ValidationError( _('intIdent value for related dataset is also required!'), field_name='int_ident') if int_ident and dataset_int_ident and organization and not Resource.raw.filter( id=int_ident, dataset_id=dataset_int_ident, dataset__organization=organization).exists(): msg = _( 'Resource with id: %(r_id)s, dataset\'s id: %(d_id)s and institution "%(ins)s" was not found.' ) % { 'r_id': int_ident, 'd_id': dataset_int_ident, "ins": organization.title } raise ValidationError(msg, field_name='int_ident')
class UserSchema(Schema): id = Str() email = Str() is_admin = Boolean() first_name = Str() last_name = Str() age = Integer() country = Str() registered_at = DateTime(format=DATETIME_FORMAT) last_login_at = DateTime(format=DATETIME_FORMAT)
class Thing(Schema): type = String(description='Only required when it is nested.') url = URL(dump_only=True, description='The URL of the resource.') same_as = List(URL(dump_only=True), dump_only=True, data_key='sameAs') updated = DateTime('iso', dump_only=True, description=m.Thing.updated) created = DateTime('iso', dump_only=True, description=m.Thing.created) @post_load def remove_type(self, data: dict): data.pop('type', None)
class Cart(Schema): class Meta: ordered = True _id = UUID(required=False, allow_none=False, missing=uuid.uuid4) products = List(Nested(Product()), required=False, missing=[]) customer_id = UUID(required=True) created_at = DateTime(required=False, allow_none=True, description='Criado em.', missing=datetime.now, format=DATETIME_FORMAT) updated_at = DateTime(required=False, allow_none=True, description='Atualizado em.', format=DATETIME_FORMAT)
class ExerciseSchema(Schema): id = Integer(dump_only=True) name = String(required=True) sets = Integer(required=True) reps = Integer(required=True) plan = Integer(required=False) day_number = Integer(required=False) created_at = DateTime(dump_only=True) updated_at = DateTime(dump_only=True) deleted_at = DateTime(dump_only=True)
class Metric(Schema): """ This schema filter dates for search the metrics """ start_time = DateTime(data_key='start_time', required=True, description="Start date for search metrics") end_time = DateTime(data_key='end_time', required=True, description="End date for search metrics")
class UserSchema(Schema): id = Integer(dump_only=True) first_name = String(required=True, validate=Length(1, 64)) last_name = String(required=True, validate=Length(1, 64)) birth_date = Date(required=True) email = Email(required=True) password = String(required=True, validate=Length(5, 32), load_only=True) created_at = DateTime(dump_only=True) updated_at = DateTime(dump_only=True) deleted_at = DateTime(dump_only=True)
class Customer(Schema): class Meta: ordered = True _id = UUID(required=False, allow_none=False, missing=uuid.uuid4) name = String(required=True, description='Nome do cliente.', validate=Length(min=1, max=100)) email = Email(required=True, description='Email do client') password = String(required=True, description='Senha do cliente.', validate=Length(min=1, max=100)) document = String(required=True, description='Documento do cliente.', validate=Length(min=1, max=100)) created_at = DateTime(required=False, allow_none=True, description='Criado em.', missing=datetime.now, format=DATETIME_FORMAT) updated_at = DateTime(required=False, allow_none=True, description='Atualizado em.', format=DATETIME_FORMAT)
class Thing(Schema): type = String(description=_type_description) same_as = List(URL(dump_only=True), dump_only=True, data_key='sameAs') updated = DateTime('iso', dump_only=True, description=m.Thing.updated.comment) created = DateTime('iso', dump_only=True, description=m.Thing.created.comment) @post_load def remove_type(self, data: dict): data.pop('type', None)
class UserSchema(BaseModelSchema): """ User schema serializer. """ id = Int(dump_only=True) login = Str(required=True, validate=[validate.Length(min=4)]) name = Str(required=True, validate=[validate.Length(min=2)]) email = Email(required=True, validate=[validate.Length(min=5)]) created_at = DateTime(dump_only=True) updated_at = DateTime(dump_only=True) is_active = Boolean(required=True) is_admin = Boolean() class Meta(BaseModelSchema.Meta): model = User exclude = ("password", )
class RentalSchema(Schema): id = Integer(required=True) user = Nested(UserSchema()) user_id = Integer() user_url = Url(relative=True) bike = Nested(BikeSchema()) bike_identifier = BytesField(as_string=True) bike_url = Url(relative=True) events = Nested(RentalUpdateSchema(), many=True) start_time = DateTime(required=True) end_time = DateTime() cancel_time = DateTime() is_active = Boolean(required=True) price = Float() distance = Float() @validates_schema def assert_end_time_with_price(self, data, **kwargs): """ Asserts that when a rental is complete both the price and end time are included. """ if "price" in data and "end_time" not in data: raise ValidationError( "If the price is included, you must also include the end time." ) elif "price" not in data and "end_time" in data: raise ValidationError( "If the end time is included, you must also include the price." ) if "price" in data and "estimated_price" in data: raise ValidationError( "Rental should have one of either price or estimated_price.") @validates_schema def assert_url_included_with_foreign_key(self, data, **kwargs): """ Asserts that when a user_id or bike_id is sent that a user_url or bike_url is sent with it. """ if "user_id" in data and "user_url" not in data: raise ValidationError( "User ID was included, but User URL was not.") if "bike_id" in data and "bike_url" not in data: raise ValidationError( "Bike ID was included, but Bike URL was not.")
class TourBookingCreateRequestSchema(BaseRequestSchema): tour_id = Integer(data_key='tourId', required=True) start_date = DateTime(data_key='startDate', format='%d-%m-%Y', required=True) note = String(validate=[ValidateLength(max=255)]) user_id = String(data_key='userId', required=True, validate=[ValidateLength(min=1, max=255)]) guests = Integer(required=True) price_per_participant = Integer(data_key='pricePerParticipant', required=True) grand_total = Integer(data_key='grandTotal', required=True) guest_name = String(data_key='guestName', required=True, validate=[ValidateLength(min=1, max=255)]) guest_phone_number = String(data_key='guestPhoneNumber', required=True, validate=[ValidateLength(min=1, max=255)]) guest_email = String(data_key='guestEmail', required=True, validate=[ValidateLength(min=1, max=255)]) @post_load() def refine_data(self, data, **kwargs): data['start_date'] = data.get('start_date').strftime('%Y-%m-%d') data['status'] = 'PENDING_PAYMENT' return data
class TradeDocument(Thing): __doc__ = m.TradeDocument.__doc__ id = Integer(description=m.TradeDocument.id.comment, dump_only=True) date = DateTime(required=False, description=m.TradeDocument.date.comment) id_document = SanitizedStr(data_key='documentId', default='', description=m.TradeDocument.id_document.comment) description = SanitizedStr(default='', description=m.TradeDocument.description.comment, validate=validate.Length(max=500)) file_name = SanitizedStr(data_key='filename', default='', description=m.TradeDocument.file_name.comment, validate=validate.Length(max=100)) file_hash = SanitizedStr(data_key='hash', default='', description=m.TradeDocument.file_hash.comment, validate=validate.Length(max=64)) url = URL(description=m.TradeDocument.url.comment) lot = NestedOn('Lot', only_query='id', description=m.TradeDocument.lot.__doc__) trading = SanitizedStr(dump_only=True, description='') weight = Float(required=False, description=m.TradeDocument.weight.comment) total_weight = Float(required=False, description=m.TradeDocument.weight.comment)
class BackendConfigurationSchema(BaseSchema): """Schema for BackendConfiguration.""" # Required properties. backend_name = String(required=True) backend_version = String(required=True, validate=Regexp("[0-9]+.[0-9]+.[0-9]+$")) n_qubits = Integer(required=True, validate=Or([Equal(-1), Range(min=1)])) basis_gates = List(String(), required=True, validate=Length(min=1)) gates = Nested(GateConfigSchema, required=True, many=True) local = Boolean(required=True) simulator = Boolean(required=True) conditional = Boolean(required=True) open_pulse = Boolean(required=True, validate=Equal(False)) # Optional properties. sample_name = String() coupling_map = List(List(Integer(), validate=Length(min=1)), validate=Length(min=1)) n_registers = Integer(validate=Range(min=1)) register_map = List(List(Integer(validate=OneOf([0, 1])), validate=Length(min=1)), validate=Length(min=1)) configurable = Boolean() credits_required = Boolean() online_date = DateTime() display_name = String() description = String() tags = List(String())
class DataWipeDocument(Thing): __doc__ = m.DataWipeDocument.__doc__ id = Integer(description=m.DataWipeDocument.id.comment, dump_only=True) url = URL(required=False, description=m.DataWipeDocument.url.comment) success = Boolean(required=False, default=False, description=m.DataWipeDocument.success.comment) software = SanitizedStr(description=m.DataWipeDocument.software.comment) date = DateTime(data_key='endTime', required=False, description=m.DataWipeDocument.date.comment) id_document = SanitizedStr( data_key='documentId', required=False, default='', description=m.DataWipeDocument.id_document.comment) file_name = SanitizedStr(data_key='filename', default='', description=m.DataWipeDocument.file_name.comment, validate=validate.Length(max=100)) file_hash = SanitizedStr(data_key='hash', default='', description=m.DataWipeDocument.file_hash.comment, validate=validate.Length(max=64)) @post_load def get_trade_document(self, data): data['document_type'] = 'DataWipeDocument'
class QuestionSchema(Schema): nodeId = str() slug = str() language = str() addedOn = DateTime() type = Str() options = List(Str())
class MessageReplySchema(Schema): """Marshmallow schema for message replies.""" reply_id36 = ID36() markdown = Markdown() rendered_html = String(dump_only=True) created_time = DateTime(dump_only=True)
class PreQuestionSchema(Schema): nodeId = Str() slug = Str() langauge = Str() text = Str() randomize = Bool() addedOn = DateTime()