How to use the pydantic.constr function in pydantic

To help you get started, we’ve selected a few pydantic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github samuelcolvin / pydantic / tests / test_types.py View on Github external
def test_string_success():
    class MoreStringsModel(BaseModel):
        str_strip_enabled: constr(strip_whitespace=True)
        str_strip_disabled: constr(strip_whitespace=False)
        str_regex: constr(regex=r'^xxx\d{3}$') = ...
        str_min_length: constr(min_length=5) = ...
        str_curtailed: constr(curtail_length=5) = ...
        str_email: EmailStr = ...
        name_email: NameEmail = ...

    m = MoreStringsModel(
        str_strip_enabled='   xxx123   ',
        str_strip_disabled='   xxx123   ',
        str_regex='xxx123',
        str_min_length='12345',
        str_curtailed='123456',
        str_email='foobar@example.com  ',
        name_email='foo bar  ',
    )
    assert m.str_strip_enabled == 'xxx123'
github checktheroads / hyperglass / hyperglass / configuration / models / logging.py View on Github external
StrictInt,
    StrictStr,
    AnyHttpUrl,
    StrictBool,
    StrictFloat,
    DirectoryPath,
    constr,
    validator,
)

# Project
from hyperglass.models import HyperglassModel, HyperglassModelExtra
from hyperglass.constants import __version__

HttpAuthMode = constr(regex=r"(basic|api_key)")
HttpProvider = constr(regex=r"(msteams|slack|generic)")
LogFormat = constr(regex=r"(text|json)")


class Syslog(HyperglassModel):
    """Validation model for syslog configuration."""

    enable: StrictBool = True
    host: StrictStr
    port: StrictInt = 514


class HttpAuth(HyperglassModel):
    """HTTP hook authentication parameters."""

    mode: HttpAuthMode = "basic"
    username: Optional[StrictStr]
github checktheroads / hyperglass / hyperglass / configuration / models / web.py View on Github external
StrictStr,
    StrictBool,
    constr,
    validator,
    root_validator,
)
from pydantic.color import Color

# Project
from hyperglass.models import HyperglassModel
from hyperglass.constants import DNS_OVER_HTTPS, FUNC_COLOR_MAP
from hyperglass.configuration.models.opengraph import OpenGraph

DEFAULT_IMAGES = Path(__file__).parent.parent.parent / "images"

Percentage = constr(regex=r"^([1-9][0-9]?|100)\%$")
TitleMode = constr(regex=("logo_only|text_only|logo_title|logo_subtitle|all"))
ColorMode = constr(regex=r"light|dark")
DOHProvider = constr(regex="|".join(DNS_OVER_HTTPS.keys()))


