class RelativeCoordinate(SketchBase): """ A location in relative units rather than real world or Page coordinates. Relative coordinates measure right and up from the origin. So the first number is for right and second is for up. """ right: conint(ge=0) up: conint(ge=0)
class NorthPoleCredential(BaseModel): byr: conint(ge=1920, le=2002) iyr: conint(ge=2010, le=2020) eyr: conint(ge=2020, le=2030) hgt: constr(regex=r'[0-9]+(cm|in)') hcl: constr(regex=r'#([0-9]|[a-f]){6}') ecl: Literal['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'] pid: constr(regex=r'^[0-9]{9}$') cid: Optional[str] @validator('hgt') def height_validation(cls, v: str): if v.endswith('cm'): height = int(v[:-2]) lower_bound = 150 upper_bound = 193 if not lower_bound <= height <= upper_bound: raise ValueError( f'Height of {height}cm has to be >= {lower_bound}cm and <= {upper_bound}cm.' ) if v.endswith('in'): height = int(v[:-2]) lower_bound = 59 upper_bound = 76 if not lower_bound <= height <= upper_bound: raise ValueError( f'Height of {height}cm has to be >= {lower_bound}in and <= {upper_bound}in.' ) return v
class RoutingIsisLspGenInterval(VendorIndependentBaseModel): level: Optional[ISIS_LEVEL] interval: conint(ge=1, le=120) """Interval in seconds""" init_wait: Optional[conint(ge=1, le=120000)] """Initial wait in milliseconds""" wait: Optional[conint(ge=1, le=120000)] """Wait between first and second lsp generation in milliseconds""" @root_validator(allow_reuse=True) def validate_order(cls, values): level = values.get('level') interval = values.get('interval') init_wait = values.get('init_wait') wait = values.get('wait') if init_wait is not None: if not all([interval]): msg = "Field 'init_wait' can only be specified together with 'interval'." raise AssertionError(msg) if wait is not None: if not all([interval, init_wait]): msg = "Field 'wait' can only be specified together with 'interval' and 'init_wait'." raise AssertionError(msg) return values
class Profile(BaseModel): repositories: Repositories watchers: conint(ge=0) languages: Dict[str, conint(ge=0)] = Field(..., example={ "C": 3, "Python": 4 })
class PageCoordinate(SketchBase): """ A location in page units rather than real world coordinates. The origin for page coordinates is the upper left corner of the page, so `0,0` is the top left corner. There are no units for `pageCoordinates`, they are simple integers that increase from left-to-right and from top-to-bottom. """ x: conint(ge=0) y: conint(ge=0)
class IosLineConfig(BaseNetModel): line_type: Literal['aux', 'console', 'vty'] line_range: conlist(item_type=conint(ge=0), min_items=1, max_items=2) aaa_config: Optional[IosLineAaaConfig] """AAA Configuration Object""" exec_timeout: Optional[conint(ge=0)] """EXEC Timeout in seconds""" transport: Optional[IosLineTransport] access_classes: Optional[List[IosLineAccessClass]]
def get_messages(device_id: int, page: conint(ge=1) = 1, records_per_page: conint(ge=0) = 50, db: Session = Depends(get_db)): if not device_repository.get_device(db, device_id)[0]: raise HTTPException(status_code=HTTP_404_NOT_FOUND) messages, record_count = message_repository.get_messages( db, device_id, page, records_per_page) page_count = math.ceil(record_count / records_per_page) return MessageResponse(page=page, page_count=page_count, record_count=record_count, items=[Message.from_orm(msg) for msg in messages])
def unitint( unit: str, **kwargs, ) -> Type[int]: namespace = dict(unit=unit) conint_t = conint(**kwargs) return type("UnitInt", (conint_t, ), namespace)
class AnimalQuery(BaseModel): type: Optional[AnimalType] = None age: Optional[AnimalAge] = None size: Optional[AnimalSize] = None gender: Optional[AnimalGender] = None breed: Optional[str] = None name: Optional[str] = None zip_code: Optional[str] = None distance: Optional[int] = None status: AnimalStatus = AnimalStatus.adoptable limit: conint(gt=0, le=100) = 100 sort: SortType = SortType.random class Config(BaseModel.Config): use_enum_values = True def dict(self, *args, **kwargs): d = super().dict(exclude_none=True, by_alias=True) if "zip_code" in d: d["location"] = d.pop("zip_code") return d @root_validator def check_dependencies(cls, values: dict) -> dict: """ Check through the values for field mismatches that result in a 400 (bad request) from the api. """ if values.get("distance") and (values.get("zip_code") is None): raise Exception( "You cannot specify 'distance' without first providing a value for 'zip_code'" ) return values
class LimitOffsetPage(BasePage[T], Generic[T]): limit: conint(gt=0) # type: ignore offset: conint(ge=0) # type: ignore __params_type__ = LimitOffsetParams @classmethod def create( cls, items: Sequence[T], total: int, params: AbstractParams, ) -> LimitOffsetPage[T]: return cls( total=total, items=items, **asdict(params.to_raw_params()), )
class RoutingIsisProcess(RoutingProtocolIgpBase): process_id: GENERIC_OBJECT_NAME is_type: Literal['level-1', 'level-1-2', 'level-2-only'] metric_style: Optional[Literal['narrow', 'transition', 'wide']] fast_flood: Optional[conint(ge=1, le=15)] network: RoutingIsisNetwork authentication: Optional[AuthenticationIsis] lsp: Optional[RoutingIsisLsp] extra_config: Optional[List[str]]
class VADAnnotation(BaseModel): frames_count: conint(gt=0) is_anomalous_regions_available: bool is_anomaly_track_id_available: bool video_length_sec: Optional[PositiveFloat] = None frame_width: conint(gt=0) frame_height: conint(gt=0) frame_rate: Optional[PositiveFloat] = None frames: List[VADFrame] = Field(..., description=("len(frames) == frames_count")) @validator('frames') def frames_len(cls, v, values, **kwargs): if len(v) != values["frames_count"]: raise ValidationError( "Length of 'frames' does not match 'frames_count'") return v class Config: extra = "allow"
class CheckpointsConfig(BaseConfig): validation_steps: Union[confloat(gt=0.0, le=1.0), PositiveInt] = 1.0 """How often within one training epoch to check the validation set. If float, % of training epoch. If int, check every n batches.""" save_top_k: int = 1 """Save and keep only ``k`` best models according to main metric; -1 will keep all; 0 will never save a model.""" early_stop_patience: conint(ge=0) = 0 """Stop training if evaluation metrics do not improve after X validations;
class Repository(BaseModel): forked: bool language: Union[str, None] topics: List[str] = [] watchers: conint(ge=0) @validator("language") def santize_language(cls, language: Union[str, None]) -> str: """Replace null/missing languages with "other" and make languages lowercase.""" if language is None: return "other" return language.lower()
class VADFrame(BaseModel): frame_id: conint(gt=0) frame_filename: Optional[str] = None video_time_sec: Optional[PositiveFloat] = None anomaly_track_id: Optional[int] = Field( ..., description=("Set to None if anomalous track not available. " "Set to -1 for Negative.")) frame_level_score: Optional[confloat(ge=0., le=1.0)] = Field( ..., description=("Set to None if anomalous region available. " "If None, anomalous_regions must not None. " "For GT, 1 for Positive and 0 for Negative.")) anomalous_regions: List[AnomalousRegion] = Field( ..., description=("Set to None if anomalous region not available. " "If empty, the frame is considered as Negative."))
class RawTaskEvent(CorvaBaseEvent, RawBaseEvent): task_id: str version: conint(ge=2, le=2) # only utils API v2 supported @staticmethod def from_raw_event(event: dict) -> List[RawTaskEvent]: return [pydantic.parse_obj_as(RawTaskEvent, event)] def get_task_event(self, api: Api) -> TaskEvent: response = api.get(path=f'v2/tasks/{self.task_id}') response.raise_for_status() return TaskEvent(**response.json()) def update_task_data(self, api: Api, status: TaskStatus, data: dict) -> requests.Response: """Updates the task.""" return api.put(path=f'v2/tasks/{self.task_id}/{status.value}', data=data)
class Note(SketchBase): """ A note is a piece of text anchored to a specific page. """ keycode: constr(min_length=1) = ... text: constr(min_length=1, max_length=255) = ... page_number: conint(ge=1) = 1 note_position: PageCoordinate = ... class Config: schema_extra = { "examples": [ { "keyCode": "1/0", "text": "Main Condo Strip", "notePosition": "49,44", "pageNumber": 1, }, ] }
base_schema = { 'title': 'Model', 'type': 'object', 'properties': {'a': {'title': 'A', 'type': 'string'}}, 'required': ['a'], } base_schema['properties']['a']['format'] = expected_schema assert Model.schema() == base_schema @pytest.mark.parametrize( 'field_type,expected_schema', [ (ConstrainedInt, {}), (conint(gt=5, lt=10), {'exclusiveMinimum': 5, 'exclusiveMaximum': 10}), (conint(ge=5, le=10), {'minimum': 5, 'maximum': 10}), (conint(multiple_of=5), {'multipleOf': 5}), (PositiveInt, {'exclusiveMinimum': 0}), (NegativeInt, {'exclusiveMaximum': 0}), ], ) def test_special_int_types(field_type, expected_schema): class Model(BaseModel): a: field_type base_schema = { 'title': 'Model', 'type': 'object', 'properties': {'a': {'title': 'A', 'type': 'integer'}}, 'required': ['a'],
class Repositories(BaseModel): forked: conint(ge=0) owned: conint(ge=0) topics: Set[str] = Field(..., example={"backend", "frontend"})
'title': 'A', 'type': inner_type, 'writeOnly': True } }, 'required': ['a'], } assert Model.schema() == base_schema @pytest.mark.parametrize( 'field_type,expected_schema', [ (ConstrainedInt, {}), (conint(gt=5, lt=10), { 'exclusiveMinimum': 5, 'exclusiveMaximum': 10 }), (conint(ge=5, le=10), { 'minimum': 5, 'maximum': 10 }), (conint(multiple_of=5), { 'multipleOf': 5 }), (PositiveInt, { 'exclusiveMinimum': 0 }), (NegativeInt, { 'exclusiveMaximum': 0
class DatesAndPriceCheckInputValidator(CheckinCheckoutValidator): listing_ids: conlist(conint(gt=0), min_items=1)
import hashlib import hmac from enum import auto from typing import NewType from typing import Optional import arrow from autoname import AutoNameUppercase from pydantic import BaseModel from pydantic.types import conint from songmam.security import SignedRequest from songmam.security import verify_signed_request # type Second = conint(ge=0) class ThreadType(AutoNameUppercase): user_to_page = auto() user_to_user = auto() group = auto() class SignedRequestContent(BaseModel): """ This class property was created based on a real object. See test for ref. # WTF, This is not the same structure as the actual object https://developers.facebook.com/docs/reference/login/signed-request """
'title': 'A', 'type': 'string' } }, 'required': ['a'], } base_schema['properties']['a']['format'] = expected_schema assert Model.schema() == base_schema @pytest.mark.parametrize( 'field_type,expected_schema', [ (ConstrainedInt, {}), (conint(gt=5, lt=10), { 'exclusiveMinimum': 5, 'exclusiveMaximum': 10 }), (conint(ge=5, le=10), { 'minimum': 5, 'maximum': 10 }), (PositiveInt, { 'exclusiveMinimum': 0 }), (NegativeInt, { 'exclusiveMaximum': 0 }), ], )
class IosLineLogging(BaseNetModel): synchronous: Optional[bool] level: Optional[Union[Literal['all'], conint(ge=0, le=7)]] limit: Optional[int]
class NetworkClockSource(VendorIndependentBaseModel): priority: conint(ge=1) interface: Optional[InterfaceName] external: Optional[str] src_type: Literal['interface']
import validators from pydantic.fields import Field from pydantic.networks import EmailStr from pydantic import BaseModel, validator from pydantic.types import conint, constr, SecretStr from sqlalchemy import func from sqlalchemy.orm import relationship from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.ext.declarative import declared_attr from sqlalchemy import Boolean, Column, DateTime, Integer, String, event, ForeignKey # pydantic type that limits the range of primary keys PrimaryKey = conint(gt=0, lt=2147483647) NameStr = constr(regex=r"^(?!\s*$).+", strip_whitespace=True, min_length=3) OrganizationSlug = constr(regex=r"^[\w]+(?:_[\w]+)*$", min_length=3) # SQLAlchemy models... class ProjectMixin(object): """Project mixin""" @declared_attr def project_id(cls): # noqa return Column(Integer, ForeignKey("project.id", ondelete="CASCADE")) @declared_attr def project(cls): # noqa return relationship("Project")
class BasePage(AbstractPage[T], Generic[T], ABC): items: Sequence[T] total: conint(ge=0) # type: ignore
# # NOTE: This files copies some of the types from models_library.basic_types # This is a minor evil to avoid the maintenance burden that creates # an extra dependency to a larger models_library (intra-repo library) from enum import Enum from pydantic.types import conint, constr # port number range PortInt = conint(gt=0, lt=65535) # e.g. 'v5' VersionTag = constr(regex=r"^v\d$") class LogLevel(str, Enum): DEBUG = "DEBUG" INFO = "INFO" WARNING = "WARNING" ERROR = "ERROR" class BootMode(str, Enum): """ Values taken by SC_BOOT_MODE environment variable set in Dockerfile and used during docker/boot.sh """ DEFAULT = "default" LOCAL = "local-development"
from enum import Enum from pydantic import BaseModel, validator from pydantic.fields import Field from pydantic.types import conint from typing import Optional from datetime import datetime class Normalization(str, Enum): """ Geospatial normalization, where `total` means the actual value for a given area and `density` means values are normalized by area. """ total = "total" density = "density" Hour = conint(ge=0, le=23) class DayOfWeek(str, Enum): """ Day of the week. """ sunday = "sunday" monday = "monday" tuesday = "tuesday" wednesday = "wednesday" thursday = "thursday" friday = "friday" saturday = "saturday" @classmethod def get_number(cls, dow: DayOfWeek) -> int:
statics=dict( crag_id=UUID, sector_id=UUID, ), voted=[ VoteDefinition( model_name="ClimbNameVote", collection_name="name_votes", item_name="name_vote", type=constr(min_length=1, strip_whitespace=True), ), VoteDefinition( model_name="RatingVote", collection_name="rating_votes", item_name="rating_vote", type=conint(ge=0, le=5), aggregation=VoteAggregation( fn=average, name="average_rating", type=float, ), ), VoteDefinition( model_name="GradeVote", collection_name="grade_votes", item_name="grade_vote", type=UUID, aggregation=VoteAggregation( fn=most_voted, name="most_voted_grade", type=UUID,