示例#1
0
class ModuleContent(object):
    dependencies = attr(default=Factory(set))
    post = attr(default=Factory(list))

    def __iter__(self):
        yield self.dependencies
        yield self.post
class ConstraintModifiers(object):
    allow_newer = attr(**_coerced_set)
    allow_any = attr(**_coerced_set)
    allow_older = attr(**_coerced_set)

    def asdict(self):
        return {k: sorted(v) for k, v in six.iteritems(asdict(self))}

    def update(self, other_modifiers):
        """ Update modifiers with values from ConstraintModifiers instance. """
        self.allow_any.update(other_modifiers.allow_any)
        self.allow_newer.update(other_modifiers.allow_newer)
        self.allow_older.update(other_modifiers.allow_older)

    def remove(self, packages):
        """ Remove all modifiers related to `packages`.

        Parameters
        ----------
        packages : an iterable of strings
            The package names that should be completely removed.
        """
        disallowed = (type(b""), type(u""))
        if isinstance(packages, disallowed):
            raise TypeError("`packages` should be a collection, not a string.")
        packages = set(packages)
        self.allow_any.difference_update(packages)
        self.allow_newer.difference_update(packages)
        self.allow_older.difference_update(packages)

    @property
    def targets(self):
        return set.union(self.allow_newer, self.allow_any, self.allow_older)
示例#3
0
class RenderedRst(object):
    title = attr.attr()
    body_soup = attr.attr()
    metadata = attr.attr()

    @property
    def body(self):
        return ''.join(str(child) for child in self.body_soup.children).strip()
示例#4
0
class SearchFacetResult(object):
    """ An individual facet result has both metadata and details,
    as each facet can define ranges into which results are categorized."""
    name = attr.attr(type=str)
    field = attr.attr(type=str)
    total = attr.attr(type=UnsignedInt64)
    missing = attr.attr(type=UnsignedInt64)
    other = attr.attr(type=UnsignedInt64)
示例#5
0
class Proxy(object):
    host = attr(type=str, default=None)
    port = attr(type=int, default=None)

    def __str__(self):
        return f'{self.host}:{self.port}'

    def string(self):
        return self.__str__()
示例#6
0
class PullupRecord(object):
    created_at = attr.attr(default=attr.Factory(
        lambda: datetime.datetime.now(pytz.utc).isoformat()))
    pullups = attr.attr(default=0)
    time_in_set = attr.attr(default=0.0)

    @property
    def created_at_dt(self):
        return dateutil.parser.parse(self.created_at)
示例#7
0
class Item(MudBase):
    short_desc = field(default='', type=str)
    item_type = field(default=-1, type=int)
    extra_flags = field(default=0, type=int)
    wear_flags = field(default=0, type=WEAR_LOCATIONS)
    cost = field(default=0, type=int)
    level = field(default=0, type=int)
    weight = field(default=0, type=int)
    affected = attr(default=Factory(list))
    value = attr(default=Factory(list), type=List)
示例#8
0
class Account:
    '''
    用户账户模型
    '''
    __tablename__ = "basic_account"

    id: int = attr.attr(metadata={"sql": "id;primary_key"})
    balance: float = attr.attr(default=0)
    score: float = attr.attr(default=0)
    created_at: datetime = attr.attr(factory=datetime.now)
    updated_at: datetime = attr.attr(factory=datetime.now)
class Proxy(object):
    ''' 代理的模式 '''
    host = attr(type=str, default=None)
    port = attr(type=int, default=None)

    def __str__(self):
        ''' toString 函数 '''
        return f'{self.host}:{self.port}'

    def string(self):
        ''' 转成字符串,打印代理时使用 '''
        return self.__str__()
示例#10
0
class ImpersonationCredentials(object):
    """
    An object representing the required
    impersonator-token/impersonated-username credentials.

    :ivar impersonator_token: The auth token of the user requesting an
        impersonation token.
    :ivar impersonated_username: The username of the user to be impersonated.
    :ivar impersonated_token: The impersonation token that can be used to
        authenticate as impersonated user.
    :ivar int expires_in: The number of seconds the impersonation token will
        last.
    """
    impersonator_token = attr(
        validator=validators.optional(validators.instance_of(text_type)))
    impersonated_username = attr(validator=validators.instance_of(text_type))
    expires_in = attr(validator=validators.instance_of(int))
    impersonated_token = attr(
        default=Factory(lambda: 'impersonated_token_' + text_type(uuid4())),
        validator=validators.instance_of(text_type))
    type_key = 'RAX-AUTH:impersonation'

    def get_session(self, session_store):
        """
        :see: :class:`ICredential.get_session`
        """
        return session_store.session_for_impersonation(
            self.impersonated_username, self.expires_in,
            self.impersonator_token, self.impersonated_token)

    @classmethod
    def from_json(cls, json_blob, auth_token):
        """
        Given an impersonation JSON blob, which should look like::

            {
                "RAX-AUTH:impersonation": {
                    "expire-in-seconds": 1000,
                    "user": {
                        "username": "******"
                    }
                }
            }

        Along with a header "X-Auth-Token" with the impersonator's token,

        :return: a class:`ImpersonationCredentials` object
        """
        expires_in = json_blob[cls.type_key].get('expire-in-seconds', 86400)
        username = json_blob[cls.type_key]['user']['username']
        return cls(impersonator_token=auth_token,
                   impersonated_username=username,
                   expires_in=int(expires_in))
