class LeaseRecord(types.Type): ''' Data container used to store the various bits of a DHCP Lease. 1535916991 f4:f5:24:8a:46:3a 172.16.1.60 android-2bfa2b2619add6eb 01:f4:f5:24:8a:46:3a Format of above line: lease expiry time, mac address, ip address, hostname, client id ''' ip_address = IPAddressValidator() mac_address = MACValidator() lease_expiry_time = ArrowValidator() client_id = validators.String(default='') hostname = validators.String(default='') def serialise(self): ''' Return JSON-able version of the LeaseRecord. ''' serialised = dict( ip_address=str(self.ip_address), mac_address=str(self.mac_address), lease_expiry_time=str(self.lease_expiry_time), client_id=self.client_id, hostname=self.hostname, ) return serialised
class AppointmentRequest(types.Type): name = validators.String(max_length=100) phone = validators.String(max_length=100) addr = validators.String(max_length=200) progress = validators.String(max_length=100) comment = validators.String(max_length=200) def format_title(self): return f'{self.name} {self.phone} {self.addr}' def format_details(self): return (f'姓名: {self.name}\n' f'電話: {self.phone}\n' f'地址: {self.addr}\n' f'裝潢進度: {self.progress}\n' f'備註:{self.comment}' ) def format_add_to_calendar_link(self): text = '量 ' + self.format_title() return ( f'https://www.google.com/calendar/render?action=TEMPLATE' f'&text={urlquote(text)}' f'&location={urlquote(self.addr)}' f'&details={urlquote(self.format_details())}' )
class CuisineBlock(BaseBlock): BLOCK_TYPE = "cuisine" SUPPORTED_DIETS = ("vegetarian", "vegan", "gluten_free") STATUS_YES = "yes" STATUS_NO = "no" STATUS_ONLY = "only" STATUS_UNKNOWN = "unknown" cuisines = validators.Array(items=Cuisine) vegetarian = validators.String() vegan = validators.String() gluten_free = validators.String() @classmethod def from_es(cls, es_poi, lang): cuisine = es_poi.get("properties", {}).get("cuisine") vegetarian = get_diet_status("vegetarian", es_poi) vegan = get_diet_status("vegan", es_poi) gluten_free = get_diet_status("gluten_free", es_poi) cuisines = [] if cuisine is not None: cuisines = [Cuisine(name=b) for b in cuisine.split(";")] elif (vegetarian == cls.STATUS_UNKNOWN and vegan == cls.STATUS_UNKNOWN and gluten_free == cls.STATUS_UNKNOWN): return None return cls(cuisines=cuisines, vegetarian=vegetarian, vegan=vegan, gluten_free=gluten_free)
class PatientCreateSchema(types.Type): nom = validators.String(max_length=MAX_LENGTH["nom"]) prenom = validators.String(max_length=MAX_LENGTH["prenom"]) ddn = validators.Date() sexe = validators.String(description="sexe", max_length=MAX_LENGTH["sexe"], enum=SEXE)
class GetResponse(types.Type): """ default type for get request responses """ count = validators.Integer(description="The number of objects matching this query.", allow_null=True) next = validators.String(description="The url for the next page of data.", allow_null=True) previous = validators.String(description="The url for the previous page of data.", allow_null=True) results = validators.Array(description="The list of objects returned by the query.", allow_null=True)
def generate_fields(self, url, method, handler): fields = [] path_names = [ item.strip("{}").lstrip("+") for item in re.findall("{[^}]*}", url) ] parameters = inspect.signature(handler).parameters for name, param in parameters.items(): if name in path_names: schema = { param.empty: None, int: validators.Integer(), float: validators.Number(), str: validators.String(), }[param.annotation] field = Field(name=name, location="path", schema=schema) fields.append(field) elif param.annotation in ( param.empty, int, float, bool, str, http.QueryParam, ): if param.default is param.empty: kwargs = {} elif param.default is None: kwargs = {"default": None, "allow_null": True} else: kwargs = {"default": param.default} schema = { param.empty: None, int: validators.Integer(**kwargs), float: validators.Number(**kwargs), bool: validators.Boolean(**kwargs), str: validators.String(**kwargs), http.QueryParam: validators.String(**kwargs), }[param.annotation] field = Field(name=name, location="query", schema=schema) fields.append(field) elif issubclass(param.annotation, types.Type): if method in ("GET", "DELETE"): for ( name, validator, ) in param.annotation.validator.properties.items(): field = Field(name=name, location="query", schema=validator) fields.append(field) else: field = Field(name=name, location="body", schema=param.annotation.validator) fields.append(field) return fields
class Car(types.Type): # validators comes from apistar id = validators.Integer(allow_null=True) # assign in POST manufacturer = validators.String(enum=list(VALID_MANUFACTURERS)) model = validators.String(max_length=50) year = validators.Integer(minimum=1900, maximum=2050) vin = validators.String(max_length=50, default='')
class LogGame(types.Type): season: int = validators.Number( 1, 11, description="Overwatch season from 1 to 11.") sr: int = validators.Number( 0, 5000, description="You SR at the end of the game from 0 to 5000.") map: str = validators.String( enum=MAP_CHOICES, allow_null=True, description=f"Name of the map the game was played.", ) heroes: List[str] = validators.Array( items=validators.String(enum=HERO_CHOICES), unique_items=True, allow_null=True, description=f"List of heroes name that you played for that game.", ) comment: str = validators.String( allow_null=True, description="Free text field to leave a comment for that game.") thrower_team: bool = validators.Boolean( allow_null=True, description="If there was a thrower in your team.") thrower_enemy_team: bool = validators.Boolean( allow_null=True, description="If there was a thrower in the enemy team.") leaver_team: bool = validators.Boolean( allow_null=True, description="If there was a leaver on your team.") leaver_enemy_team: bool = validators.Boolean( allow_null=True, description="If there was a leaver on the enemy team.") group_with: List[str] = validators.Array( items=validators.String(), allow_null=True, unique_items=True, description="List of people of you grouped with for this game.", )
class SessionSettings(types.Type): cookie_name = validators.String(default='session_id') cookie_age = validators.Integer(allow_null=True) cookie_domain = validators.String(allow_null=True) cookie_path = validators.String(default='/') cookie_secure = validators.Boolean(default=False) cookie_httponly = validators.Boolean(default=False)
class Person(types.Type): id = validators.Integer(allow_null=True) department = validators.String(enum=list(VALID_DEPARTMENT)) first_name = validators.String(max_length=50) last_name = validators.String(max_length=50) email = validators.String(max_length=100) gender = validators.String(enum=['Male', 'Female'])
class PhoneBlock(BaseBlock): BLOCK_TYPE = 'phone' url = validators.String() international_format = validators.String() local_format = validators.String() @classmethod def from_es(cls, es_poi, lang): raw = es_poi.get_phone() if not raw: return None parsed_phone_number = utils.parse_phone_number(raw) if parsed_phone_number is None: return None # At this point, it should all work but just in case... e164 = utils.get_e164_phone_number(parsed_phone_number) national = utils.get_national_phone_number(parsed_phone_number) international = utils.get_international_phone_number( parsed_phone_number) if e164 is None or national is None or international is None: return None return cls(url='tel:{}'.format(e164), international_format=international, local_format=national)
class DescriptionEvent(BaseBlock): BLOCK_TYPE = "event_description" description = validators.String(allow_null=True) free_text = validators.String(allow_null=True) price = validators.String(allow_null=True) tags = validators.Array(allow_null=True) @classmethod def from_es(cls, es_poi, lang): if es_poi.PLACE_TYPE != 'event': return None description = es_poi.get('description') free_text = es_poi.get('free_text') price = es_poi.get('pricing_info') tags = es_poi.get('tags', []) if isinstance(tags, str): tags = tags.split(';') if not description: return None return cls( description=description, free_text=free_text, price=price, tags=tags )
class Ip(types.Type): # validators comes from apistar id = validators.Integer(allow_null=True) # assign in POST gender = validators.String(enum=list(VALID_GENDERS)) first_name = validators.String(max_length=50) last_name = validators.String(max_length=50) email = validators.String(max_length=50, default='') ip = validators.String(max_length=15, default="0.0.0.0")
class Case(types.Type): """ # 条件表 """ name = validators.String(max_length=255, title=u"条件名称") desc = validators.String(allow_null=True, title=u'条件描述') sql = validators.String(title=u'条件sql') no_data_pass = validators.Boolean(default=True, title=u'无数据满足')
class User(types.Type): """Simple User class.""" userid = validators.Integer(minimum=1, allow_null=True) userhash = validators.String(min_length=32, max_length=32) username = validators.String(max_length=50) fullname = validators.String(max_length=100) joined = validators.Date(allow_null=True) timezone = validators.String(enum=VALID_TIMEZONES)
class GameType(types.Type): name = validators.String() platform = validators.String() score = validators.Number() resolution_tested = validators.String(pattern="^\d+x\d+$") genre = validators.Array() players = validators.Array() language = validators.Number() awesome_city = CityType
class Car(types.Type): """Simple Car class.""" # allow_null required to assign id manually. id = validators.Integer(allow_null=True) make = validators.String(enum=VALID_MAKES) model = validators.String(min_length=1, max_length=50) year = validators.Integer(minimum=1900, maximum=2050) vin = validators.String(max_length=50, default="")
class Business(types.Type): id = validators.Integer(allow_null=True) # assign in POST company = validators.String(max_length=100) address = validators.String(max_length=200) city = validators.String(max_length=50) country = validators.String(enum=list(VALID_COUNTRIES)) # Thought would be enough to set default to '', but got error, "May not be null". # So added "allow_null = True" post_code = validators.String(max_length=20, default='', allow_null=True)
class RegisterPlayer(types.Type): battletag: str = validators.String(description="Your Battle.net Tag") password: str = validators.String( min_length=12, description="Password used to authenticate with the API.") default_platform: str = validators.String( enum=PLATFORM_CHOICES, description="Platform you're playing on.") default_region: str = validators.String( enum=REGION_CHOICES, description="Region you're playing on.")
class Product(types.Type): """Represent the item that was added to a basket.""" name = validators.String(max_length=100) type = validators.String(enum=["mobile", "sim", "broadband"]) basket_id = validators.String(max_length=48, allow_null=True) @classmethod def from_model(cls, obj): return cls(name=obj.name, type=obj.type, basket_id=str(obj.basket.id))
class Anime(types.Type): id = validators.Integer(allow_null=True) title = validators.String(max_length=2500) year = validators.Integer(minimum=1900, maximum=2050) episodes = validators.Integer(maximum=9999) status = validators.String(enum=list(ANIME_VALID_STATUS)) type = validators.String(allow_null=True) animeSeason = validators.Object(allow_null=True) picture = validators.String(allow_null=True) sources = validators.Array(allow_null=True)
class CallBack(types.Type): """ 回调表 """ name = validators.String(max_length=255, title=u'接口名称', description=u'接口名称') url = validators.String(title=u'回调url', description=u'回调url') create_time = validators.DateTime(default=cur_date_time(), title=u'创建时间', description=u'创建时间') def __str__(self): return self.name
class Movie(types.Type): id = validators.Integer(allow_null=True) # assign in POST genre = validators.Array(items=validators.String(enum=list(VALID_GENRES))) director_name = validators.String(max_length=100) year = validators.Integer(minimum=1900, maximum=2050) language = validators.String(max_length=100, enum=list(VALID_LANGUAGES), allow_null=True) title = validators.String(max_length=200) rating = validators.Number(minimum=0, maximum=10)
class CsrfSettings(types.Type): CSRF_COOKIE_NAME = validators.String(default='csrftoken') CSRF_COOKIE_AGE = validators.Integer(default=60 * 60 * 24 * 7 * 52) CSRF_COOKIE_DOMAIN = validators.String(allow_null=True) CSRF_COOKIE_PATH = validators.String(default='/') CSRF_COOKIE_SECURE = validators.Boolean(default=False) CSRF_COOKIE_HTTPONLY = validators.Boolean(default=False) CSRF_HEADER_NAME = validators.String(default='HTTP_X_CSRFTOKEN') CSRF_TOKEN_FIELD_NAME = validators.String(default='csrf_token') CSRF_TRUSTED_ORIGINS = validators.Array(default=[])
class Block(PickleType): height = validators.Integer() timestamp = validators.DateTime() txns = validators.Array(items=Transaction, allow_null=True, default=[]) mined_hash = validators.String(max_length=100) previous_hash = validators.String(max_length=100, allow_null=True) nonce = validators.Integer() @property def previous_block(self): return get_block(self.previous_hash)
def generate_fields(self, url, method, handler): fields = [] path_names = [ item.strip('{}').lstrip('+') for item in re.findall('{[^}]*}', url) ] parameters = inspect.signature(handler).parameters for name, param in parameters.items(): if name in path_names: schema = { param.empty: None, int: validators.Integer(), float: validators.Number(), str: validators.String() }[param.annotation] field = Field(name=name, location='path', schema=schema) fields.append(field) elif param.annotation in (param.empty, int, float, bool, str, http.QueryParam): if param.default is param.empty: kwargs = {} elif param.default is None: kwargs = {'default': None, 'allow_null': True} else: kwargs = {'default': param.default} schema = { param.empty: None, int: validators.Integer(**kwargs), float: validators.Number(**kwargs), bool: validators.Boolean(**kwargs), str: validators.String(**kwargs), http.QueryParam: validators.String(**kwargs), }[param.annotation] field = Field(name=name, location='query', schema=schema) fields.append(field) elif issubclass(param.annotation, types.Type): if method in ('GET', 'DELETE'): for name, validator in param.annotation.validator.properties.items( ): field = Field(name=name, location='query', schema=validator) fields.append(field) else: field = Field(name=name, location='body', schema=param.annotation.validator) fields.append(field) return fields
class AuthenticatedUserData(types.Type): id = validators.Integer() email = validators.String(description="Email address", pattern="[^@]+@[^@]+\.[^@]+", allow_null=True) phone = validators.String(description="Phone number", pattern="\D*", allow_null=True) first_name = validators.String() last_name = validators.String() language = validators.Integer() groups = validators.Array() location = validators.Integer() picture = validators.String(allow_null=True)
class Product(types.Type): name = validators.String(max_length=10) rating = validators.Integer(allow_null=True, default=None, minimum=0, maximum=100) created = validators.DateTime()
class URLExtractionJSONParams(BaseExtractionJSONParams): """Validator for URL content extraction parameters.""" url = validators.String( max_length=400, allow_null=True, description='URL of document to fetch and analyze', )
def resolve(self, parameter: inspect.Parameter, path_params: ValidatedPathParams, query_params: ValidatedQueryParams): params = path_params if (parameter.name in path_params) else query_params has_default = parameter.default is not parameter.empty allow_null = parameter.default is None param_validator = { parameter.empty: validators.Any(), str: validators.String(allow_null=allow_null), int: validators.Integer(allow_null=allow_null), float: validators.Number(allow_null=allow_null), bool: validators.Boolean(allow_null=allow_null) }[parameter.annotation] validator = validators.Object( properties=[(parameter.name, param_validator)], required=[] if has_default else [parameter.name]) try: params = validator.validate(params, allow_coerce=True) except validators.ValidationError as exc: raise exceptions.NotFound(exc.detail) return params.get(parameter.name, parameter.default)