class LayerDetailsDTO(Model): """ Describes a layer within the Layer List """ def __init__(self): """ DTO constructor initialise all arrays to empty""" super().__init__() self.layer_info_locales = [] layer_id = IntType(required=True, serialized_name='layerId') layer_name = StringType(required=True, serialized_name='layerName') map_category = StringType(required=True, validators=[is_known_category], serialized_name='mapCategory') layer_source = StringType(required=True, serialized_name='layerSource') layer_type = StringType(required=True, validators=[is_known_type], serialized_name='layerType') layer_style = BaseType(serialized_name='layerStyle') layer_geometry_type = BaseType(required=True, serialized_name='layerGeometryType') # We will either return a LayerInfo object for the specified locale or all locales if no locale is specified layer_info = ModelType(LayerInfoDTO, serialized_name='layerInfo', serialize_when_none=False) layer_info_locales = ListType(ModelType(LayerInfoDTO), serialized_name='layerInfoLocales', serialize_when_none=False)
class Location(Model): latitude = BaseType(required=True) longitude = BaseType(required=True) elevation = BaseType() def validate_latitude(self, data, latitude): if latitude: if not isinstance(latitude, basestring): latitude = "{:.14f}".format(latitude) valid_latitude = COORDINATES_REG_EXP.match(str(latitude)) if (valid_latitude is not None and valid_latitude.group() == str(latitude)): if not -90 <= float(latitude) <= 90: raise ValidationError( u"Invalid value. Latitude must be between -90 and 90 degree." ) else: raise ValidationError( u"Invalid value. Required latitude format 12.0123456789") def validate_longitude(self, data, longitude): if longitude: if not isinstance(longitude, basestring): longitude = "{:.14f}".format(longitude) valid_longitude = COORDINATES_REG_EXP.match(str(longitude)) if (valid_longitude is not None and valid_longitude.group() == str(longitude)): if not -180 <= float(longitude) <= 180: raise ValidationError( u"Invalid value. Longitude must be between -180 and 180 degree." ) else: raise ValidationError( u"Invalid value. Required longitude format 12.0123456789")
class TypeDescriptorBase(InternalTypeDescriptor): __abstract_type_descriptor__ = True class Options(object): serialize_when_none = False required = BooleanType() default = BaseType() serialized_name = StringType() deserialize_from = ListType(StringType()) choices = ListType(BaseType()) serialize_when_none = BooleanType() messages = DictType(StringType()) def init_schematics_type(self, context=None): descriptor_class = self.schematics_type kwargs = self.get_descriptor_kwargs() return descriptor_class(**kwargs) def get_descriptor_kwargs(self): primitive = self.to_primitive() # may be empty if no raw data is provided if primitive is None: return {} return { k: v for k, v in iteritems(primitive) if k not in self.non_kwarg_keys } @property def non_kwarg_keys(self): return {"type"}
class Location(Model): class Options: serialize_when_none = False latitude = BaseType(required=True) longitude = BaseType(required=True) elevation = BaseType()
class ProjectDTO(Model): """ Describes JSON model for a tasking manager project """ project_id = IntType(serialized_name='projectId') project_status = StringType(required=True, serialized_name='projectStatus', validators=[is_known_project_status], serialize_when_none=False) project_priority = StringType(required=True, serialized_name='projectPriority', validators=[is_known_project_priority], serialize_when_none=False) area_of_interest = BaseType(serialized_name='areaOfInterest') tasks = BaseType(serialize_when_none=False) default_locale = StringType(required=True, serialized_name='defaultLocale', serialize_when_none=False) project_info = ModelType(ProjectInfoDTO, serialized_name='projectInfo', serialize_when_none=False) project_info_locales = ListType(ModelType(ProjectInfoDTO), serialized_name='projectInfoLocales', serialize_when_none=False) mapper_level = StringType(required=True, serialized_name='mapperLevel', validators=[is_known_mapping_level]) enforce_mapper_level = BooleanType(required=True, default=False, serialized_name='enforceMapperLevel') enforce_validator_role = BooleanType(required=True, default=False, serialized_name='enforceValidatorRole') private = BooleanType(required=True) entities_to_map = StringType(serialized_name='entitiesToMap') changeset_comment = StringType(serialized_name='changesetComment') due_date = DateTimeType(serialized_name='dueDate') imagery = StringType() josm_preset = StringType(serialized_name='josmPreset', serialize_when_none=False) mapping_types = ListType(StringType, serialized_name='mappingTypes', validators=[is_known_mapping_type]) campaign_tag = StringType(serialized_name='campaignTag') organisation_tag = StringType(serialized_name='organisationTag') license_id = IntType(serialized_name='licenseId') allowed_usernames = ListType(StringType(), serialized_name='allowedUsernames', default=[]) priority_areas = BaseType(serialized_name='priorityAreas') last_updated = DateTimeType(serialized_name='lastUpdated') author = StringType()
class DraftProjectDTO(Model): """ Describes JSON model used for creating draft project """ project_name = StringType(required=True, serialized_name='projectName') area_of_interest = BaseType(required=True, serialized_name='areaOfInterest') tasks = BaseType(required=False) has_arbitrary_tasks = BooleanType(required=True, serialized_name='arbitraryTasks') user_id = IntType(required=True)
class DraftProjectDTO(Model): """ Describes JSON model used for creating draft project """ cloneFromProjectId = IntType(serialized_name="cloneFromProjectId") project_name = StringType(required=True, serialized_name="projectName") area_of_interest = BaseType(required=True, serialized_name="areaOfInterest") tasks = BaseType(required=False) has_arbitrary_tasks = BooleanType(required=True, serialized_name="arbitraryTasks") user_id = IntType(required=True)
class HTTPHelperResponseModel(Model): """ This is the model for the `HTTPHelperResponseHandler` class. When using the `HTTPHelperResponseHandler` class there will be the only acceptable values to create state,This state can in turn be used within the HTTPHelper class """ response = BaseType(required=False, default=None) response_status_code_validation = IntType(required=False, default=None) response_type_validation = BaseType(required=False, default=None) response_schematic_validation = BaseType(required=False, default=None)
class HTTPHelperConnectionModel(Model): """ This is the model for the `HTTPHelperConnectionHandler` class. When using the `HTTPHelperConnectionHandler` class there will be the only acceptable values to create state,This state can in turn be used within the HTTPHelper class """ timeout = IntType(required=False, default=None) ssl_verify = BooleanType(required=False, default=True) retry_policy = BaseType(required=False, default=None) proxy = BaseType(required=False, default=None)
class Schema(Model): multipleOf = FloatType(min_value=0, serialize_when_none=False) # must be present if exclusiveMaximum is present. maximum = FloatType(serialize_when_none=False) exclusiveMaximum = BooleanType(serialize_when_none=False) # must be present if exclusiveMinimum is present. minimum = FloatType(serialize_when_none=False) exclusiveMinimum = BooleanType(serialize_when_none=False) # validation for strings maxLength = IntType(min_value=0, serialize_when_none=False) minLength = IntType(min_value=0, serialize_when_none=False) pattern = RegularExpression(serialize_when_none=False) # validation for arrays additionalItems = PolyModelType([BooleanType(), "Schema"], serialize_when_none=False) items_ = PolyModelType(["Schema", ListType(ModelType("Schema"))], serialized_name="items", deserialize_from=["items"], serialize_when_none=False) maxItems = IntType(min_value=0, serialize_when_none=False) minItems = IntType(min_value=0, serialize_when_none=False) uniqueItems = BooleanType(serialize_when_none=False) # validation for objects maxProperties = IntType(min_value=0, serialize_when_none=False) minProperties = IntType(min_value=0, serialize_when_none=False) # TODO: allow boolean type. additionalProperties = PolyModelType( ["Schema"], # claim_function=_claim_additional_properties, required=False, serialize_when_none=False) properties = DictType(ModelType("Schema"), serialize_when_none=False) patternProperties = DictType(ModelType("Schema"), serialize_when_none=False) dependencies = ModelType("Schema", serialize_when_none=False) required = ListType(StringType(), min_size=1, serialize_when_none=False) # any type enum = ListType(BaseType(), serialize_when_none=False) type = StringType(serialize_when_none=False, required=True) format = DataTypeFormat(serialize_when_none=False) allOf = ListType(ModelType("Schema"), serialize_when_none=False) anyOf = ListType(ModelType("Schema"), serialize_when_none=False) oneOf = ListType(ModelType("Schema"), serialize_when_none=False) # not = ModelType("Schema") definitions = ModelType("Schema", serialize_when_none=False) title = StringType(serialize_when_none=False) description = StringType(serialize_when_none=False) default = BaseType(serialize_when_none=False) collectionFormat = StringType( choices={"csv", "ssv", "tsv", "pipes", "multi"}, serialize_when_none=False)
class HTTPHelperModel(Model): """ This is the model for the `HTTPHelper` class. When using the `HTTPHelper` class there will be the only acceptable values to create state and kick off the request """ mock_enable = BooleanType(required=False, default=False) mock_status = IntType(required=False, default=None) mock_text = BaseType(required=False, default=None) endpoint = StringType(required=True, default=None) auth_data = DictType(BaseType, required=False, default=None) auth_type = StringType(required=False, choices=authentication_choices, default=None) session_auth_data = BaseType(required=False, default=None) session_auth_type = StringType(required=False, choices=authentication_choices, default=None) body = BaseType(required=False, default=None) proxy = BaseType(required=False, default=None) headers = DictType(StringType, required=False, default=None) session_headers = DictType(StringType, required=False, default=None) query = DictType(StringType, required=False, default=None) timeout = IntType(required=False, default=None) ssl_verify = BooleanType(required=False, default=True) retry_policy = BaseType(required=False, default=None) request_schematic_validation = BaseType(required=False, default=None) request_type_validation = BaseType(required=False, default=None) response_status_code_validation = IntType(required=False, default=None) response_type_validation = BaseType(required=False, default=None) response_schematic_validation = BaseType(required=False, default=None)
class HTTPHelperSessionModel(Model): """ This is the model for the `HTTPHelperSessionHandler` class. When using the `HTTPHelperSessionHandler` class there will be the only acceptable values to create state, This state can in turn be used within the HTTPHelper class """ mock_enable = BooleanType(required=False, default=False) mock_status = IntType(required=False, default=None) mock_text = BaseType(required=False, default=None) headers = DictType(StringType, default=dict({})) auth_data = BaseType(required=False, default=None) auth_type = StringType(required=False, choices=authentication_choices, default=None)
class HTTPHelperRequestModel(Model): """ This is the model for the `HTTPHelperRequestHandler` class. When using the `HTTPHelperRequestHandler` class there will be the only acceptable values to create state, This state can in turn be used within the HTTPHelper class """ method = StringType(required=True) endpoint = StringType(required=True, default=None) query = DictType(StringType, default=dict({})) headers = DictType(StringType, default=dict({})) body = BaseType(required=False, default=None) auth_data = DictType(BaseType, required=False, default=None) auth_type = StringType(required=False, choices=authentication_choices, default=None) request_schematic_validation = BaseType(required=False, default=None) request_type_validation = BaseType(required=False, default=None)
class Identifier(Model): scheme = StringType(required=True, choices=ORA_CODES) id = BaseType(required=True) legalName = StringType() legalName_en = StringType() legalName_ru = StringType() uri = URLType()
class ProjectSummary(Model): """ Model used for PM dashboard """ project_id = IntType(required=True, serialized_name='projectId') area = FloatType(serialized_name='projectArea(in sq.km)') name = StringType() author = StringType(serialized_name='createdBy') created = DateTimeType() due_date = DateTimeType() last_updated = DateTimeType(serialized_name='lastUpdated') priority = StringType(serialized_name='projectPriority') campaign_tag = StringType(serialized_name='campaignTag') organisation_tag = StringType(serialized_name='organisationTag') entities_to_map = StringType(serialized_name='entitiesToMap') changeset_comment = StringType(serialized_name='changesetComment') percent_mapped = IntType(serialized_name='percentMapped') percent_validated = IntType(serialized_name='percentValidated') percent_bad_imagery = IntType(serialized_name='percentBadImagery') aoi_centroid = BaseType(serialized_name='aoiCentroid') mapper_level = StringType(serialized_name='mapperLevel') mapper_level_enforced = BooleanType(serialized_name='mapperLevelEnforced') validator_level_enforced = BooleanType(serialized_name='validatorLevelEnforced') short_description = StringType(serialized_name='shortDescription') total_mappers = IntType(serialized_name='totalMappers') total_tasks = IntType(serialized_name='totalTasks') total_comments = IntType(serialized_name='totalComments') total_mapping_time = IntType(serialized_name='totalMappingTime') total_validation_time = IntType(serialized_name='totalValidationTime') total_time_spent = StringType(serialized_name='totalTimeSpent') average_mapping_time=StringType(serialized_name='averageMappingTime') average_validation_time=StringType(serialized_name='averageValidationTime') status = StringType()
class Identifier(Model): scheme = StringType(required=True, choices=IDENTIFIER_CODES) # The scheme that holds the unique identifiers used to identify the item being identified. id = BaseType(required=True) # The identifier of the organization in the selected scheme. legalName = StringType() # The legally registered name of the organization. legalName_en = StringType() legalName_ru = StringType() uri = URLType() # A URI to identify the organization.
class ResponseDataModel(Model): code = IntType( required=True, metadata=ValidatorDoc( '系统返回值代码,成功为0,失败为非零。 \n参见 https://fy0.github.io/slim/#/quickstart/query_and_modify?id=返回值 ' )) data = BaseType(required=True, metadata=ValidatorDoc('数据项')) msg = StringType(metadata=ValidatorDoc('文本提示信息'))
class ProjectSummary(Model): """ Model used for PM dashboard """ project_id = IntType(required=True, serialized_name='projectId') name = StringType() campaign_tag = StringType(serialized_name='campaignTag') percent_mapped = IntType(serialized_name='percentMapped') percent_validated = IntType(serialized_name='percentValidated') created = DateTimeType() last_updated = DateTimeType(serialized_name='lastUpdated') aoi_centroid = BaseType(serialized_name='aoiCentroid')
class MetaFieldDescriptor(BaseModel): type = ModelType(TypeInfo, required=True) # Invalidate field when value is None or is not supplied. Default: False. required = BooleanType() # When no data is provided default to this value. May be a callable. # Default: None. default = BaseType() # The name of this field defaults to the class attribute used in the model. # However if the field has another name in foreign data set this argument. # Serialized data will use this value for the key name too. serialized_name = StringType() # A name or list of named fields for which foreign data sets are searched # to provide a value for the given field. This only effects inbound data. deserialize_from = ListType(StringType()) # A list of valid choices. This is the last step of the validator chain. choices = ListType(BaseType()) # A list of callables. Each callable receives the value after it has been # converted into a rich python type. Default: [] # validators = ListType(StringType()) # Dictates if the field should appear in the serialized data even if the # value is None. Default: True serialize_when_none = BooleanType() # Override the error messages with a dict. You can also do this by # subclassing the Type and defining a MESSAGES dict attribute on the class. # A metaclass will merge all the MESSAGES and override the resulting dict # with instance level messages and assign to self.messages. messages = DictType(StringType()) def schematics_field_descriptor(self, context=None): return self.type.schematics_field_descriptor(context=context, **self._kwargs()) def requires_context(self): return self.type.requires_context() def _kwargs(self): return { k: v for k, v in iteritems(self.to_primitive()) if k not in ["type"] }
class ProjectSearchResultsDTO(Model): """ Contains all results for the search criteria """ def __init__(self): """ DTO constructor initialise all arrays to empty""" super().__init__() self.results = [] self.map_results = [] map_results = BaseType(serialized_name='mapResults') results = ListType(ModelType(ListSearchResultDTO)) pagination = ModelType(Pagination)
class ProductModel(Model): description = StringType() quantity = FloatType() business_unity = StringType() total_value = FloatType() unit_value = FloatType() product_code = StringType() ncm_code = StringType() cfop = StringType() total_tax = FloatType() metadata = BaseType()
class ItemValidator(Model): name = StringType() country = StringType(validators=[is_valid_country_iso]) time = StringType() fromCurrency = ListType(StringType(validators=[is_valid_currency_iso])) toCurrency = ListType(StringType(validators=[is_valid_currency_iso])) unit = StringType(validators=[is_valid_unit]) buyMargin = ListType(StringType(validators=[is_valid_margin])) sellMargin = ListType(StringType(validators=[is_valid_margin])) isCrossInverted = BooleanType() exchangeUnit = BaseType()
class Model(SchematicsModel): class Options(object): """Export options for Document.""" serialize_when_none = False roles = { "default": blacklist("__parent__"), "embedded": blacklist("__parent__"), } __parent__ = BaseType() def __eq__(self, other): if isinstance(other, self.__class__): for k in self._fields: if k != '__parent__' and self.get(k) != other.get(k): return False return True return NotImplemented def convert(self, raw_data, **kw): """ Converts the raw data into richer Python constructs according to the fields on the model """ value = convert(self.__class__, raw_data, **kw) for i, j in value.items(): if isinstance(j, list): for x in j: set_parent(x, self) else: set_parent(j, self) return value def to_patch(self, role=None): """ Return data as it would be validated. No filtering of output unless role is defined. """ field_converter = lambda field, value: field.to_primitive(value) data = export_loop(self.__class__, self, field_converter, role=role, raise_error_on_role=True, print_none=True) return data def get_role(self): root = self.__parent__ while root.__parent__ is not None: root = root.__parent__ request = root.request return 'Administrator' if request.authenticated_role == 'Administrator' else 'edit'
class HTTPApiErrorResponse(Model): status_code = IntType(required=True) code = StringType(required=True, min_length=1) data = BaseType() @classmethod def from_error(cls, error): return cls({ 'status_code': error.status_code, 'code': error.code, 'data': error.data, })
class ProjectDTO(Model): """ Describes JSON model for a tasking manager project """ project_id = IntType(serialized_name='projectId') project_status = StringType(required=True, serialized_name='projectStatus', validators=[is_known_project_status], serialize_when_none=False) project_priority = StringType(required=True, serialized_name='projectPriority', validators=[is_known_project_priority], serialize_when_none=False) area_of_interest = BaseType(serialized_name='areaOfInterest') aoi_bbox = ListType(FloatType, serialized_name='aoiBBOX') tasks = BaseType(serialize_when_none=False) default_locale = StringType(required=True, serialized_name='defaultLocale', serialize_when_none=False) project_info = ModelType(ProjectInfoDTO, serialized_name='projectInfo', serialize_when_none=False) project_info_locales = ListType(ModelType(ProjectInfoDTO), serialized_name='projectInfoLocales', serialize_when_none=False) mapper_level = StringType(required=True, serialized_name='mapperLevel', validators=[is_known_mapping_level]) enforce_mapper_level = BooleanType(required=True, default=False, serialized_name='enforceMapperLevel') enforce_validator_role = BooleanType(required=True, default=False, serialized_name='enforceValidatorRole') enforce_random_task_selection = BooleanType(required=True, default=False, serialized_name='enforceRandomTaskSelection') allow_non_beginners = BooleanType(required=False, default=False, serialized_name='allowNonBeginners') private = BooleanType(required=True) entities_to_map = StringType(serialized_name='entitiesToMap') changeset_comment = StringType(serialized_name='changesetComment') osmcha_filter_id = StringType(serialized_name='osmchaFilterId') due_date = DateTimeType(serialized_name='dueDate') imagery = StringType() josm_preset = StringType(serialized_name='josmPreset', serialize_when_none=False) mapping_types = ListType(StringType, serialized_name='mappingTypes', validators=[is_known_mapping_type]) campaign_tag = StringType(serialized_name='campaignTag') organisation_tag = StringType(serialized_name='organisationTag') license_id = IntType(serialized_name='licenseId') allowed_usernames = ListType(StringType(), serialized_name='allowedUsernames', default=[]) priority_areas = BaseType(serialized_name='priorityAreas') created = DateTimeType() last_updated = DateTimeType(serialized_name='lastUpdated') author = StringType() active_mappers = IntType(serialized_name='activeMappers') task_creation_mode = StringType(required=True, serialized_name='taskCreationMode', validators=[is_known_task_creation_mode], serialize_when_none=False) mapping_editors = ListType(StringType, min_size=1, required=True, serialized_name='mappingEditors', validators=[is_known_editor]) validation_editors = ListType(StringType, min_size=1, required=True, serialized_name='validationEditors', validators=[is_known_editor])
class Identifier(Model): class Options: serialize_when_none = False scheme = URLType( ) # The scheme that holds the unique identifiers used to identify the item being identified. id = BaseType( ) # The identifier of the organization in the selected scheme. legalName = StringType( ) # The legally registered name of the organization. legalName_en = StringType() legalName_ru = StringType() uri = URLType() # A URI to identify the organization.
class ProjectSearchResultDTO(Model): """ Describes one search result""" project_id = IntType(required=True, serialized_name='projectId') locale = StringType(required=True) name = StringType(default='') short_description = StringType(serialized_name='shortDescription', default='') mapper_level = StringType(required=True, serialized_name='mapperLevel') priority = StringType(required=True) aoi_centroid = BaseType(serialized_name='aoiCentroid') organisation_tag = StringType(serialized_name='organisationTag') campaign_tag = StringType(serialized_name='campaignTag') percent_mapped = IntType(serialized_name='percentMapped') percent_validated = IntType(serialized_name='percentValidated')
class FinishResponse(Model): check_output: Optional[IndividualData] = ModelType(IndividualData, default=None) result: StringType(default=None) errors: List[Error] = ListType(ModelType(Error), default=[]) warnings: List[Warn] = ListType(ModelType(Warn), default=[]) provider_data = BaseType(required=True) @staticmethod def error(errors: List[Error]) -> 'RunCheckResponse': res = FinishResponse() res.errors = errors return res
class ProjectSummary(Model): """ Model used for PM dashboard """ project_id = IntType(required=True, serialized_name='projectId') name = StringType() campaign_tag = StringType(serialized_name='campaignTag') percent_mapped = IntType(serialized_name='percentMapped') percent_validated = IntType(serialized_name='percentValidated') created = DateTimeType() last_updated = DateTimeType(serialized_name='lastUpdated') aoi_centroid = BaseType(serialized_name='aoiCentroid') mapper_level = StringType(serialized_name='mapperLevel') organisation_tag = StringType(serialized_name='organisationTag') short_description = StringType(serialized_name='shortDescription') status = StringType()
class Model(SchematicsModel): class Options(object): """Export options for Document.""" serialize_when_none = False roles = { "default": blacklist("__parent__"), "embedded": blacklist("__parent__"), } __parent__ = BaseType() def __init__(self, *args, **kwargs): super(Model, self).__init__(*args, **kwargs) for i, j in self._data.items(): if isinstance(j, list): for x in j: set_parent(x, self) else: set_parent(j, self) def __eq__(self, other): if isinstance(other, self.__class__): for k in self._fields: if k != '__parent__' and self.get(k) != other.get(k): return False return True return NotImplemented def to_patch(self, role=None, *arg, **kwargs): """ Return data as it would be validated. No filtering of output unless role is defined. """ field_converter = lambda field, value, context: field.to_primitive( value, context) data = export_loop(self.__class__, self, field_converter=field_converter, role=role, *arg, **kwargs) return data def get_role(self): root = self.__parent__ while root.__parent__ is not None: root = root.__parent__ request = root.request return 'Administrator' if request.authenticated_role == 'Administrator' else 'edit'
def __init__(self, enum, **kwargs): BaseType.__init__(self, **kwargs) self.enum = enum self.mode = kwargs.get('default', None)