示例#11
0
class Special(object):
    command = attr(default=None)
    arg1 = attr(default=None)
    arg2 = attr(default=None)
    comment = attr(default=None, type=str)

    @classmethod
    def read(cls, reader, letter, **kwargs):
        command = letter
        arg1 = reader.read_number()
        arg2 = reader.read_word()
        comment = reader.read_to_eol()
        return cls(command=command, arg1=arg1, arg2=arg2, comment=comment)
示例#12
0
class UserRole:
    '''
    用户角色关联模型
    多对多关系
    无需对外输出
    '''
    __tablename__ = "basic_user_role"

    id: int = attr.attr(metadata={"sql": "id;primary_key"})
    user_id: int
    role_id: int
    created_at: datetime = attr.attr(factory=datetime.now)
    updated_at: datetime = attr.attr(factory=datetime.now)
示例#13
0
class _Job(object):
    requirement = attr(validator=optional(instance_of(Requirement)))
    kind = attr(validator=instance_of(JobType))

    def __attrs_post_init__(self):
        if self.requirement is None and self.kind != JobType.upgrade:
            raise ValueError(
                u"_Job requirement cannot be none if kind != {}",format(
                    JobType.upgrade
                )
            )

    def __str__(self):
        return u"{} {}".format(self.kind.name, self.requirement)
示例#14
0
class Proxy(object):
    """
    proxy schema
    """
    host = attr(type=str, default=None)
    port = attr(type=int, default=None)
    location = attr(type=str, default=None)
    isp = attr(type=str, default=None)
    country = attr(type=str, default=None)
    anonymous = attr(type=bool, default=None)
    protocol = attr(type=str, default=None)
    alive_time = attr(type=int, default=None)

    def __str__(self):
        """
        to string, for print
        :return:
        """
        return f'{self.host}:{self.port}'

    def string(self):
        """
        to string
        :return: <host>:<port>
        """
        return self.__str__()
示例#15
0
class PatternClone:

    source = attr()
    flags = attr(default=PatternFlags.clone)
    x = attr(default=0)
    y = attr(default=0)

    def iff_chunks(self):
        yield (b"PPAR", pack("<I", self.source))
        yield (b"PFFF", pack("<I", self.flags))
        yield (b"PXXX", pack("<i", self.x))
        yield (b"PYYY", pack("<i", self.y))

    def source_pattern(self, project):
        return project.patterns[self.source]
示例#16
0
class APIKeyCredentials(object):
    """
    An object representing the required username/api-key credentials plus an
    optional tenant identifier.

    :ivar username: The username of the user to authenticate.
    :ivar api_key: The API key used to authenticate the user.
    :ivar tenant_id: Optional - the tenant ID of the user.
    """
    username = attr(validator=validators.instance_of(text_type))
    api_key = attr(validator=validators.instance_of(text_type))
    tenant_id = attr(default=None)
    type_key = "RAX-KSKEY:apiKeyCredentials"

    def get_session(self, session_store):
        """
        :see: :class:`ICredential.get_session`
        """
        return session_store.session_for_api_key(self.username, self.api_key,
                                                 self.tenant_id)

    @classmethod
    def from_json(cls, json_blob):
        """
        Given an authentication JSON blob, which should look like::

            {
                "auth": {
                    "RAX-KSKEY:apiKeyCredentials": {
                        "username": "******",
                        "apiKey": "key"
                    },
                    "tenantId": "111111"
                }
            }

        ``"tenantId"`` is interchanable with ``"tenantName"``, and is
        optional.

        :return: a class:`APIKeyCredentials` object
        """
        tenant_id = json_blob['auth'].get('tenantName')
        if tenant_id is None:
            tenant_id = json_blob['auth'].get('tenantId')

        username = json_blob['auth'][cls.type_key]['username']
        api_key = json_blob['auth'][cls.type_key]['apiKey']
        return cls(username=username, api_key=api_key, tenant_id=tenant_id)