class Analytics(HyperglassModel):
    """Validation model for Google Analytics."""

    enable: StrictBool = False
    id: Optional[StrictStr]

    @validator("id")
    def validate_id(cls, value, values):
        """Ensure ID is set if analytics is enabled.

        Arguments:
github checktheroads / hyperglass / hyperglass / configuration / models.py View on Github external
decimal: str = r"^[0-9]{1,10}$"
            extended_as: str = r"^([0-9]{0,5})\:([0-9]{1,5})$"
            large: str = r"^([0-9]{1,10})\:([0-9]{1,10})\:[0-9]{1,10}$"

        regex: Regex = Regex()

    class BgpAsPath(BaseSettings):
        """Class model for params.features.bgp_aspath"""

        enable: bool = True

        class Regex(BaseSettings):
            """Class model for params.bgp_aspath.regex"""

            mode: constr(regex="asplain|asdot") = "asplain"
            asplain: str = r"^(\^|^\_)(\d+\_|\d+\$|\d+\(\_\.\+\_\))+$"
            asdot: str = (
                r"^(\^|^\_)((\d+\.\d+)\_|(\d+\.\d+)\$|(\d+\.\d+)\(\_\.\+\_\))+$"
            )

        regex: Regex = Regex()

    class Ping(BaseSettings):
        """Class model for params.features.ping"""

        enable: bool = True

    class Traceroute(BaseSettings):
        """Class model for params.features.traceroute"""

        enable: bool = True
github samuelcolvin / nosht / py / web / views / donate.py View on Github external
async def execute(self, m: Model):
        action_id = int(self.request.match_info['action_id'])
        v = await self.conn.execute(
            'update actions set extra=extra || $3 where id=$1 and user_id=$2',
            action_id,
            self.session['user_id'],
            json.dumps({'gift_aid': m.dict()}),
        )
        if v != 'UPDATE 1':
            raise JsonErrors.HTTPNotFound(message='action not found')


class DonationOptionBread(Bread):
    class Model(BaseModel):
        category: int
        name: constr(max_length=255)
        amount: condecimal(ge=1, max_digits=6, decimal_places=2)
        live: bool = True
        short_description: str
        long_description: str
        sort_index: int = None

    browse_enabled = True
    retrieve_enabled = True
    edit_enabled = True
    add_enabled = True
    delete_enabled = True

    model = Model
    table = 'donation_options'
    table_as = 'opt'
    browse_order_by_fields = 'opt.category', 'opt.sort_index', 'opt.amount'
github rafalp / Misago / misago / graphql / mutations / postreply.py View on Github external
async def create_input_model(context: GraphQLContext) -> PostReplyInputModel:
    return create_model(
        "PostReplyInputModel",
        thread=(PositiveInt, ...),
        body=(constr(strip_whitespace=True), ...),
    )
github MolSSI / QCFractal / qcfractal / interface / models / gridoptimization.py View on Github external
"""
    GridOptimizationRecord options.
    """

    scans: List[ScanDimension] = Field(
        ..., description="The dimensions to scan along (along with their options) for the GridOptimization."
    )
    preoptimization: bool = Field(
        True,
        description="If ``True``, first runs an unrestricted optimization before starting the grid computations. "
        "This is especially useful when combined with ``relative`` ``step_types``.",
    )


_gridopt_constr = constr(strip_whitespace=True, regex="gridoptimization")
_qcfractal_constr = constr(strip_whitespace=True, regex="qcfractal")


class GridOptimizationInput(ProtoModel):
    """
    The input to create a GridOptimization Service with.

    """

    program: _qcfractal_constr = Field(
        "qcfractal",
        description="The name of the source program which initializes the Grid Optimization. This is a constant "
        "and is used for provenance information.",
    )
    procedure: _gridopt_constr = Field(
        "gridoptimization",
        description="The name of the procedure being run. This is a constant and is used for provenance information.",
github checktheroads / hyperglass / hyperglass / configuration / models / web.py View on Github external
validator,
    root_validator,
)
from pydantic.color import Color

# Project
from hyperglass.models import HyperglassModel
from hyperglass.constants import DNS_OVER_HTTPS, FUNC_COLOR_MAP
from hyperglass.configuration.models.opengraph import OpenGraph

DEFAULT_IMAGES = Path(__file__).parent.parent.parent / "images"

Percentage = constr(regex=r"^([1-9][0-9]?|100)\%$")
TitleMode = constr(regex=("logo_only|text_only|logo_title|logo_subtitle|all"))
ColorMode = constr(regex=r"light|dark")
DOHProvider = constr(regex="|".join(DNS_OVER_HTTPS.keys()))


class Analytics(HyperglassModel):
    """Validation model for Google Analytics."""

    enable: StrictBool = False
    id: Optional[StrictStr]

    @validator("id")
    def validate_id(cls, value, values):
        """Ensure ID is set if analytics is enabled.

        Arguments:
            value {str|None} -- Google Analytics ID
            values {[type]} -- Already-validated model parameters
github 3lpsy / boucanpy / boucanpy / core / zone / forms.py View on Github external
from typing import Optional
from pydantic import BaseModel, validator, constr
from boucanpy.core import is_valid_domain, is_valid_ipv4address


class ZoneCreateForm(BaseModel):
    domain: constr(min_length=4, max_length=64)
    ip: constr(min_length=7, max_length=15)
    dns_server_id: Optional[int]
    http_server_id: Optional[int]

    @validator("ip")
    def check_is_valid_ipv4address(cls, v):
        if not is_valid_ipv4address(v):
            raise ValueError(f"ip must be in a valid IPv4Address format")
        return v

    @validator("domain")
    def check_is_valid_domain(cls, v):
        if not is_valid_domain(v):
            raise ValueError(f"domain must be in a valid domain format")
        return v.lower()
github checktheroads / hyperglass / hyperglass / configuration / models / logging.py View on Github external
StrictStr,
    AnyHttpUrl,
    StrictBool,
    StrictFloat,
    DirectoryPath,
    constr,
    validator,
)

# Project
from hyperglass.models import HyperglassModel, HyperglassModelExtra
from hyperglass.constants import __version__

HttpAuthMode = constr(regex=r"(basic|api_key)")
HttpProvider = constr(regex=r"(msteams|slack|generic)")
LogFormat = constr(regex=r"(text|json)")


class Syslog(HyperglassModel):
    """Validation model for syslog configuration."""

    enable: StrictBool = True
    host: StrictStr
    port: StrictInt = 514


class HttpAuth(HyperglassModel):
    """HTTP hook authentication parameters."""

    mode: HttpAuthMode = "basic"
    username: Optional[StrictStr]
    password: SecretStr