class FilesSchema(Schema): """Files metadata schema.""" enabled = fields.Bool() default_preview = SanitizedUnicode() order = fields.List(SanitizedUnicode())
class PiValidatePipeVarsSchema(Schema): run_pipe = fields.Bool(required=True) url = fields.Str(required=True) version = fields.Str(required=True) policy = fields.Nested(PiPolicySchema)
class RHUserSearch(RHProtected): """Search for users based on given criteria""" def _serialize_pending_user(self, entry): first_name = entry.data.get('first_name') or '' last_name = entry.data.get('last_name') or '' full_name = '{} {}'.format(first_name, last_name).strip() or 'Unknown' affiliation = entry.data.get('affiliation') or '' email = entry.data['email'].lower() ext_id = '{}:{}'.format(entry.provider.name, entry.identifier) # detailed data to put in redis to create a pending user if needed self.externals[ext_id] = { 'first_name': first_name, 'last_name': last_name, 'email': email, 'affiliation': affiliation, 'phone': entry.data.get('phone') or '', 'address': entry.data.get('address') or '', } # simple data for the search results return { '_ext_id': ext_id, 'id': None, 'identifier': 'ExternalUser:{}'.format(ext_id), 'email': email, 'affiliation': affiliation, 'full_name': full_name, } def _serialize_entry(self, entry): if isinstance(entry, User): return search_result_schema.dump(entry) else: return self._serialize_pending_user(entry) def _process_pending_users(self, results): cache = GenericCache('external-user') for entry in results: ext_id = entry.pop('_ext_id', None) if ext_id is not None: cache.set(ext_id, self.externals[ext_id], 86400) @use_kwargs( { 'first_name': fields.Str(validate=validate.Length(min=1)), 'last_name': fields.Str(validate=validate.Length(min=1)), 'email': fields.Str(validate=lambda s: len(s) > 3 and '@' in s), 'affiliation': fields.Str(validate=validate.Length(min=1)), 'exact': fields.Bool(missing=False), 'external': fields.Bool(missing=False), 'favorites_first': fields.Bool(missing=False) }, validate=validate_with_message( lambda args: args.viewkeys( ) & {'first_name', 'last_name', 'email', 'affiliation'}, 'No criteria provided')) def _process(self, exact, external, favorites_first, **criteria): matches = search_users(exact=exact, include_pending=True, external=external, **criteria) self.externals = {} results = sorted((self._serialize_entry(entry) for entry in matches), key=itemgetter('full_name')) if favorites_first: favorites = {u.id for u in session.user.favorite_users} results.sort(key=lambda x: x['id'] not in favorites) total = len(results) results = results[:10] self._process_pending_users(results) return jsonify(users=results, total=total)
class OrderDeleteSchema(abstract.AbstractDeleteSchema): data_erasure = fields.Bool(data_key="dataErasure", required=False)
class V10PresentationExchangeSchema(BaseExchangeSchema): """Schema for de/serialization of v1.0 presentation exchange records.""" class Meta: """V10PresentationExchangeSchema metadata.""" model_class = V10PresentationExchange presentation_exchange_id = fields.Str( required=False, description="Presentation exchange identifier", example=UUIDFour.EXAMPLE, # typically a UUID4 but not necessarily ) connection_id = fields.Str( required=False, description="Connection identifier", example=UUIDFour.EXAMPLE, # typically a UUID4 but not necessarily ) thread_id = fields.Str( required=False, description="Thread identifier", example=UUIDFour.EXAMPLE, # typically a UUID4 but not necessarily ) initiator = fields.Str( required=False, description="Present-proof exchange initiator: self or external", example=V10PresentationExchange.INITIATOR_SELF, validate=validate.OneOf(["self", "external"]), ) role = fields.Str( required=False, description="Present-proof exchange role: prover or verifier", example=V10PresentationExchange.ROLE_PROVER, validate=validate.OneOf(["prover", "verifier"]), ) state = fields.Str( required=False, description="Present-proof exchange state", example=V10PresentationExchange.STATE_VERIFIED, ) presentation_proposal_dict = fields.Dict( required=False, description="Serialized presentation proposal message") presentation_request = fields.Dict( required=False, description="(Indy) presentation request (also known as proof request)", ) presentation_request_dict = fields.Dict( required=False, description="Serialized presentation request message") presentation = fields.Dict( required=False, description="(Indy) presentation (also known as proof)") verified = fields.Str( # tag: must be a string required=False, description="Whether presentation is verified: true or false", example="true", validate=validate.OneOf(["true", "false"]), ) auto_present = fields.Bool( required=False, description="Prover choice to auto-present proof as verifier requests", example=False, ) error_msg = fields.Str(required=False, description="Error message", example="Invalid structure")
class V20PresExRecordSchema(BaseExchangeSchema): """Schema for de/serialization of v2.0 presentation exchange records.""" class Meta: """V20PresExRecordSchema metadata.""" model_class = V20PresExRecord pres_ex_id = fields.Str( required=False, description="Presentation exchange identifier", example=UUIDFour.EXAMPLE, # typically a UUID4 but not necessarily ) connection_id = fields.Str( required=False, description="Connection identifier", example=UUIDFour.EXAMPLE, # typically a UUID4 but not necessarily ) thread_id = fields.Str( required=False, description="Thread identifier", example=UUIDFour.EXAMPLE, # typically a UUID4 but not necessarily ) initiator = fields.Str( required=False, description="Present-proof exchange initiator: self or external", example=V20PresExRecord.INITIATOR_SELF, validate=validate.OneOf([ getattr(V20PresExRecord, m) for m in vars(V20PresExRecord) if m.startswith("INITIATOR_") ]), ) role = fields.Str( required=False, description="Present-proof exchange role: prover or verifier", example=V20PresExRecord.ROLE_PROVER, validate=validate.OneOf([ getattr(V20PresExRecord, m) for m in vars(V20PresExRecord) if m.startswith("ROLE_") ]), ) state = fields.Str( required=False, description="Present-proof exchange state", validate=validate.OneOf([ getattr(V20PresExRecord, m) for m in vars(V20PresExRecord) if m.startswith("STATE_") ]), ) pres_proposal = fields.Nested( V20PresProposalSchema(), required=False, description="Presentation proposal message", ) pres_request = fields.Nested( V20PresRequestSchema(), required=False, description="Presentation request message", ) pres = fields.Nested( V20PresSchema(), required=False, description="Presentation message", ) by_format = fields.Nested( Schema.from_dict( { "pres_proposal": fields.Dict(required=False), "pres_request": fields.Dict(required=False), "pres": fields.Dict(required=False), }, name="V20PresExRecordByFormatSchema", ), required=False, description= ("Attachment content by format for proposal, request, and presentation" ), dump_only=True, ) verified = fields.Str( # tag: must be a string required=False, description="Whether presentation is verified: 'true' or 'false'", example="true", validate=validate.OneOf(["true", "false"]), ) auto_present = fields.Bool( required=False, description="Prover choice to auto-present proof as verifier requests", example=False, ) auto_verify = fields.Bool( required=False, description="Verifier choice to auto-verify proof presentation") error_msg = fields.Str(required=False, description="Error message", example="Invalid structure")
class OperatorServiceSchema(ServiceSchema): skip_crd = fields.Bool(allow_none=True, data_key="skipCRD") @staticmethod def schema_config(): return OperatorServiceConfig
class CreateEventSchema(EventSchema): name = fields.String(required=True) description = fields.String(required=True) start = fields.DateTime(required=True) end = fields.DateTime(required=True) request_promotion = fields.Bool()
class FlowerSchema(Schema): blooming = fields.Bool(required=True)
class FileSystemElementForSearchResultSchema(Schema): path = fields.Str() basename = fields.Str() is_directory = fields.Bool() size = fields.Int()
class FileSystemElementForDirectoryTreeSchema(Schema): basename = fields.Str() is_directory = fields.Bool() size = fields.Int()
class CoverCardSchema(CardActionSchema): cover = fields.Bool()
class AgentSchema(BaseSchema): namespace = fields.Str(allow_none=True, data_key=POLYAXON_KEYS_K8S_NAMESPACE) is_replica = fields.Bool(allow_none=True, data_key=POLYAXON_KEYS_AGENT_IS_REPLICA) compressed_logs = fields.Bool(allow_none=True, data_key=POLYAXON_KEYS_AGENT_COMPRESSED_LOGS) sidecar = fields.Nested( PolyaxonSidecarContainerSchema, allow_none=True, data_key=POLYAXON_KEYS_AGENT_SIDECAR, ) init = fields.Nested(PolyaxonInitContainerSchema, allow_none=True, data_key=POLYAXON_KEYS_AGENT_INIT) artifacts_store = fields.Nested( ConnectionTypeSchema, allow_none=True, data_key=POLYAXON_KEYS_AGENT_ARTIFACTS_STORE, ) connections = fields.List( fields.Nested(ConnectionTypeSchema), allow_none=True, data_key=POLYAXON_KEYS_AGENT_CONNECTIONS, ) app_secret_name = fields.Str( allow_none=True, data_key=POLYAXON_KEYS_K8S_APP_SECRET_NAME, ) agent_secret_name = fields.Str( allow_none=True, data_key=POLYAXON_KEYS_AGENT_SECRET_NAME, ) runs_sa = fields.Str( allow_none=True, data_key=POLYAXON_KEYS_AGENT_RUNS_SA, ) @staticmethod def schema_config(): return AgentConfig @validates_schema @check_partial def validate_connection(self, data, **kwargs): validate_agent_config(data.get("artifacts_store"), data.get("connections")) @pre_load def pre_validate(self, data, **kwargs): connections = data.get(POLYAXON_KEYS_AGENT_CONNECTIONS) try: connections = parser.get_dict( key=POLYAXON_KEYS_AGENT_CONNECTIONS, value=connections, is_list=True, is_optional=True, ) except PolyaxonSchemaError as e: raise ValidationError("Received an invalid connections") from e if connections: data[POLYAXON_KEYS_AGENT_CONNECTIONS] = connections artifacts_store = data.get(POLYAXON_KEYS_AGENT_ARTIFACTS_STORE) try: artifacts_store = parser.get_dict( key=POLYAXON_KEYS_AGENT_ARTIFACTS_STORE, value=artifacts_store, is_optional=True, ) except PolyaxonSchemaError as e: raise ValidationError( "Received an invalid artifacts store `{}`".format( artifacts_store)) from e if artifacts_store: data[POLYAXON_KEYS_AGENT_ARTIFACTS_STORE] = artifacts_store sidecar = data.get(POLYAXON_KEYS_AGENT_SIDECAR) try: sidecar = parser.get_dict(key=POLYAXON_KEYS_AGENT_SIDECAR, value=sidecar, is_optional=True) except PolyaxonSchemaError as e: raise ValidationError( "Received an invalid sidecar `{}`".format(sidecar)) from e if sidecar: data[POLYAXON_KEYS_AGENT_SIDECAR] = sidecar init = data.get(POLYAXON_KEYS_AGENT_INIT) try: init = parser.get_dict(key=POLYAXON_KEYS_AGENT_INIT, value=init, is_optional=True) except PolyaxonSchemaError as e: raise ValidationError( "Received an invalid init `{}`".format(init)) from e if init: data[POLYAXON_KEYS_AGENT_INIT] = init return data
class TableMetadataOptionsResponseSchema(Schema): deferrable = fields.Bool() initially = fields.Bool() match = fields.Bool() ondelete = fields.Bool() onupdate = fields.Bool()
class AuthorSchema(StrictSchema): name = fields.Str(required=True, validate=validate.Length(min=1, max=50)) email = fields.Email(validate=validate.Length(min=1, max=50)) maintainer = fields.Bool(default=False) url = fields.Url(validate=validate.Length(min=1, max=255))
user_settings_schema, db) from grant.utils.validate import is_z_address_valid blueprint = Blueprint('user', __name__, url_prefix='/api/v1/users') @blueprint.route("/me", methods=["GET"]) @auth.requires_auth def get_me(): dumped_user = self_user_schema.dump(g.current_user) return dumped_user @blueprint.route("/<user_id>", methods=["GET"]) @query({ "withProposals": fields.Bool(required=False, missing=None), "withComments": fields.Bool(required=False, missing=None), "withFunded": fields.Bool(required=False, missing=None), "withPending": fields.Bool(required=False, missing=None), "withArbitrated": fields.Bool(required=False, missing=None), "withRequests": fields.Bool(required=False, missing=None), "withRejectedPermanently": fields.Bool(required=False, missing=None) }) def get_user(user_id, with_proposals, with_comments, with_funded, with_pending, with_arbitrated, with_requests, with_rejected_permanently): user = User.get_by_id(user_id) if user: result = user_schema.dump(user) authed_user = auth.get_authed_user() is_self = authed_user and authed_user.id == user.id if with_requests:
class UserOutputSchema(Schema): username = fields.String() role = fields.Int() isVerified = fields.Bool()
class RoomSchema(ma.ModelSchema): id = fields.Int() name = fields.Str() description = fields.Str() private = fields.Bool() language = fields.Str()
class DeletionSchema(Schema): success = fields.Bool() code = fields.Int(required=True) label = fields.Str() message = fields.Str() params = fields.List(fields.Str())
class TodoItemSchema(Schema): id = fields.Str() task = fields.Str() completed = fields.Bool() created = fields.DateTime()
class HooksSchema(ServiceSchema): load_fixtures = fields.Bool(allow_none=True) @staticmethod def schema_config(): return HooksConfig
class ModifiableSettingsSchema(Schema): """This is the Schema for the settings that can be modified via the API""" premium_should_sync = fields.Bool(missing=None) include_crypto2crypto = fields.Bool(missing=None) anonymized_logs = fields.Bool(missing=None) submit_usage_analytics = fields.Bool(missing=None) ui_floating_precision = fields.Integer( strict=True, validate=webargs.validate.Range( min=0, max=8, error='Floating numbers precision in the UI must be between 0 and 8', ), missing=None, ) taxfree_after_period = TaxFreeAfterPeriodField(missing=None) balance_save_frequency = fields.Integer( strict=True, validate=webargs.validate.Range( min=1, error='The number of hours after which balances should be saved should be >= 1', ), missing=None, ) include_gas_costs = fields.Bool(missing=None) # TODO: Add some validation to this field historical_data_start = fields.String(missing=None) # TODO: Add some validation to this field # even though it gets validated since we try to connect to it eth_rpc_endpoint = fields.String(missing=None) main_currency = FiatAssetField(missing=None) # TODO: Add some validation to this field date_display_format = fields.String(missing=None) kraken_account_type = KrakenAccountTypeField(missing=None) active_modules = fields.List(fields.String(), missing=None) @validates_schema # type: ignore def validate_settings_schema( # pylint: disable=no-self-use self, data: Dict[str, Any], **_kwargs: Any, ) -> None: if data['active_modules'] is not None: for module in data['active_modules']: if module not in AVAILABLE_MODULES: raise ValidationError( message=f'{module} is not a valid module', field_name='active_modules', ) @post_load # type: ignore def transform_data( # pylint: disable=no-self-use self, data: Dict[str, Any], **_kwargs: Any, ) -> Any: return ModifiableDBSettings( premium_should_sync=data['premium_should_sync'], include_crypto2crypto=data['include_crypto2crypto'], anonymized_logs=data['anonymized_logs'], ui_floating_precision=data['ui_floating_precision'], taxfree_after_period=data['taxfree_after_period'], balance_save_frequency=data['balance_save_frequency'], include_gas_costs=data['include_gas_costs'], historical_data_start=data['historical_data_start'], eth_rpc_endpoint=data['eth_rpc_endpoint'], main_currency=data['main_currency'], date_display_format=data['date_display_format'], submit_usage_analytics=data['submit_usage_analytics'], kraken_account_type=data['kraken_account_type'], active_modules=data['active_modules'], )
class RequestSchema(Schema): id = fields.Int() name = fields.Str(description="name") bool_field = fields.Bool() list_field = fields.List(fields.Int())
class YumRepoSchema(Schema): name = fields.Str(validate=validate.Length(max=1024)) gpgcheck = fields.Bool() enabled = fields.Bool() base_url = fields.Str(validate=validate.Length(max=2048))
class CommonConfigSchema(Schema): """ Common methods for JobConfigSchema and PackageConfigSchema """ config_file_path = fields.String(missing=None) specfile_path = fields.String(missing=None) downstream_package_name = fields.String(missing=None) upstream_project_url = fields.String(missing=None) upstream_package_name = fields.String(missing=None) upstream_ref = fields.String(missing=None) upstream_tag_template = fields.String() archive_root_dir_template = fields.String() dist_git_url = NotProcessedField( additional_message="it is generated from dist_git_base_url and downstream_package_name", load_only=True, ) dist_git_base_url = fields.String(mising=None) dist_git_namespace = fields.String(missing=None) create_tarball_command = fields.List(fields.String(), missing=None) current_version_command = fields.List(fields.String(), missing=None) allowed_gpg_keys = fields.List(fields.String(), missing=None) spec_source_id = fields.Method( deserialize="spec_source_id_fm", serialize="spec_source_id_serialize" ) synced_files = fields.Nested(SyncFilesConfigSchema) actions = ActionField(default={}) create_pr = fields.Bool(default=True) sync_changelog = fields.Bool(default=False) patch_generation_ignore_paths = fields.List(fields.String(), missing=None) notifications = fields.Nested(NotificationsSchema) copy_upstream_release_description = fields.Bool(default=False) sources = fields.List(fields.Nested(SourceSchema), missing=None) # For backwards compatibility with packit-service. Should be removed once # packit-service uses dump method. def dump_config(self, *args, **kwargs): return self.dump(*args, **kwargs) # For backwards compatibility with packit-service. Should be removed once # packit-service uses load method. def load_config(self, *args, **kwargs): return self.load(*args, **kwargs) @staticmethod def spec_source_id_serialize(value: PackageConfig): return value.spec_source_id @staticmethod def spec_source_id_fm(value: Union[str, int]): """ method used in spec_source_id field.Method If value is int, it is transformed int -> "Source" + str(int) ex. 1 -> "Source1" :return str: prepends "Source" in case input value is int """ if value: try: value = int(value) except ValueError: # not a number pass else: # is a number! value = f"Source{value}" return value
class BaseLossSchema(Schema): input_layer = Tensor(allow_none=True) output_layer = Tensor(allow_none=True) weights = fields.Float(default=1.0, missing=1.0) name = fields.Str(allow_none=True) collect = fields.Bool(default=True, missing=True)
class PiPolicySchema(Schema): enabled = fields.Bool(required=True) enforcing = fields.Bool(required=True) version = fields.Str(required=True)
class DeploymentSchema(BaseCamelSchema): deployment_type = fields.Str(allow_none=True, validate=validate.OneOf( DeploymentTypes.VALUES)) deployment_chart = fields.Str( allow_none=True, validate=validate.OneOf(DeploymentCharts.VALUES), default=DeploymentCharts.PLATFORM, ) deployment_version = fields.Str(allow_none=True) release_name = fields.Str(allow_none=True) namespace = fields.Str(allow_none=True) rbac = fields.Nested(RBACSchema, allow_none=True) polyaxon_secret = fields.Str(allow_none=True) internal_token = fields.Str(allow_none=True) password_length = fields.Int(allow_none=True) ssl = fields.Nested(SSLSchema, allow_none=True) encryption_secret = fields.Str(allow_none=True) platform_secret = fields.Str(allow_none=True) agent_secret = fields.Str(allow_none=True) timezone = fields.Str(allow_none=True) environment = fields.Str(allow_none=True) ingress = fields.Nested(IngressSchema, allow_none=True) user = fields.Nested(RootUserSchema, allow_none=True) node_selector = fields.Dict(allow_none=True) tolerations = fields.List(fields.Dict(allow_none=True), allow_none=True) affinity = fields.Dict(allow_none=True) limit_resources = fields.Bool(allow_none=True) global_replicas = fields.Int(allow_none=True) global_concurrency = fields.Int(allow_none=True) gateway = fields.Nested(ApiServiceSchema, allow_none=True) api = fields.Nested(ApiServiceSchema, allow_none=True) streams = fields.Nested(ApiServiceSchema, allow_none=True) scheduler = fields.Nested(WorkerServiceSchema, allow_none=True) compiler = fields.Nested(WorkerServiceSchema, allow_none=True) worker = fields.Nested(WorkerServiceSchema, allow_none=True) beat = fields.Nested(ServiceSchema, allow_none=True) agent = fields.Nested(AgentServiceSchema, allow_none=True) operator = fields.Nested(OperatorServiceSchema, allow_none=True) init = fields.Nested(HelperServiceSchema, allow_none=True) sidecar = fields.Nested(HelperServiceSchema, allow_none=True) tables_hook = fields.Nested(ServiceSchema, allow_none=True) clean_hooks = fields.Nested(ServiceSchema, allow_none=True) api_hooks = fields.Nested(ServiceSchema, allow_none=True) hooks = fields.Nested(HooksSchema, allow_none=True) flower = fields.Nested(ServiceSchema, allow_none=True) postgresql = fields.Nested(PostgresqlSchema, allow_none=True) redis = fields.Nested(RedisSchema, allow_none=True) rabbitmq = fields.Nested(RabbitmqSchema, data_key="rabbitmq-ha", allow_none=True) broker = fields.Str(allow_none=True, validate=validate.OneOf(["redis", "rabbitmq"])) email = fields.Nested(EmailSchema, allow_none=True) ldap = fields.Raw(allow_none=True) metrics = fields.Raw(allow_none=True) image_pull_secrets = fields.List(fields.Str(), allow_none=True) host_name = fields.Str(allow_none=True) allowed_hosts = fields.List(fields.Str(), allow_none=True) include_host_ips = fields.Bool(allow_none=True) intervals = fields.Nested(IntervalsSchema, allow_none=True) artifacts_store = fields.Nested(ConnectionTypeSchema, allow_none=True) connections = fields.List(fields.Nested(ConnectionTypeSchema), allow_none=True) notification_connections = fields.List( fields.Nested(ConnectionTypeSchema), allow_none=True, ) log_level = fields.Str(allow_none=True) security_context = fields.Nested(SecurityContextSchema, allow_none=True) external_services = fields.Nested(ExternalServicesSchema, allow_none=True) debug_mode = fields.Bool(allow_none=True) organization_key = fields.Str(allow_none=True) auth = fields.Nested(AuthSchema, allow_none=True) ui = fields.Nested(UISchema, allow_none=True) include_chart_revision = fields.Bool(allow_none=True) operators = fields.Nested(OperatorsSchema, allow_none=True) istio = fields.Dict(allow_none=True) # Pending validation dns = fields.Raw(allow_none=True) @staticmethod def schema_config(): return DeploymentConfig @validates_schema def validate_connections(self, data, **kwargs): validate_connections(data.get("artifacts_store"), data.get("connections")) @validates_schema def validate_deployment(self, data, **kwargs): validate_deployment_chart( deployment_chart=data.get("deployment_chart"), agent=data.get("agent"), environment=data.get("environment"), ) validate_platform_deployment( postgresql=data.get("postgresql"), redis=data.get("redis"), rabbitmq=data.get("rabbitmq"), broker=data.get("broker"), scheduler=data.get("scheduler"), compiler=data.get("compiler"), worker=data.get("worker"), beat=data.get("beat"), external_services=data.get("external_services"), ) validate_gateway(data.get("gateway")) if data.get("deployment_chart") == DeploymentCharts.AGENT: wrong_agent_deployment_keys( polyaxon_secret=data.get("polyaxon_secret"), internal_token=data.get("internal_token"), password_length=data.get("password_length"), user=data.get("user"), global_replicas=data.get("global_replicas"), global_concurrency=data.get("global_concurrency"), api=data.get("api"), scheduler=data.get("scheduler"), worker=data.get("worker"), beat=data.get("beat"), tables_hook=data.get("tables_hook"), api_hooks=data.get("api_hooks"), hooks=data.get("hooks"), flower=data.get("flower"), postgresql=data.get("postgresql"), redis=data.get("redis"), rabbitmq=data.get("rabbitmq"), broker=data.get("broker"), email=data.get("email"), ldap=data.get("ldap"), intervals=data.get("intervals"), metrics=data.get("metrics"), organization_key=data.get("organization_key"), ui=data.get("ui"), )
class MethodResponseSchema(Schema): success = fields.Bool() message = fields.Str() data = fields.Dict() version = fields.Str()
class JoinResponse(BaseSerializer): showGameNotFound = fields.Bool(required=True) redirectLink = fields.Str(required=True)