示例#17
0
class PasswordCredentials(object):
    """
    An object representing the required username/password credentials plus
    an optional tenant identifier.

    :ivar username: The username of the user to authenticate.
    :ivar password: The password used to authenticate the user.
    :ivar tenant_id: Optional - the tenant ID of the user.
    """
    username = attr(validator=validators.instance_of(text_type))
    password = attr(validator=validators.instance_of(text_type))
    tenant_id = attr(default=None)
    type_key = "passwordCredentials"

    def get_session(self, session_store):
        """
        :see: :class:`ICredential.get_session`
        """
        return session_store.session_for_username_password(
            self.username, self.password, self.tenant_id)

    @classmethod
    def from_json(cls, json_blob):
        """
        Given an authentication JSON blob, which should look like::

            {
                "auth": {
                    "passwordCredentials": {
                        "username": "******",
                        "password": "******"
                    },
                    "tenantId": "111111"
                }
            }

        ``"tenantId"`` is interchanable with ``"tenantName"``, and is
        optional.

        :return: a class:`PasswordCredentials` object
        """
        tenant_id = json_blob['auth'].get('tenantName')
        if tenant_id is None:
            tenant_id = json_blob['auth'].get('tenantId')

        username = json_blob['auth'][cls.type_key]['username']
        password = json_blob['auth'][cls.type_key]['password']
        return cls(username=username, password=password, tenant_id=tenant_id)
示例#18
0
class Nothing(object):
    name = attr()

    def __bool__(self):
        return False

    __nonzero__ = __bool__
示例#19
0
文件: utils.py 项目: zphang/num2num
def argparse_attr(default=attr.NOTHING, validator=None,
                  repr=True, cmp=True, hash=True, init=True,
                  convert=None, opt_string=None,
                  **argparse_kwargs):
    if opt_string is None:
        opt_string_ls = []
    elif isinstance(opt_string, str):
        opt_string_ls = [opt_string]
    else:
        opt_string_ls = opt_string

    if argparse_kwargs.get("type", None) is bool:
        argparse_kwargs["choices"] = {True, False}
        argparse_kwargs["type"] = _is_true

    return attr.attr(
        default=default,
        validator=validator,
        repr=repr,
        cmp=cmp,
        hash=hash,
        init=init,
        convert=convert,
        metadata={
            "opt_string_ls": opt_string_ls,
            "argparse_kwargs": argparse_kwargs,
        }
    )
示例#20
0
class MercArea(object):
    metadata = attr(default="")
    helps = attr(default=Factory(list))
    rooms = attr(default=Factory(OrderedDict))
    mobs = attr(default=Factory(OrderedDict))
    objects = attr(default=Factory(OrderedDict))
    resets = attr(default=Factory(list))
    specials = attr(default=Factory(list))
    shops = attr(default=Factory(list))
示例#21
0
class Exit(object):
    keyword = attr(default='', type=Word)
    description = attr(default="", type=str)
    door = attr(default=None, type=EXIT_DIRECTIONS)
    exit_info = attr(default=0, type=EXIT_FLAGS, converter=EXIT_FLAGS)
    rs_flags = attr(default=0, type=int)
    key = attr(default=0, type=int)
    destination = attr(default=None, type=int)

    @classmethod
    def read(cls, reader, **kwargs):
        logger.debug("Reading exit")
        locks = 0
        door = reader.read_number()
        description = reader.read_string()
        keyword = reader.read_string()
        exit_info = 0
        locks = reader.read_number()
        key = reader.read_number()
        destination = reader.read_number()
        if locks == 1:
            exit_info = EXIT_FLAGS.ISDOOR
        elif locks == 2:
            exit_info = EXIT_FLAGS.ISDOOR | EXIT_FLAGS.PICKPROOF
        elif locks == 3:
            exit_info = EXIT_FLAGS.ISDOOR | EXIT_FLAGS.NOPASS
        elif locks == 4:
            exit_info = EXIT_FLAGS.ISDOOR | EXIT_FLAGS.NOPASS | EXIT_FLAGS.PICKPROOF
        return cls(door=door,
                   description=description,
                   keyword=keyword,
                   exit_info=exit_info,
                   key=key,
                   destination=destination)
示例#22
0
class MercReset(object):
    command = attr(default=None)
    arg1 = attr(default=None)
    arg2 = attr(default=None)
    arg3 = attr(default=None)
    arg4 = attr(default=None)
    arg5 = attr(default=None)
    comment = attr(default=None)

    @classmethod
    def read(cls, reader, letter):
        command = letter
        reader.read_number()  #if_flag
        arg1 = reader.read_number()
        arg2 = reader.read_number()
        if letter == 'G' or letter == 'R':
            arg3 = 0
        else:
            arg3 = reader.read_number()
        if letter == 'P' or letter == 'M':
            arg4 = 0
        else:
            arg4 = reader.read_number()
        arg5 = reader.read_number()
        reader.index -= 1
        comment = reader.read_to_eol()
        return cls(command=command,
                   arg1=arg1,
                   arg2=arg2,
                   arg3=arg3,
                   arg4=arg4,
                   arg5=arg5,
                   comment=comment)
