class MailOutput(Schema): html_body = fields.Str() plain_body = fields.Str() subject = fields.Str() # # This is because Email is not typed on marshmallow to = fields.Email() # type: ignore cc = fields.List(fields.Email()) # type: ignore bcc = fields.List(fields.Email()) # type: ignore
def admin_user_output(many: bool = True) -> Schema: attributes: MarshmallowSchema = {} attributes["uuid"] = fields.UUID() # This is because Email is not typed on marshmallow attributes["email"] = fields.Email() # type: ignore attributes["name"] = fields.Str() attributes["surname"] = fields.Str() attributes["first_login"] = fields.DateTime(allow_none=True, format=ISO8601UTC) attributes["last_login"] = fields.DateTime(allow_none=True, format=ISO8601UTC) attributes["last_password_change"] = fields.DateTime(allow_none=True, format=ISO8601UTC) attributes["is_active"] = fields.Boolean() attributes["privacy_accepted"] = fields.Boolean() attributes["roles"] = fields.List(fields.Nested(Role)) attributes["expiration"] = fields.DateTime(allow_none=True, format=ISO8601UTC) if Connector.authentication_service == "neo4j": attributes["belongs_to"] = fields.Neo4jRelationshipToSingle( Group, data_key="group") else: attributes["belongs_to"] = fields.Nested(Group, data_key="group") if custom_fields := mem.customizer.get_custom_output_fields(None): attributes.update(custom_fields)
def group_users_output() -> Schema: attributes: MarshmallowSchema = {} # This is because Email is not typed on marshmallow attributes["email"] = fields.Email() # type: ignore attributes["name"] = fields.Str() attributes["surname"] = fields.Str() attributes["roles"] = fields.List(fields.Nested(Role)) if custom_fields := mem.customizer.get_custom_output_fields(None): attributes.update(custom_fields)
class ListInput(Schema): elements = fields.List( fields.Str(), required=True, metadata={ "autocomplete_endpoint": "/api/tests/autocomplete", "autocomplete_id_bind": "my_id", "autocomplete_label_bind": "my_label", "autocomplete_show_id": True, }, )
class PhenotypeOutputSchema(Schema): uuid = fields.Str(required=True) name = fields.Str(required=True) age = fields.Integer() sex = fields.Str(required=True, validate=validate.OneOf(SEX)) hpo = fields.List(fields.Nested(Hpo), required=False) birth_place = fields.Nested(GeoData, required=False) relationships = fields.Nested( Relationships, metadata={"description": "family relationships between phenotypes"}, )
class Input1(Schema): # Note: This is a replacement of the normal DelimitedList defined by rapydo unique_delimited_list = fields.DelimitedList( fields.Str(), delimiter=",", required=True, unique=True ) # Note: This is a replacement of the normal List list defined by rapydo advanced_list = fields.List( fields.Str(), required=True, unique=True, min_items=2, )
def getInputSchema(request: FlaskRequest, is_post: bool) -> Type[Schema]: graph = neo4j.get_instance() # as defined in Marshmallow.schema.from_dict attributes: Dict[str, Union[fields.Field, type]] = {} attributes["name"] = fields.Str(required=True) attributes["age"] = fields.Integer(allow_none=True, validate=validate.Range(min=0)) attributes["sex"] = fields.Str( required=True, validate=validate.OneOf(SEX), metadata={"description": ""} ) attributes["hpo"] = fields.List( fields.Str(), metadata={ "label": "HPO", "autocomplete_endpoint": "/api/hpo", "autocomplete_show_id": True, "autocomplete_id_bind": "hpo_id", "autocomplete_label_bind": "label", }, ) geodata_keys = [] geodata_labels = [] for g in graph.GeoData.nodes.all(): geodata_keys.append(g.uuid) geodata_labels.append(g.province) if len(geodata_keys) == 1: default_geodata = geodata_keys[0] else: default_geodata = None attributes["birth_place"] = fields.Str( required=False, allow_none=True, metadata={ "label": "Birth Place", "description": "", }, dump_default=default_geodata, validate=validate.OneOf(choices=geodata_keys, labels=geodata_labels), ) return Schema.from_dict(attributes, name="PhenotypeDefinition")
def get_output_schema(): # as defined in Marshmallow.schema.from_dict attributes: Dict[str, Union[fields.Field, type]] = {} attributes["uuid"] = fields.UUID() attributes["email"] = fields.Email() attributes["name"] = fields.Str() attributes["surname"] = fields.Str() attributes["first_login"] = fields.DateTime(allow_none=True, format=ISO8601UTC) attributes["last_login"] = fields.DateTime(allow_none=True, format=ISO8601UTC) attributes["last_password_change"] = fields.DateTime(allow_none=True, format=ISO8601UTC) attributes["is_active"] = fields.Boolean() attributes["privacy_accepted"] = fields.Boolean() attributes["roles"] = fields.List(fields.Nested(Roles)) attributes["expiration"] = fields.DateTime(allow_none=True, format=ISO8601UTC) attributes["belongs_to"] = fields.Nested(Group, data_key="group") if custom_fields := mem.customizer.get_custom_output_fields(None): attributes.update(custom_fields)
def admin_user_input(request: FlaskRequest, is_post: bool) -> Type[Schema]: is_admin = HTTPTokenAuth.is_session_user_admin(request, auth) attributes: MarshmallowSchema = {} if is_post: # This is because Email is not typed on marshmallow attributes["email"] = fields.Email( # type: ignore required=is_post, validate=validate.Length(max=100)) attributes["name"] = fields.Str( required=is_post, validate=validate.Length(min=1), metadata={"label": "First Name"}, ) attributes["surname"] = fields.Str( required=is_post, validate=validate.Length(min=1), metadata={"label": "Last Name"}, ) attributes["password"] = fields.Str( required=is_post, validate=validate.Length(min=auth.MIN_PASSWORD_LENGTH), metadata={"password": True}, ) if Connector.check_availability("smtp"): attributes["email_notification"] = fields.Bool( metadata={"label": "Notify password by email"}) attributes["is_active"] = fields.Bool( dump_default=True, required=False, metadata={"label": "Activate user"}, ) roles = {r.name: r.description for r in auth.get_roles()} if not is_admin and RoleEnum.ADMIN.value in roles: roles.pop(RoleEnum.ADMIN.value) attributes["roles"] = fields.List( fields.Str(validate=validate.OneOf( choices=[r for r in roles.keys()], labels=[r for r in roles.values()], )), dump_default=[auth.default_role], required=False, unique=True, metadata={ "label": "Roles", "description": "", "extra_descriptions": auth.role_descriptions, }, ) group_keys = [] group_labels = [] for g in auth.get_groups(): group_keys.append(g.uuid) group_labels.append(f"{g.shortname} - {g.fullname}") if len(group_keys) == 1: default_group = group_keys[0] else: default_group = None attributes["group"] = fields.Str( required=is_post, dump_default=default_group, validate=validate.OneOf(choices=group_keys, labels=group_labels), metadata={ "label": "Group", "description": "The group to which the user belongs", }, ) attributes["expiration"] = fields.DateTime( required=False, allow_none=True, metadata={ "label": "Account expiration", "description": "This user will be blocked after this date", }, ) if custom_fields := mem.customizer.get_custom_input_fields( request=request, scope=mem.customizer.ADMIN): attributes.update(custom_fields)
def test_responses(self, faker: Faker) -> None: class MySchema(Schema): name = fields.Str() f = "myfield" assert ( ResponseMaker.get_schema_type(f, fields.Str(metadata={"password": True})) == "password" ) assert ResponseMaker.get_schema_type(f, fields.Bool()) == "boolean" assert ResponseMaker.get_schema_type(f, fields.Boolean()) == "boolean" assert ResponseMaker.get_schema_type(f, fields.Date()) == "date" assert ResponseMaker.get_schema_type(f, fields.DateTime()) == "datetime" assert ResponseMaker.get_schema_type(f, fields.AwareDateTime()) == "datetime" assert ResponseMaker.get_schema_type(f, fields.NaiveDateTime()) == "datetime" assert ResponseMaker.get_schema_type(f, fields.Decimal()) == "number" # This is because Email is not typed on marshmallow assert ResponseMaker.get_schema_type(f, fields.Email()) == "email" # type: ignore assert ResponseMaker.get_schema_type(f, fields.Float()) == "number" assert ResponseMaker.get_schema_type(f, fields.Int()) == "int" assert ResponseMaker.get_schema_type(f, fields.Integer()) == "int" assert ResponseMaker.get_schema_type(f, fields.Number()) == "number" assert ResponseMaker.get_schema_type(f, fields.Str()) == "string" assert ResponseMaker.get_schema_type(f, fields.String()) == "string" assert ResponseMaker.get_schema_type(f, fields.Dict()) == "dictionary" assert ResponseMaker.get_schema_type(f, fields.List(fields.Str())) == "string[]" assert ResponseMaker.get_schema_type(f, fields.Nested(MySchema())) == "nested" # Unsupported types, fallback to string assert ResponseMaker.get_schema_type(f, fields.URL()) == "string" assert ResponseMaker.get_schema_type(f, fields.Url()) == "string" assert ResponseMaker.get_schema_type(f, fields.UUID()) == "string" # assert ResponseMaker.get_schema_type(f, fields.Constant("x")) == "string" assert ResponseMaker.get_schema_type(f, fields.Field()) == "string" # assert ResponseMaker.get_schema_type(f, fields.Function()) == "string" # assert ResponseMaker.get_schema_type(f, fields.Mapping()) == "string" # assert ResponseMaker.get_schema_type(f, fields.Method()) == "string" # assert ResponseMaker.get_schema_type(f, fields.Raw()) == "string" # assert ResponseMaker.get_schema_type(f, fields.TimeDelta()) == "string" assert not ResponseMaker.is_binary(None) assert not ResponseMaker.is_binary("") assert not ResponseMaker.is_binary("application/json") assert ResponseMaker.is_binary("application/octet-stream") assert ResponseMaker.is_binary("application/x-bzip") assert ResponseMaker.is_binary("application/x-bzip2") assert ResponseMaker.is_binary("application/pdf") assert ResponseMaker.is_binary("application/msword") assert ResponseMaker.is_binary("application/rtf") assert ResponseMaker.is_binary("application/x-tar") assert ResponseMaker.is_binary("application/gzip") assert ResponseMaker.is_binary("application/zip") assert ResponseMaker.is_binary("application/x-7z-compressed") assert not ResponseMaker.is_binary("text/plain") assert not ResponseMaker.is_binary("text/css") assert not ResponseMaker.is_binary("text/csv") assert not ResponseMaker.is_binary("text/html") assert not ResponseMaker.is_binary("text/javascript") assert not ResponseMaker.is_binary("text/xml") assert ResponseMaker.is_binary("image/gif") assert ResponseMaker.is_binary("image/jpeg") assert ResponseMaker.is_binary("image/png") assert ResponseMaker.is_binary("image/svg+xml") assert ResponseMaker.is_binary("image/tiff") assert ResponseMaker.is_binary("image/webp") assert ResponseMaker.is_binary("image/bmp") assert ResponseMaker.is_binary("image/aac") assert ResponseMaker.is_binary("audio/midi") assert ResponseMaker.is_binary("audio/mpeg") assert ResponseMaker.is_binary("audio/wav") assert ResponseMaker.is_binary("audio/anyother") assert ResponseMaker.is_binary("video/mpeg") assert ResponseMaker.is_binary("video/ogg") assert ResponseMaker.is_binary("video/webm") assert ResponseMaker.is_binary("video/anyother") assert ResponseMaker.is_binary("video/anyother") assert not ResponseMaker.is_binary(faker.pystr()) response = EndpointResource.response("", code=200) assert response[1] == 200 # type: ignore response = EndpointResource.response(None, code=200) assert response[1] == 204 # type: ignore response = EndpointResource.response(None, code=200, head_method=True) assert response[1] == 200 # type: ignore
class Relationships(Schema): mother = fields.Nested(FamilyMembers, required=False) father = fields.Nested(FamilyMembers, required=False) sons = fields.List(fields.Nested(FamilyMembers, required=False), required=False)
class InputSchema(Schema): # lowercase key without label defined. label will be key.title() in schema mystr = fields.Str(required=True, validate=validate.Length(min=4)) # non-lowercase key without label defined. label will be == to key in schema MYDATE = fields.Date(required=True) MYDATETIME = fields.AwareDateTime( required=True, format=ISO8601UTC, default_timezone=pytz.utc, validate=validate.Range( max=datetime.now(pytz.utc).replace(hour=23, minute=59, second=59), min=datetime(1900, 1, 1, tzinfo=pytz.utc), max_inclusive=True, error="Invalid date", ), ) myint_exclusive = fields.Int( required=True, # Explicit label definition... but missing description validate=validate.Range( min=1, max=10, min_inclusive=False, max_inclusive=False ), metadata={ "label": "Int exclusive field", }, ) myint_inclusive = fields.Int( required=True, # Both label and description explicit definition validate=validate.Range(min=1, max=10), metadata={ "label": "Int inclusive field", "description": "This field accepts values in a defined range", }, ) myselect = fields.Str( required=True, validate=validate.OneOf(choices=["a", "b"], labels=["A", "B"]), ) myselect2 = fields.Str( required=True, # Wrong definition, number labels < number of choices # Labels will be ignored and replaced by choices validate=validate.OneOf(choices=["a", "b"], labels=["A"]), ) mymaxstr = fields.Str(required=True, validate=validate.Length(max=7)) myequalstr = fields.Str(required=True, validate=validate.Length(equal=6)) # Note: requests (from pytest) has to json-dump the arrays and objects, # but the normal Marshmallow fields does not json-load the inputs # fields.Nested is a replacement of the default Nested field with the ability # to receive json dumped data from requests or pytest mynested = fields.Nested(Nested, required=True) mynullablenested = fields.Nested(Nested, required=True, allow_none=True) # fields.List is a replacement of the default List field with the ability # to receive json dumped data from requests or pytest # In json model the type of this field will be resolved as string[] mylist = fields.List(fields.Str(), required=True) # In json model the type of this field will be resolved as int[] mylist2 = fields.List(CustomInt, required=True) # In json model the type of this field will be resolved as mylist3[] # The type is key[] ... should be something more explicative like FieldName[] mylist3 = fields.List(CustomGenericField, required=True)