INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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.
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
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
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.
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. ) whether to v...
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.
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.
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.
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 will be included...
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 Python modu...
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 BaseModel ) the return value will b...
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 that model Foo...
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 and on of them has...
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 set ( [ Foo Bar Baz ] ).
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.
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.
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.
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.
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.
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.
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
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 ().
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
def create_component(self, name, project, description=None, leadUserName=None, assigneeType=None, isAssigneeTypeValid=False, ): """Create...
Delete component by id.
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)
Return a ResultList of Dashboard resources and a total count.
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...
Get a list of filter Resources which are the favourites of the currently authenticated user.
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.
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.
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.
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.
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.
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.
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.
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.
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...
Create a new issue and return an issue Resource for it.
def create_issue(self, fields=None, prefetch=True, **fieldargs): """Create a new issue and return an issue Resource for it. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field -- if the fields...
Bulk create new issues and return an issue Resource for each successfully created issue.
def create_issues(self, field_list, prefetch=True): """Bulk create new issues and return an issue Resource for each successfully created issue. See `create_issue` documentation for field information. :param field_list: a list of dicts each containing field names and the values to use. Each dic...
Returns whether or not the JIRA instance supports service desk.
def supports_service_desk(self): """Returns whether or not the JIRA instance supports service desk. :rtype: bool """ url = self._options['server'] + '/rest/servicedeskapi/info' headers = {'X-ExperimentalApi': 'opt-in'} try: r = self._session.get(url, headers=...
Create a new customer and return an issue Resource for it.
def create_customer(self, email, displayName): """Create a new customer and return an issue Resource for it. :param email: Customer Email :type email: str :param displayName: Customer display name :type displayName: str :rtype: Customer """ url = self._o...
Get a list of ServiceDesk Resources from the server visible to the current authenticated user.
def service_desks(self): """Get a list of ServiceDesk Resources from the server visible to the current authenticated user. :rtype: List[ServiceDesk] """ url = self._options['server'] + '/rest/servicedeskapi/servicedesk' headers = {'X-ExperimentalApi': 'opt-in'} r_json =...
Create a new customer request and return an issue Resource for it.
def create_customer_request(self, fields=None, prefetch=True, **fieldargs): """Create a new customer request and return an issue Resource for it. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that ...
Get the metadata required to create issues optionally filtered by projects and issue types.
def createmeta(self, projectKeys=None, projectIds=[], issuetypeIds=None, issuetypeNames=None, expand=None, ): """Get the metadata required to create issues, optionally filtered by projects and issue...
Assign an issue to a user. None will set it to unassigned. - 1 will set it to Automatic.
def assign_issue(self, issue, assignee): """Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic. :param issue: the issue ID or key to assign :type issue: int or str :param assignee: the user to assign the issue to :type assignee: str :...
Get a list of comment Resources.
def comments(self, issue): """Get a list of comment Resources. :param issue: the issue to get comments from :type issue: str :rtype: List[Comment] """ r_json = self._get_json('issue/' + str(issue) + '/comment') comments = [Comment(self._options, self._session, r...
Add a comment from the current authenticated user on the specified issue and return a Resource for it.
def add_comment(self, issue, body, visibility=None, is_internal=False): """Add a comment from the current authenticated user on the specified issue and return a Resource for it. The issue identifier and comment body are required. :param issue: ID or key of the issue to add the comment to ...
Get a list of remote link Resources from an issue.
def remote_links(self, issue): """Get a list of remote link Resources from an issue. :param issue: the issue to get remote links from """ r_json = self._get_json('issue/' + str(issue) + '/remotelink') remote_links = [RemoteLink( self._options, self._session, raw_remo...
Add a remote link from an issue to an external application and returns a remote link Resource for it.
def add_remote_link(self, issue, destination, globalId=None, application=None, relationship=None): """Add a remote link from an issue to an external application and returns a remote link Resource for it. ``object`` should be a dict containing at least ``url`` to the linked external URL and ``ti...
Add a simple remote link from an issue to web resource.
def add_simple_link(self, issue, object): """Add a simple remote link from an issue to web resource. This avoids the admin access problems from add_remote_link by just using a simple object and presuming all fields are correct and not requiring more complex ``application`` data....
Get a list of the transitions available on the specified issue to the current user.
def transitions(self, issue, id=None, expand=None): """Get a list of the transitions available on the specified issue to the current user. :param issue: ID or key of the issue to get the transitions from :param id: if present, get only the transition matching this ID :param expand: extr...
Get a transitionid available on the specified issue to the current user.
def find_transitionid_by_name(self, issue, transition_name): """Get a transitionid available on the specified issue to the current user. Look at https://developer.atlassian.com/static/rest/jira/6.1.html#d2e1074 for json reference :param issue: ID or key of the issue to get the transitions from...
Perform a transition on an issue.
def transition_issue(self, issue, transition, fields=None, comment=None, worklog=None, **fieldargs): """Perform a transition on an issue. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field --...
Register a vote for the current authenticated user on an issue.
def add_vote(self, issue): """Register a vote for the current authenticated user on an issue. :param issue: ID or key of the issue to vote on :rtype: Response """ url = self._get_url('issue/' + str(issue) + '/votes') return self._session.post(url)
Remove the current authenticated user s vote from an issue.
def remove_vote(self, issue): """Remove the current authenticated user's vote from an issue. :param issue: ID or key of the issue to remove vote on """ url = self._get_url('issue/' + str(issue) + '/votes') self._session.delete(url)
Add a user to an issue s watchers list.
def add_watcher(self, issue, watcher): """Add a user to an issue's watchers list. :param issue: ID or key of the issue affected :param watcher: username of the user to add to the watchers list """ url = self._get_url('issue/' + str(issue) + '/watchers') self._session.pos...
Remove a user from an issue s watch list.
def remove_watcher(self, issue, watcher): """Remove a user from an issue's watch list. :param issue: ID or key of the issue affected :param watcher: username of the user to remove from the watchers list :rtype: Response """ url = self._get_url('issue/' + str(issue) + '/w...
Get a list of worklog Resources from the server for an issue.
def worklogs(self, issue): """Get a list of worklog Resources from the server for an issue. :param issue: ID or key of the issue to get worklogs from :rtype: List[Worklog] """ r_json = self._get_json('issue/' + str(issue) + '/worklog') worklogs = [Worklog(self._options, ...
Add a new worklog entry on an issue and return a Resource for it.
def add_worklog(self, issue, timeSpent=None, timeSpentSeconds=None, adjustEstimate=None, newEstimate=None, reduceBy=None, comment=None, started=None, ...
Create a link between two issues.
def create_issue_link(self, type, inwardIssue, outwardIssue, comment=None): """Create a link between two issues. :param type: the type of link to create :param inwardIssue: the issue to link from :param outwardIssue: the issue to link to :param comment: a comment to add to the ...
Delete a link between two issues.
def delete_issue_link(self, id): """Delete a link between two issues. :param id: ID of the issue link to delete """ url = self._get_url('issueLink') + "/" + id return self._session.delete(url)
Get a list of issue link type Resources from the server.
def issue_link_types(self): """Get a list of issue link type Resources from the server. :rtype: List[IssueLinkType] """ r_json = self._get_json('issueLinkType') link_types = [IssueLinkType(self._options, self._session, raw_link_json) for raw_link_json in r_...
Get a list of issue type Resources from the server.
def issue_types(self): """Get a list of issue type Resources from the server. :rtype: List[IssueType] """ r_json = self._get_json('issuetype') issue_types = [IssueType( self._options, self._session, raw_type_json) for raw_type_json in r_json] return issue_ty...
: param name: Name of the issue type: type name: str: rtype: IssueType
def issue_type_by_name(self, name): """ :param name: Name of the issue type :type name: str :rtype: IssueType """ issue_types = self.issue_types() try: issue_type = [it for it in issue_types if it.name == name][0] except IndexError: ...
Returns request types supported by a service desk instance.: param service_desk: The service desk instance.: type service_desk: ServiceDesk: rtype: List [ RequestType ]
def request_types(self, service_desk): """ Returns request types supported by a service desk instance. :param service_desk: The service desk instance. :type service_desk: ServiceDesk :rtype: List[RequestType] """ if hasattr(service_desk, 'id'): service_desk = ...
Get a dict of all available permissions on the server.
def my_permissions(self, projectKey=None, projectId=None, issueKey=None, issueId=None, ): """Get a dict of all available permissions on the server. :param projectKey: limit returned permis...
Get a list of priority Resources from the server.
def priorities(self): """Get a list of priority Resources from the server. :rtype: List[Priority] """ r_json = self._get_json('priority') priorities = [Priority( self._options, self._session, raw_priority_json) for raw_priority_json in r_json] return priorit...
Get a list of project Resources from the server visible to the current authenticated user.
def projects(self): """Get a list of project Resources from the server visible to the current authenticated user. :rtype: List[Project] """ r_json = self._get_json('project') projects = [Project( self._options, self._session, raw_project_json) for raw_project_json i...
Register an image file as a project avatar.
def create_temp_project_avatar(self, project, filename, size, avatar_img, contentType=None, auto_confirm=False): """Register an image file as a project avatar. The avatar created is temporary and must be confirmed before it can be used. Avatar images are specified by a filename, si...
Confirm the temporary avatar image previously uploaded with the specified cropping.
def confirm_project_avatar(self, project, cropping_properties): """Confirm the temporary avatar image previously uploaded with the specified cropping. After a successful registry with :py:meth:`create_temp_project_avatar`, use this method to confirm the avatar for use. The final avatar can be a...
Set a project s avatar.
def set_project_avatar(self, project, avatar): """Set a project's avatar. :param project: ID or key of the project to set the avatar on :param avatar: ID of the avatar to set """ self._set_avatar( None, self._get_url('project/' + project + '/avatar'), avatar)
Delete a project s avatar.
def delete_project_avatar(self, project, avatar): """Delete a project's avatar. :param project: ID or key of the project to delete the avatar from :param avatar: ID of the avatar to delete """ url = self._get_url('project/' + project + '/avatar/' + avatar) return self._s...
Get a list of component Resources present on a project.
def project_components(self, project): """Get a list of component Resources present on a project. :param project: ID or key of the project to get components from :type project: str :rtype: List[Component] """ r_json = self._get_json('project/' + project + '/components') ...