How to use the pydantic.StrictStr 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_strict_str_subclass():
    class MyStrictStr(StrictStr):
        pass

    class Model(BaseModel):
        v: MyStrictStr

    m = Model(v=MyStrictStr('foobar'))
    assert isinstance(m.v, MyStrictStr)
    assert m.v == 'foobar'
github dr-leo / pandaSDMX / tests / test_util.py View on Github external
def test_dictlike_anno():
    @validate_dictlike('items')
    class Foo(BaseModel):
        items: DictLike[StrictStr, int] = DictLike()

    f = Foo()
    assert type(f.items) == DictLike

    # Can be set with DictLike
    f.items = DictLike(a=1, b=2)
    assert type(f.items) == DictLike

    # Can be set with dict()
    f.items = {'a': 1, 'b': 2}
    assert type(f.items) == DictLike

    # Type checking on creation
    with pytest.raises(pydantic.ValidationError):
        f = Foo(items={1: 'a'})
github checktheroads / hyperglass / hyperglass / api / models / response.py View on Github external
"examples": [
                {
                    "output": "192.0.2.1/32 is not allowed.",
                    "level": "danger",
                    "keywords": ["192.0.2.1/32"],
                }
            ]
        }


class QueryResponse(BaseModel):
    """Query response model."""

    output: Union[Dict, StrictStr]
    level: ResponseLevel = "success"
    random: StrictStr
    cached: StrictBool
    runtime: StrictInt
    keywords: List[StrictStr] = []
    timestamp: StrictStr
    format: ResponseFormat = "text/plain"

    class Config:
        """Pydantic model configuration."""

        title = "Query Response"
        description = "Looking glass response"
        fields = {
            "level": {"title": "Level", "description": "Severity"},
            "cached": {
                "title": "Cached",
                "description": "`true` if the response is from a previously cached query.",
github checktheroads / hyperglass / hyperglass / configuration / models / routers.py View on Github external
elif vrf_name == "default" and vrf.get("display_name") is None:
                vrf["display_name"] = "Global"

            # Validate the non-default VRF against the standard
            # Vrf() class.
            vrf = Vrf(**vrf)

            vrfs.append(vrf)
        return vrfs


class Routers(HyperglassModelExtra):
    """Validation model for device configurations."""

    hostnames: List[StrictStr] = []
    vrfs: List[StrictStr] = []
    display_vrfs: List[StrictStr] = []
    routers: List[Router] = []
    networks: List[StrictStr] = []

    @classmethod
    def _import(cls, input_params):
        """Import loaded YAML, initialize per-network definitions.

        Remove unsupported characters from device names, dynamically
        set attributes for the devices class. Builds lists of common
        attributes for easy access in other modules.

        Arguments:
            input_params {dict} -- Unvalidated router definitions

        Returns:
github checktheroads / hyperglass / hyperglass / configuration / models / cache.py View on Github external
"""Validation model for Redis cache config."""

# Standard Library
from typing import Union

# Third Party
from pydantic import Field, StrictInt, StrictStr, StrictBool, IPvAnyAddress

# Project
from hyperglass.models import HyperglassModel


class Cache(HyperglassModel):
    """Validation model for params.cache."""

    host: Union[IPvAnyAddress, StrictStr] = Field(
        "localhost", title="Host", description="Redis server IP address or hostname."
    )
    port: StrictInt = Field(6379, title="Port", description="Redis server TCP port.")
    database: StrictInt = Field(
        1, title="Database ID", description="Redis server database ID."
    )
    timeout: StrictInt = Field(
        120,
        title="Timeout",
        description="Time in seconds query output will be kept in the Redis cache.",
    )
    show_text: StrictBool = Field(
        True,
        title="Show Text",
        description="Show the cache text in the hyperglass UI.",
    )
github checktheroads / hyperglass / hyperglass / api / models / cert_import.py View on Github external
"""hyperglass-agent certificate import models."""
# Standard Library
from typing import Union

# Third Party
from pydantic import BaseModel, StrictStr

# Project
from hyperglass.models import StrictBytes


class EncodedRequest(BaseModel):
    """Certificate request model."""

    device: StrictStr
    encoded: Union[StrictStr, StrictBytes]
github checktheroads / hyperglass / hyperglass / configuration / models / vrfs.py View on Github external
value {int} -- Initial ge value
            values {dict} -- Other post-validation fields

        Returns:
            {int} -- Validated ge value
        """
        net_len = values["network"].prefixlen
        if net_len > value:
            value = net_len
        return value


class InfoConfigParams(HyperglassModelExtra):
    """Validation model for per-help params."""

    title: Optional[StrictStr]

    class Config:
        """Pydantic model configuration."""

        title = "Help Parameters"
        description = "Set dynamic or reusable values which may be used in the help/information content. Params my be access by using Python string formatting syntax, e.g. `{param_name}`. Any arbitrary values may be added."


class InfoConfig(HyperglassModel):
    """Validation model for help configuration."""

    enable: StrictBool = True
    file: Optional[FilePath]
    params: InfoConfigParams = InfoConfigParams()

    class Config:
github checktheroads / hyperglass / hyperglass / configuration / models / web.py View on Github external
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

        Raises:
            ValueError: Raised if analytics is enabled but no ID is set.

        Returns:
            {str|None} -- Google Analytics ID if enabled.
        """
        if values["enable"] and value is None:
github checktheroads / hyperglass / hyperglass / parsing / models / juniper.py View on Github external
class JuniperRouteTableEntry(_JuniperBase):
    """Parse Juniper rt-entry data."""

    active_tag: StrictBool
    preference: int
    age: StrictInt
    local_preference: int
    metric: int = 0
    as_path: List[StrictInt] = []
    validation_state: StrictInt = 3
    next_hop: StrictStr
    peer_rid: StrictStr
    peer_as: int
    source_as: int
    source_rid: StrictStr
    communities: List[StrictStr] = None

    @root_validator(pre=True)
    def validate_optional_flags(cls, values):
        """Flatten & rename keys prior to validation."""
        next_hop = values.pop("nh")
        selected_next_hop = ""

        for hop in next_hop:
            if "selected-next-hop" in hop:
                selected_next_hop = hop.get("to", "")
                break

        values["next-hop"] = selected_next_hop

        _path_attr = values.get("bgp-path-attributes", {})
github checktheroads / hyperglass / hyperglass / configuration / models / structured.py View on Github external
# Third Party
from pydantic import StrictStr, constr

# Project
from hyperglass.models import HyperglassModel

StructuredCommunityMode = constr(regex=r"(permit|deny)")
StructuredRPKIMode = constr(regex=r"(router|external)")


class StructuredCommunities(HyperglassModel):
    """Control structured data response for BGP communties."""

    mode: StructuredCommunityMode = "deny"
    items: List[StrictStr] = []


class StructuredRpki(HyperglassModel):
    """Control structured data response for RPKI state."""

    mode: StructuredRPKIMode = "router"


class Structured(HyperglassModel):
    """Control structured data responses."""

    communities: StructuredCommunities = StructuredCommunities()
    rpki: StructuredRpki = StructuredRpki()