INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
decorator(caller) converts a caller function into a decorator
def decorator(caller, _func=None): """decorator(caller) converts a caller function into a decorator""" if _func is not None: # return a decorated function # this is obsolete behavior; you should use decorate instead return decorate(_func, caller) # else return a decorator function if in...
Append ``a`` to the list of the virtual ancestors, unless it is already included.
def append(a, vancestors): """ Append ``a`` to the list of the virtual ancestors, unless it is already included. """ add = True for j, va in enumerate(vancestors): if issubclass(va, a): add = False break if issubclass(a, va): vancestors[j] = a ...
Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's.
def text_fd_to_metric_families(fd): """Parse Prometheus text format from a file descriptor. This is a laxer parser than the main Go parser, so successful parsing does not imply that the parsed text meets the specification. Yields Metric's. """ name = '' documentation = '' typ = 'un...
Format a key for use in the mmap file.
def mmap_key(metric_name, name, labelnames, labelvalues): """Format a key for use in the mmap file.""" # ensure labels are in consistent order for identity labels = dict(zip(labelnames, labelvalues)) return json.dumps([metric_name, name, labels], sort_keys=True)
Yield (key, value, pos). No locking is performed.
def _read_all_values(self): """Yield (key, value, pos). No locking is performed.""" pos = 8 # cache variables to local ones and prevent attributes lookup # on every loop iteration used = self._used data = self._m unpack_from = struct.unpack_from while p...
Initialize a value. Lock must be held by caller.
def _init_value(self, key): """Initialize a value. Lock must be held by caller.""" encoded = key.encode('utf-8') # Pad to be 8-byte aligned. padded = encoded + (b' ' * (8 - (len(encoded) + 4) % 8)) value = struct.pack('i{0}sd'.format(len(padded)).encode(), len(encoded), padded, 0...
Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint']) c.labels(...
def labels(self, *labelvalues, **labelkwargs): """Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTT...
Remove the given labelset from the metric.
def remove(self, *labelvalues): if not self._labelnames: raise ValueError('No label names were set when constructing %s' % self) """Remove the given labelset from the metric.""" if len(labelvalues) != len(self._labelnames): raise ValueError('Incorrect label count (expect...
Call the provided function to return the Gauge value. The function must return a float, and may be called from multiple threads. All other methods of the Gauge become NOOPs.
def set_function(self, f): """Call the provided function to return the Gauge value. The function must return a float, and may be called from multiple threads. All other methods of the Gauge become NOOPs. """ def samples(self): return (('', {}, float(f())),) ...
Observe the given amount.
def observe(self, amount): """Observe the given amount.""" self._count.inc(1) self._sum.inc(amount)
Observe the given amount.
def observe(self, amount): """Observe the given amount.""" self._sum.inc(amount) for i, bound in enumerate(self._upper_bounds): if amount <= bound: self._buckets[i].inc(1) break
Set info metric.
def info(self, val): """Set info metric.""" if self._labelname_set.intersection(val.keys()): raise ValueError('Overlapping labels for Info metric, metric: %s child: %s' % ( self._labelnames, val)) with self._lock: self._value = dict(val)
Set enum metric state.
def state(self, state): """Set enum metric state.""" with self._lock: self._value = self._states.index(state)
Returns an instance from given settings. This uses by default the key ``dupefilter:<timestamp>``. When using the ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as it needs to pass the spider name in the key. Parameters ---------- settings : scrapy.s...
def from_settings(cls, settings): """Returns an instance from given settings. This uses by default the key ``dupefilter:<timestamp>``. When using the ``scrapy_redis.scheduler.Scheduler`` class, this method is not used as it needs to pass the spider name in the key. Parameters ...
Returns True if request was already seen. Parameters ---------- request : scrapy.http.Request Returns ------- bool
def request_seen(self, request): """Returns True if request was already seen. Parameters ---------- request : scrapy.http.Request Returns ------- bool """ fp = self.request_fingerprint(request) # This returns the number of values added, ...
Logs given request. Parameters ---------- request : scrapy.http.Request spider : scrapy.spiders.Spider
def log(self, request, spider): """Logs given request. Parameters ---------- request : scrapy.http.Request spider : scrapy.spiders.Spider """ if self.debug: msg = "Filtered duplicate request: %(request)s" self.logger.debug(msg, {'request'...
Process items from a redis queue. Parameters ---------- r : Redis Redis connection instance. keys : list List of keys to read the items from. timeout: int Read timeout.
def process_items(r, keys, timeout, limit=0, log_every=1000, wait=.1): """Process items from a redis queue. Parameters ---------- r : Redis Redis connection instance. keys : list List of keys to read the items from. timeout: int Read timeout. """ limit = limit o...
Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_PARAMS`` setting. Parameters ---------- settin...
def get_redis_from_settings(settings): """Returns a redis client instance from given Scrapy settings object. This function uses ``get_client`` to instantiate the client and uses ``defaults.REDIS_PARAMS`` global as defaults values for the parameters. You can override them using the ``REDIS_PARAMS`` sett...
Returns a redis client instance. Parameters ---------- redis_cls : class, optional Defaults to ``redis.StrictRedis``. url : str, optional If given, ``redis_cls.from_url`` is used to instantiate the class. **kwargs Extra parameters to be passed to the ``redis_cls`` class. ...
def get_redis(**kwargs): """Returns a redis client instance. Parameters ---------- redis_cls : class, optional Defaults to ``redis.StrictRedis``. url : str, optional If given, ``redis_cls.from_url`` is used to instantiate the class. **kwargs Extra parameters to be passed...
Returns a str if a bytes object is given.
def bytes_to_str(s, encoding='utf-8'): """Returns a str if a bytes object is given.""" if six.PY3 and isinstance(s, bytes): return s.decode(encoding) return s
Setup redis connection and idle signal. This should be called after the spider has set its crawler object.
def setup_redis(self, crawler=None): """Setup redis connection and idle signal. This should be called after the spider has set its crawler object. """ if self.server is not None: return if crawler is None: # We allow optional crawler argument to keep bac...
Returns a request to be scheduled or none.
def next_requests(self): """Returns a request to be scheduled or none.""" use_set = self.settings.getbool('REDIS_START_URLS_AS_SET', defaults.START_URLS_AS_SET) fetch_one = self.server.spop if use_set else self.server.lpop # XXX: Do we need to use a timeout here? found = 0 ...
Returns a Request instance from data coming from Redis. By default, ``data`` is an encoded URL. You can override this method to provide your own message decoding. Parameters ---------- data : bytes Message from redis.
def make_request_from_data(self, data): """Returns a Request instance from data coming from Redis. By default, ``data`` is an encoded URL. You can override this method to provide your own message decoding. Parameters ---------- data : bytes Message from redi...
Schedules a request if available
def schedule_next_requests(self): """Schedules a request if available""" # TODO: While there is capacity, schedule a batch of redis requests. for req in self.next_requests(): self.crawler.engine.crawl(req, spider=self)
Encode a request object
def _encode_request(self, request): """Encode a request object""" obj = request_to_dict(request, self.spider) return self.serializer.dumps(obj)
Decode an request previously encoded
def _decode_request(self, encoded_request): """Decode an request previously encoded""" obj = self.serializer.loads(encoded_request) return request_from_dict(obj, self.spider)
Push a request
def push(self, request): """Push a request""" self.server.lpush(self.key, self._encode_request(request))
Push a request
def push(self, request): """Push a request""" data = self._encode_request(request) score = -request.priority # We don't use zadd method as the order of arguments change depending on # whether the class is Redis or StrictRedis, and the option of using # kwargs only accepts...
Pop a request timeout not support in this queue class
def pop(self, timeout=0): """ Pop a request timeout not support in this queue class """ # use atomic range/remove using multi/exec pipe = self.server.pipeline() pipe.multi() pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0) results, count...
Find the closest xterm-256 approximation to the given RGB value. @param r,g,b: each is a number between 0-255 for the Red, Green, and Blue values @returns: integer between 0 and 255, compatible with xterm. >>> rgb2short(18, 52, 86) 23 >>> rgb2short(255, 255, 255) 231 >>> rgb2short(13, 173, 2...
def rgb2short(r, g, b): """ Find the closest xterm-256 approximation to the given RGB value. @param r,g,b: each is a number between 0-255 for the Red, Green, and Blue values @returns: integer between 0 and 255, compatible with xterm. >>> rgb2short(18, 52, 86) 23 >>> rgb2short(255, 255, 255) ...
Given a string name of one of the properties of this class, returns the value of the property as a string when the value is greater than 1. When it is not greater than one, returns an empty string. As an example, if you want to show an icon for new files, but you only want a number to a...
def n_or_empty(self, _key): """Given a string name of one of the properties of this class, returns the value of the property as a string when the value is greater than 1. When it is not greater than one, returns an empty string. As an example, if you want to show an icon for new files, ...
If the user has asked for each directory name to be shortened, will return the name up to their specified length. Otherwise returns the full name.
def maybe_shorten_name(powerline, name): """If the user has asked for each directory name to be shortened, will return the name up to their specified length. Otherwise returns the full name.""" max_size = powerline.segment_conf("cwd", "max_dir_size") if max_size: return name[:max_size] r...
Returns the foreground and background color to use for the given name.
def get_fg_bg(powerline, name, is_last_dir): """Returns the foreground and background color to use for the given name. """ if requires_special_home_display(powerline, name): return (powerline.theme.HOME_FG, powerline.theme.HOME_BG,) if is_last_dir: return (powerline.theme.CWD_FG, powerl...
Determine and check the current working directory for validity. Typically, an directory arises when you checkout a different branch on git that doesn't have this directory. When an invalid directory is found, a warning is printed to the screen, but the directory is still returned as-is, since this is w...
def get_valid_cwd(): """Determine and check the current working directory for validity. Typically, an directory arises when you checkout a different branch on git that doesn't have this directory. When an invalid directory is found, a warning is printed to the screen, but the directory is still returne...
Brutally simple email address validation. Note unlike most email address validation * raw ip address (literal) domain parts are not allowed. * "John Doe <local_part@domain.com>" style "pretty" email addresses are processed * the local part check is extremely basic. This raises the possibility of unicode spo...
def validate_email(value: str) -> Tuple[str, str]: """ Brutally simple email address validation. Note unlike most email address validation * raw ip address (literal) domain parts are not allowed. * "John Doe <local_part@domain.com>" style "pretty" email addresses are processed * the local part check...
Create a DSN from from connection settings. Stolen approximately from sqlalchemy/engine/url.py:URL.
def make_dsn( *, driver: str, user: str = None, password: str = None, host: str = None, port: str = None, name: str = None, query: Dict[str, Any] = None, ) -> str: """ Create a DSN from from connection settings. Stolen approximately from sqlalchemy/engine/url.py:URL. """...
Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import fails.
def import_string(dotted_path: str) -> Any: """ Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import fails. """ try: module_path, class_name = dotted_path.strip(' ').rsplit('.', 1...
Truncate a value and add a unicode ellipsis (three dots) to the end if it was too long
def truncate(v: str, *, max_len: int = 80) -> str: """ Truncate a value and add a unicode ellipsis (three dots) to the end if it was too long """ if isinstance(v, str) and len(v) > (max_len - 2): # -3 so quote + string + … + quote has correct length return repr(v[: (max_len - 3)] + '…') ...
Ensure that the field's name does not shadow an existing attribute of the model.
def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None: """ Ensure that the field's name does not shadow an existing attribute of the model. """ for base in bases: if getattr(base, field_name, None): raise NameError( f'Field name "{field_name...
Url regex generator taken from Marshmallow library, for details please follow library source code: https://github.com/marshmallow-code/marshmallow/blob/298870ef6c089fb4d91efae9ca4168453ffe00d2/marshmallow/validate.py#L37
def url_regex_generator(*, relative: bool, require_tld: bool) -> Pattern[str]: """ Url regex generator taken from Marshmallow library, for details please follow library source code: https://github.com/marshmallow-code/marshmallow/blob/298870ef6c089fb4d91efae9ca4168453ffe00d2/marshmallow/validate.py#...
Partially taken from typing.get_type_hints. Resolve string or ForwardRef annotations into type objects if possible.
def resolve_annotations(raw_annotations: Dict[str, AnyType], module_name: Optional[str]) -> Dict[str, AnyType]: """ Partially taken from typing.get_type_hints. Resolve string or ForwardRef annotations into type objects if possible. """ if module_name: base_globals: Optional[Dict[str, Any]] ...
Try to update ForwardRefs on fields based on this Field, globalns and localns.
def update_field_forward_refs(field: 'Field', globalns: Any, localns: Any) -> None: """ Try to update ForwardRefs on fields based on this Field, globalns and localns. """ if type(field.type_) == ForwardRef: field.type_ = field.type_._evaluate(globalns, localns or None) # type: ignore fi...
Assume IPv4Network initialised with a default ``strict`` argument See more: https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network
def ip_v4_network_validator(v: Any) -> IPv4Network: """ Assume IPv4Network initialised with a default ``strict`` argument See more: https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network """ if isinstance(v, IPv4Network): return v with change_exception(errors.IPv4Netw...
Assume IPv6Network initialised with a default ``strict`` argument See more: https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network
def ip_v6_network_validator(v: Any) -> IPv6Network: """ Assume IPv6Network initialised with a default ``strict`` argument See more: https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network """ if isinstance(v, IPv6Network): return v with change_exception(errors.IPv6Netw...
Perform a simple check if the value is callable. Note: complete matching of argument type hints and return types is not performed
def callable_validator(v: Any) -> AnyCallable: """ Perform a simple check if the value is callable. Note: complete matching of argument type hints and return types is not performed """ if callable(v): return v raise errors.CallableError(value=v)
Build environment variables suitable for passing to the Model.
def _build_environ(self) -> Dict[str, Optional[str]]: """ Build environment variables suitable for passing to the Model. """ d: Dict[str, Optional[str]] = {} if self.__config__.case_insensitive: env_vars = {k.lower(): v for k, v in os.environ.items()} else: ...
Decorate methods on the class indicating that they should be used to validate fields :param fields: which field(s) the method should be called on :param pre: whether or not this validator should be called before the standard validators (else after) :param whole: for complex objects (sets, lists etc.) whethe...
def validator( *fields: str, pre: bool = False, whole: bool = False, always: bool = False, check_fields: bool = True ) -> Callable[[AnyCallable], classmethod]: """ Decorate methods on the class indicating that they should be used to validate fields :param fields: which field(s) the method should be call...
Make a generic function which calls a validator with the right arguments. Unfortunately other approaches (eg. return a partial of a function that builds the arguments) is slow, hence this laborious way of doing things. It's done like this so validators don't all need **kwargs in their signature, eg. any c...
def make_generic_validator(validator: AnyCallable) -> 'ValidatorCallable': """ Make a generic function which calls a validator with the right arguments. Unfortunately other approaches (eg. return a partial of a function that builds the arguments) is slow, hence this laborious way of doing things. ...
Validate sequence-like containers: lists, tuples, sets and generators
def _validate_sequence_like( self, v: Any, values: Dict[str, Any], loc: 'LocType', cls: Optional['ModelOrDc'] ) -> 'ValidateReturn': """ Validate sequence-like containers: lists, tuples, sets and generators """ if not sequence_like(v): e: errors_.PydanticTypeErro...
Whether the field is "complex" eg. env variables should be parsed as JSON.
def is_complex(self) -> bool: """ Whether the field is "complex" eg. env variables should be parsed as JSON. """ from .main import BaseModel # noqa: F811 return ( self.shape != Shape.SINGLETON or lenient_issubclass(self.type_, (BaseModel, list, set, dict...
Process a list of models and generate a single JSON Schema with all of them defined in the ``definitions`` top-level JSON key, including their sub-models. :param models: a list of models to include in the generated JSON Schema :param by_alias: generate the schemas using the aliases defined, if any :par...
def schema( models: Sequence[Type['main.BaseModel']], *, by_alias: bool = True, title: Optional[str] = None, description: Optional[str] = None, ref_prefix: Optional[str] = None, ) -> Dict[str, Any]: """ Process a list of models and generate a single JSON Schema with all of them defined i...
Generate a JSON Schema for one model. With all the sub-models defined in the ``definitions`` top-level JSON key. :param model: a Pydantic model (a class that inherits from BaseModel) :param by_alias: generate the schemas using the aliases defined, if any :param ref_prefix: the JSON Pointer prefix for s...
def model_schema( model: Type['main.BaseModel'], by_alias: bool = True, ref_prefix: Optional[str] = None ) -> Dict[str, Any]: """ Generate a JSON Schema for one model. With all the sub-models defined in the ``definitions`` top-level JSON key. :param model: a Pydantic model (a class that inherits fr...
Process a Pydantic field and return a tuple with a JSON Schema for it as the first item. Also return a dictionary of definitions with models as keys and their schemas as values. If the passed field is a model and has sub-models, and those sub-models don't have overrides (as ``title``, ``default``, etc), they ...
def field_schema( field: Field, *, by_alias: bool = True, model_name_map: Dict[Type['main.BaseModel'], str], ref_prefix: Optional[str] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Process a Pydantic field and return a tuple with a JSON Schema for it as the first item. Also ret...
Get the JSON Schema validation keywords for a ``field`` with an annotation of a Pydantic ``Schema`` with validation arguments.
def get_field_schema_validations(field: Field) -> Dict[str, Any]: """ Get the JSON Schema validation keywords for a ``field`` with an annotation of a Pydantic ``Schema`` with validation arguments. """ f_schema: Dict[str, Any] = {} if lenient_issubclass(field.type_, (str, bytes)): for att...
Process a set of models and generate unique names for them to be used as keys in the JSON Schema definitions. By default the names are the same as the class name. But if two models in different Python modules have the same name (e.g. "users.Model" and "items.Model"), the generated names will be based on the...
def get_model_name_map(unique_models: Set[Type['main.BaseModel']]) -> Dict[Type['main.BaseModel'], str]: """ Process a set of models and generate unique names for them to be used as keys in the JSON Schema definitions. By default the names are the same as the class name. But if two models in different Pytho...
Take a single ``model`` and generate a set with itself and all the sub-models in the tree. I.e. if you pass model ``Foo`` (subclass of Pydantic ``BaseModel``) as ``model``, and it has a field of type ``Bar`` (also subclass of ``BaseModel``) and that model ``Bar`` has a field of type ``Baz`` (also subclass of ``...
def get_flat_models_from_model(model: Type['main.BaseModel']) -> Set[Type['main.BaseModel']]: """ Take a single ``model`` and generate a set with itself and all the sub-models in the tree. I.e. if you pass model ``Foo`` (subclass of Pydantic ``BaseModel``) as ``model``, and it has a field of type ``Bar`` (a...
Take a single Pydantic ``Field`` (from a model) that could have been declared as a sublcass of BaseModel (so, it could be a submodel), and generate a set with its model and all the sub-models in the tree. I.e. if you pass a field that was declared to be of type ``Foo`` (subclass of BaseModel) as ``field``, and ...
def get_flat_models_from_field(field: Field) -> Set[Type['main.BaseModel']]: """ Take a single Pydantic ``Field`` (from a model) that could have been declared as a sublcass of BaseModel (so, it could be a submodel), and generate a set with its model and all the sub-models in the tree. I.e. if you pass a...
Take a list of Pydantic ``Field``s (from a model) that could have been declared as sublcasses of ``BaseModel`` (so, any of them could be a submodel), and generate a set with their models and all the sub-models in the tree. I.e. if you pass a the fields of a model ``Foo`` (subclass of ``BaseModel``) as ``fields...
def get_flat_models_from_fields(fields: Sequence[Field]) -> Set[Type['main.BaseModel']]: """ Take a list of Pydantic ``Field``s (from a model) that could have been declared as sublcasses of ``BaseModel`` (so, any of them could be a submodel), and generate a set with their models and all the sub-models in t...
Take a list of ``models`` and generate a set with them and all their sub-models in their trees. I.e. if you pass a list of two models, ``Foo`` and ``Bar``, both subclasses of Pydantic ``BaseModel`` as models, and ``Bar`` has a field of type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``se...
def get_flat_models_from_models(models: Sequence[Type['main.BaseModel']]) -> Set[Type['main.BaseModel']]: """ Take a list of ``models`` and generate a set with them and all their sub-models in their trees. I.e. if you pass a list of two models, ``Foo`` and ``Bar``, both subclasses of Pydantic ``BaseModel`` ...
Used by ``field_schema()``, you probably should be using that function. Take a single ``field`` and generate the schema for its type only, not including additional information as title, etc. Also return additional schema definitions, from sub-models.
def field_type_schema( field: Field, *, by_alias: bool, model_name_map: Dict[Type['main.BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Used by ``field_schema()``, you probably should be using that funct...
Used by ``model_schema()``, you probably should be using that function. Take a single ``model`` and generate its schema. Also return additional schema definitions, from sub-models. The sub-models of the returned schema will be referenced, but their definitions will not be included in the schema. All the de...
def model_process_schema( model: Type['main.BaseModel'], *, by_alias: bool = True, model_name_map: Dict[Type['main.BaseModel'], str], ref_prefix: Optional[str] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ Used by ``model_schema()``, you probably should be using that function. ...
You probably should be using ``model_schema()``, this function is indirectly used by that function. Take a single ``model`` and generate the schema for its type only, not including additional information as title, etc. Also return additional schema definitions, from sub-models.
def model_type_schema( model: Type['main.BaseModel'], *, by_alias: bool, model_name_map: Dict[Type['main.BaseModel'], str], ref_prefix: Optional[str] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ You probably should be using ``model_schema()``, this function is indirectly used by t...
This function is indirectly used by ``field_schema()``, you probably should be using that function. Take a list of Pydantic ``Field`` from the declaration of a type with parameters, and generate their schema. I.e., fields used as "type parameters", like ``str`` and ``int`` in ``Tuple[str, int]``.
def field_singleton_sub_fields_schema( sub_fields: Sequence[Field], *, by_alias: bool, model_name_map: Dict[Type['main.BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ This function is indirectly used by ...
This function is indirectly used by ``field_schema()``, you should probably be using that function. Take a single Pydantic ``Field``, and return its schema and any additional definitions from sub-models.
def field_singleton_schema( # noqa: C901 (ignore complexity) field: Field, *, by_alias: bool, model_name_map: Dict[Type['main.BaseModel'], str], schema_overrides: bool = False, ref_prefix: Optional[str] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ This function is indirectly ...
Get an annotation with validation implemented for numbers and strings based on the schema. :param annotation: an annotation from a field specification, as ``str``, ``ConstrainedStr`` :param schema: an instance of Schema, possibly with declarations for validations and JSON Schema :return: the same ``annotat...
def get_annotation_from_schema(annotation: Any, schema: Schema) -> Type[Any]: """ Get an annotation with validation implemented for numbers and strings based on the schema. :param annotation: an annotation from a field specification, as ``str``, ``ConstrainedStr`` :param schema: an instance of Schema, ...
Dynamically create a model. :param model_name: name of the created model :param __config__: config class to use for the new model :param __base__: base class for the new model to inherit from :param __validators__: a dict of method names and @validator class methods :param **field_definitions: field...
def create_model( # noqa: C901 (ignore complexity) model_name: str, *, __config__: Type[BaseConfig] = None, __base__: Type[BaseModel] = None, __module__: Optional[str] = None, __validators__: Dict[str, classmethod] = None, **field_definitions: Any, ) -> BaseModel: """ Dynamically cr...
validate data against a model.
def validate_model( # noqa: C901 (ignore complexity) model: Union[BaseModel, Type[BaseModel]], input_data: 'DictStrAny', raise_exc: bool = True, cls: 'ModelOrDc' = None ) -> Union['DictStrAny', Tuple['DictStrAny', Optional[ValidationError]]]: """ validate data against a model. """ values = {} e...
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
def dict( self, *, include: 'SetStr' = None, exclude: 'SetStr' = None, by_alias: bool = False, skip_defaults: bool = False ) -> 'DictStrAny': """ Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. """ get_key = self._g...
Generate a JSON representation of the model, `include` and `exclude` arguments as per `dict()`. `encoder` is an optional function to supply as `default` to json.dumps(), other arguments as per `json.dumps()`.
def json( self, *, include: 'SetStr' = None, exclude: 'SetStr' = None, by_alias: bool = False, skip_defaults: bool = False, encoder: Optional[Callable[[Any], Any]] = None, **dumps_kwargs: Any, ) -> str: """ Generate a JSON representatio...
Creates a new model and set __values__ without any validation, thus values should already be trusted. Chances are you don't want to use this method directly.
def construct(cls: Type['Model'], values: 'DictAny', fields_set: 'SetStr') -> 'Model': """ Creates a new model and set __values__ without any validation, thus values should already be trusted. Chances are you don't want to use this method directly. """ m = cls.__new__(cls) ...
Duplicate a model, optionally choose which fields to include, exclude and change. :param include: fields to include in new model :param exclude: fields to exclude from new model, as with values this takes precedence over include :param update: values to change/add in the new model. Note: the da...
def copy( self: 'Model', *, include: 'SetStr' = None, exclude: 'SetStr' = None, update: 'DictStrAny' = None, deep: bool = False, ) -> 'Model': """ Duplicate a model, optionally choose which fields to include, exclude and change. :param include...
Try to update ForwardRefs on fields based on this Model, globalns and localns.
def update_forward_refs(cls, **localns: Any) -> None: """ Try to update ForwardRefs on fields based on this Model, globalns and localns. """ globalns = sys.modules[cls.__module__].__dict__ globalns.setdefault(cls.__name__, cls) for f in cls.__fields__.values(): ...
ISO 8601 encoding for timedeltas.
def timedelta_isoformat(td: datetime.timedelta) -> str: """ ISO 8601 encoding for timedeltas. """ minutes, seconds = divmod(td.seconds, 60) hours, minutes = divmod(minutes, 60) return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
Parse a date/int/float/string and return a datetime.date. Raise ValueError if the input is well formatted but not a valid date. Raise ValueError if the input isn't well formatted.
def parse_date(value: Union[date, StrIntFloat]) -> date: """ Parse a date/int/float/string and return a datetime.date. Raise ValueError if the input is well formatted but not a valid date. Raise ValueError if the input isn't well formatted. """ if isinstance(value, date): if isinstance(...
Parse a time/string and return a datetime.time. This function doesn't support time zone offsets. Raise ValueError if the input is well formatted but not a valid time. Raise ValueError if the input isn't well formatted, in particular if it contains an offset.
def parse_time(value: Union[time, str]) -> time: """ Parse a time/string and return a datetime.time. This function doesn't support time zone offsets. Raise ValueError if the input is well formatted but not a valid time. Raise ValueError if the input isn't well formatted, in particular if it contai...
Parse a datetime/int/float/string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input is well formatted but not a valid datetime. Raise ValueError if the input isn'...
def parse_datetime(value: Union[datetime, StrIntFloat]) -> datetime: """ Parse a datetime/int/float/string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input i...
Parse a duration int/float/string and return a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation.
def parse_duration(value: StrIntFloat) -> timedelta: """ Parse a duration int/float/string and return a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation. """ if isinstance(value, timedelta): return value if...
Decorator that converts Issue and Project resources to their keys when used as arguments.
def translate_resource_args(func): """Decorator that converts Issue and Project resources to their keys when used as arguments.""" @wraps(func) def wrapper(*args, **kwargs): """ :type args: *Any :type kwargs: **Any :return: Any """ arg_list = [] for ar...
Check if the current version of the library is outdated.
def _check_update_(self): """Check if the current version of the library is outdated.""" try: data = requests.get("https://pypi.python.org/pypi/jira/json", timeout=2.001).json() released_version = data['info']['version'] if parse_version(released_version) > parse_ver...
Fetch pages. :param item_type: Type of single item. ResultList of such items will be returned. :type item_type: type :param items_key: Path to the items in JSON returned from server. Set it to None, if response is an array, and not a JSON object. :type items_key: Optiona...
def _fetch_pages(self, item_type, items_key, request_path, startAt=0, maxResults=50, params=None, base=JIRA_BASE_URL, ): """Fetch pages. ...
:type item_type: type :type items_key: str :type resource: Dict[str, Any] :rtype: Union[List[Dashboard], List[Issue]]
def _get_items_from_page(self, item_type, items_key, resource, ): """ :type item_type: type :type items_key: str :type resource: Dict[str, Any] :rtype: Union[List[D...
Find Resource object for any addressable resource on the server. This method is a universal resource locator for any REST-ful resource in JIRA. The argument ``resource_format`` is a string of the form ``resource``, ``resource/{0}``, ``resource/{0}/sub``, ``resource/{0}/sub/{1}``, etc. The forma...
def find(self, resource_format, ids=None): """Find Resource object for any addressable resource on the server. This method is a universal resource locator for any REST-ful resource in JIRA. The argument ``resource_format`` is a string of the form ``resource``, ``resource/{0}``, ``resour...
Execute all asynchronous jobs and wait for them to finish. By default it will run on 10 threads. :param size: number of threads to run on.
def async_do(self, size=10): """Execute all asynchronous jobs and wait for them to finish. By default it will run on 10 threads. :param size: number of threads to run on. """ if hasattr(self._session, '_async_jobs'): logging.info("Executing asynchronous %s jobs found in queu...
Return the mutable server application properties. :param key: the single property to return a value for :type key: Optional[str] :rtype: Union[Dict[str, str], List[Dict[str, str]]]
def application_properties(self, key=None): """Return the mutable server application properties. :param key: the single property to return a value for :type key: Optional[str] :rtype: Union[Dict[str, str], List[Dict[str, str]]] """ params = {} if key is not None...
Set the application property. :param key: key of the property to set :type key: str :param value: value to assign to the property :type value: str
def set_application_property(self, key, value): """Set the application property. :param key: key of the property to set :type key: str :param value: value to assign to the property :type value: str """ url = self._options['server'] + \ '/rest/api/late...
List of application links. :return: json
def applicationlinks(self, cached=True): """List of application links. :return: json """ # if cached, return the last result if cached and hasattr(self, '_applicationlinks'): return self._applicationlinks # url = self._options['server'] + '/rest/applinks/lat...
Attach an attachment to an issue and returns a Resource for it. The client will *not* attempt to open or validate the attachment; it expects a file-like object to be ready for its use. The user is still responsible for tidying up (e.g., closing the file, killing the socket, etc.) :param issue:...
def add_attachment(self, issue, attachment, filename=None): """Attach an attachment to an issue and returns a Resource for it. The client will *not* attempt to open or validate the attachment; it expects a file-like object to be ready for its use. The user is still responsible for tidying up (e...
Delete attachment by id. :param id: ID of the attachment to delete :type id: str
def delete_attachment(self, id): """Delete attachment by id. :param id: ID of the attachment to delete :type id: str """ url = self._get_url('attachment/' + str(id)) return self._session.delete(url)
Create a component inside a project and return a Resource for it. :param name: name of the component :type name: str :param project: key of the project to create the component in :type project: str :param description: a description of the component :type description: str...
def create_component(self, name, project, description=None, leadUserName=None, assigneeType=None, isAssigneeTypeValid=False, ): """Create...
Return a ResultList of Dashboard resources and a ``total`` count. :param filter: either "favourite" or "my", the type of dashboards to return :type filter: Optional[str] :param startAt: index of the first dashboard to return (Default: 0) :type startAt: int :param maxResults: max...
def dashboards(self, filter=None, startAt=0, maxResults=20): """Return a ResultList of Dashboard resources and a ``total`` count. :param filter: either "favourite" or "my", the type of dashboards to return :type filter: Optional[str] :param startAt: index of the first dashboard to retur...
Delete component by id. :param id: ID of the component to use :type id: str :rtype: Response
def delete_component(self, id): """Delete component by id. :param id: ID of the component to use :type id: str :rtype: Response """ url = self._get_url('component/' + str(id)) return self._session.delete(url)
Get a list of filter Resources which are the favourites of the currently authenticated user. :rtype: List[Filter]
def favourite_filters(self): """Get a list of filter Resources which are the favourites of the currently authenticated user. :rtype: List[Filter] """ r_json = self._get_json('filter/favourite') filters = [Filter(self._options, self._session, raw_filter_json) f...
Create a new filter and return a filter Resource for it. :param name: name of the new filter :type name: str :param description: useful human readable description of the new filter :type description: str :param jql: query string that defines the filter :type jql: str ...
def create_filter(self, name=None, description=None, jql=None, favourite=None): """Create a new filter and return a filter Resource for it. :param name: name of the new filter :type name: str :param description: useful human readable description of the new filter ...
Update a filter and return a filter Resource for it. :param name: name of the new filter :type name: Optional[str] :param description: useful human readable description of the new filter :type description: Optional[str] :param jql: query string that defines the filter :t...
def update_filter(self, filter_id, name=None, description=None, jql=None, favourite=None): """Update a filter and return a filter Resource for it. :param name: name of the new filter :type name: Optional[str] :param description: useful human r...
Get a group Resource from the server. :param id: ID of the group to get :param id: str :param expand: Extra information to fetch inside each resource :type expand: Optional[Any] :rtype: User
def group(self, id, expand=None): """Get a group Resource from the server. :param id: ID of the group to get :param id: str :param expand: Extra information to fetch inside each resource :type expand: Optional[Any] :rtype: User """ group = Group(self._op...
Return a list of groups matching the specified criteria. :param query: filter groups by name with this string :type query: Optional[str] :param exclude: filter out groups by name with this string :type exclude: Optional[Any] :param maxResults: maximum results to return. (Default...
def groups(self, query=None, exclude=None, maxResults=9999): """Return a list of groups matching the specified criteria. :param query: filter groups by name with this string :type query: Optional[str] :param exclude: filter out groups by name with this string :type exclude: Opti...
Return a hash or users with their information. Requires JIRA 6.0 or will raise NotImplemented. :param group: Name of the group. :type group: str
def group_members(self, group): """Return a hash or users with their information. Requires JIRA 6.0 or will raise NotImplemented. :param group: Name of the group. :type group: str """ if self._version < (6, 0, 0): raise NotImplementedError( "Group mem...
Create a new group in JIRA. :param groupname: The name of the group you wish to create. :type groupname: str :return: Boolean - True if successful. :rtype: bool
def add_group(self, groupname): """Create a new group in JIRA. :param groupname: The name of the group you wish to create. :type groupname: str :return: Boolean - True if successful. :rtype: bool """ url = self._options['server'] + '/rest/api/latest/group' ...
Delete a group from the JIRA instance. :param groupname: The group to be deleted from the JIRA instance. :type groupname: str :return: Boolean. Returns True on success. :rtype: bool
def remove_group(self, groupname): """Delete a group from the JIRA instance. :param groupname: The group to be deleted from the JIRA instance. :type groupname: str :return: Boolean. Returns True on success. :rtype: bool """ # implementation based on # htt...
Get an issue Resource from the server. :param id: ID or key of the issue to get :type id: Union[Issue, str] :param fields: comma-separated string of issue fields to include in the results :type fields: Optional[str] :param expand: extra information to fetch inside each resource ...
def issue(self, id, fields=None, expand=None): """Get an issue Resource from the server. :param id: ID or key of the issue to get :type id: Union[Issue, str] :param fields: comma-separated string of issue fields to include in the results :type fields: Optional[str] :para...