示例#23
0
class RomAffectData(object):
    where = attr(default=None)
    type = attr(default=None)
    level = attr(default=None)
    duration = attr(default=None)
    location = attr(default=None)
    modifier = attr(default=None)
    bitvector = attr(default=0)
示例#24
0
class Dice(object):
    number = attr(default=0, type=int)
    sides = attr(default=0, type=int)
    bonus = attr(default=0, type=int)

    @classmethod
    def read(cls, reader, **kwargs):
        number = reader.read_number()
        reader.read_letter()  #D
        sides = reader.read_number()
        bonus = reader.read_number()
        return cls(number=number, sides=sides, bonus=bonus, **kwargs)

    def roll(self):
        score = 0
        for roll in range(self.number):
            score += random.randrange(1, self.sides)
        score += self.bonus
        return score
示例#25
0
class A:
    a: int = attr.ib(default=1)
    b: int = attr.ib(default=attr.Factory(int))
    c: int = attr.ib()
    d: int = attr.ib(init=False)
    e: int = attr.attr(init=False)
    f: int = attr.attrib(init=False)
    g: int = attr.ib(default=attr.NOTHING)
    h: int = attr.ib(factory=int)
    i: int = attr.ib(factory=None)
示例#26
0
class _CompositeValidator(object):
    validators = attr()

    def __call__(self, inst, attr, value):
        for validator in self.validators:
            validator(inst, attr, value)

    def __repr__(self):
        return ("<composite validator for validators {!r}>".format(
            self.validators))
示例#27
0
class _ListOfValidator(object):
    etype = attr.attr()

    def __call__(self, inst, attr, value):
        if False in set(map(lambda el: isinstance(el, self.etype), value)):
            raise ValueError("{attr} should be list of {etype}".format(
                attr=attr.name, etype=self.etype))

    def __repr__(self):
        return ("<is value is the list of {etype}>".format(etype=self.etype))
示例#28
0
class TokenCredentials(object):
    """
    An object representing the required token/tenant credentials.

    :ivar token: The auth token to be authenticated
    :ivar tenant_id: The tenant ID the token belongs to.
    """
    token = attr(validator=validators.instance_of(text_type))
    tenant_id = attr(validator=validators.instance_of(text_type))
    type_key = "token"

    def get_session(self, session_store):
        """
        :see: :class:`ICredential.get_session`
        """
        return session_store.session_for_token(self.token, self.tenant_id)

    @classmethod
    def from_json(cls, json_blob):
        """
        Given an authentication JSON blob, which should look like::

            {
                "auth": {
                    "token": {
                        "id": "my_token"
                    },
                    "tenantId": "111111"
                }
            }

        ``"tenantId"`` is interchanable with ``"tenantName"``, and is
        optional.

        :return: a class:`TokenCredentials` object
        """
        tenant_id = json_blob['auth'].get('tenantName')
        if tenant_id is None:
            tenant_id = json_blob['auth'].get('tenantId')

        token = json_blob['auth'][cls.type_key]['id']
        return cls(token=token, tenant_id=tenant_id)
示例#29
0
class Proxy(object):
    """
    proxy schema
    """
    host = attr(type=str, default=None)
    port = attr(type=int, default=None)

    def __str__(self):
        """
        to string, for print
        :return:
        """
        return f'{self.host}:{self.port}'

    def string(self):
        """
        to string
        :return: <host>:<port>
        """
        return self.__str__()
示例#30
0
class _IsInValidator(object):
    choices = attr.attr()

    def __call__(self, inst, attr, value):
        if value not in self.choices:
            raise ValueError("{attr} should be one of {choice}".format(
                attr=attr.name, choice=self.choices))

    def __repr__(self):
        return ("<is value present in list of  {choice}>".format(
            choice=self.choices))
示例#31
0
import os.path
import yaml

from attr import attributes, attr, validators, asdict


valid_str = validators.instance_of(str)

optional_str_attr = attr(
    validator=validators.optional(valid_str),
    default='',
)


@attributes
class Config:
    username = optional_str_attr
    password = optional_str_attr


def get_config(path):

    if not os.path.exists(path):
        return Config()

    with open(path) as f:
        config = yaml.load(f)

    return Config(
        username=config['username'],
        password=config['password'],