Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def check_bot(task_type=SYSTEM_TASK): if glb.wxbot.bot.alive: msg = generate_run_info() message = Message(content=msg, receivers='status') glb.wxbot.send_msg(message) _logger.info( '{0} Send status message {1} at {2:%Y-%m-...
[ "\n wxpy bot 健康检查任务\n " ]
Please provide a description of the function:def timeout_message_report(): timeout_list = glb.ioloop._timeouts delay_task = [] for timeout in timeout_list: if not timeout.callback: continue if len(timeout.callback.args) == 2: task_type, message = timeout.callback...
[ "\n 周期/延时 消息报告\n " ]
Please provide a description of the function:def register_listener_handle(wxbot): from wxpy import TEXT @wxbot.bot.register(wxbot.default_receiver, TEXT, except_self=False) def sender_command_handle(msg): command_dict = {MESSAGE_REPORT_COMMAND: timeout_message_report(), ...
[ "\n wechat_sender 向 wxpy 注册控制消息 handler\n " ]
Please provide a description of the function:def listen(bot, receivers=None, token=None, port=10245, status_report=False, status_receiver=None, status_interval=DEFAULT_REPORT_TIME): global glb periodic_list = [] app = Application() wxbot = WxBot(bot, receivers, status_receiver) regis...
[ "\n 传入 bot 实例并启动 wechat_sender 服务\n\n :param bot: (必填|Bot对象) - wxpy 的 Bot 对象实例\n :param receivers: (选填|wxpy.Chat 对象|Chat 对象列表) - 消息接收者,wxpy 的 Chat 对象实例, 或 Chat 对象列表,如果为 list 第一个 Chat 为默认接收者。如果为 Chat 对象,则默认接收者也是此对象。 不填为当前 bot 对象的文件接收者\n :param token: (选填|str) - 信令,防止 receiver 被非法滥用,建议加上 token 防止非法使用,如果使用...
Please provide a description of the function:def run( target, target_type, tags=None, ruleset_name=None, ruleset_file=None, ruleset=None, logging_level=logging.WARNING, checks_paths=None, pull=None, insecure=False, skips=None, timeout=None, ): _set_logging(level=...
[ "\n Runs the sanity checks for the target.\n\n :param timeout: timeout per-check (in seconds)\n :param skips: name of checks to skip\n :param target: str (image name, ostree or dockertar)\n or ImageTarget\n or path/file-like object for dockerfile\n :param target_...
Please provide a description of the function:def get_checks( target_type=None, tags=None, ruleset_name=None, ruleset_file=None, ruleset=None, logging_level=logging.WARNING, checks_paths=None, skips=None, ): _set_logging(level=logging_level) logger.debug("Finding checks start...
[ "\n Get the sanity checks for the target.\n\n :param skips: name of checks to skip\n :param target_type: TargetType enum\n :param tags: list of str (if not None, the checks will be filtered by tags.)\n :param ruleset_name: str (e.g. fedora; if None, default would be used)\n :param ruleset_file: fi...
Please provide a description of the function:def _set_logging( logger_name="colin", level=logging.INFO, handler_class=logging.StreamHandler, handler_kwargs=None, format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s', date_format='%H:%M:%S'): ...
[ "\n Set personal logger for this library.\n\n :param logger_name: str, name of the logger\n :param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler\n :param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr)\n :param handler_kwargs: dict, keywor...
Please provide a description of the function:def check_label(labels, required, value_regex, target_labels): present = target_labels is not None and not set(labels).isdisjoint(set(target_labels)) if present: if required and not value_regex: return True elif value_regex: ...
[ "\n Check if the label is required and match the regex\n\n :param labels: [str]\n :param required: bool (if the presence means pass or not)\n :param value_regex: str (using search method)\n :param target_labels: [str]\n :return: bool (required==True: True if the label is present and match the rege...
Please provide a description of the function:def json(self): return { 'name': self.name, 'message': self.message, 'description': self.description, 'reference_url': self.reference_url, 'tags': self.tags, }
[ "\n Get json representation of the check\n\n :return: dict (str -> obj)\n " ]
Please provide a description of the function:def get_checks_paths(checks_paths=None): p = os.path.join(__file__, os.pardir, os.pardir, os.pardir, "checks") p = os.path.abspath(p) # let's utilize the default upstream checks always if checks_paths: p += [os.path.abspath(x) for x in checks_pat...
[ "\n Get path to checks.\n\n :param checks_paths: list of str, directories where the checks are present\n :return: list of str (absolute path of directory with checks)\n " ]
Please provide a description of the function:def get_ruleset_file(ruleset=None): ruleset = ruleset or "default" ruleset_dirs = get_ruleset_dirs() for ruleset_directory in ruleset_dirs: possible_ruleset_files = [os.path.join(ruleset_directory, ruleset + ext) for ext in EXTS] for rulese...
[ "\n Get the ruleset file from name\n\n :param ruleset: str\n :return: str\n " ]
Please provide a description of the function:def get_ruleset_dirs(): ruleset_dirs = [] cwd_rulesets = os.path.join(".", RULESET_DIRECTORY_NAME) if os.path.isdir(cwd_rulesets): logger.debug("Ruleset directory found in current directory ('{}').".format(cwd_rulesets)) ruleset_dirs.append...
[ "\n Get the directory with ruleset files\n First directory to check: ./rulesets\n Second directory to check: $HOME/.local/share/colin/rulesets\n Third directory to check: /usr/local/share/colin/rulesets\n :return: str\n " ]
Please provide a description of the function:def get_rulesets(): rulesets_dirs = get_ruleset_dirs() ruleset_files = [] for rulesets_dir in rulesets_dirs: for f in os.listdir(rulesets_dir): for ext in EXTS: file_path = os.path.join(rulesets_dir, f) if ...
[ "\"\n Get available rulesets.\n " ]
Please provide a description of the function:def get_checks(self, target_type, tags=None, skips=None): skips = skips or [] result = [] for check_struct in self.ruleset_struct.checks: if check_struct.name in skips: continue logger.debug("Processin...
[ "\n Get all checks for given type/tags.\n\n :param skips: list of str\n :param target_type: TargetType class\n :param tags: list of str\n :return: list of check instances\n " ]
Please provide a description of the function:def get_version_msg_from_the_cmd(package_name, cmd=None, use_rpm=None, max_lines_of_the_output=None): if use_rpm is None: use_rpm = is_rpm_installed() if use_rpm: rpm_version = get_rpm_version(package_name=package...
[ "\n Get str with the version (or string representation of the error).\n\n :param package_name: str\n :param cmd: str or [str] (defaults to [package_name, \"--version\"])\n :param use_rpm: True/False/None (whether to use rpm -q for getting a version)\n :param max_lines_of_the_output: use first n lines...
Please provide a description of the function:def get_rpm_version(package_name): version_result = subprocess.run(["rpm", "-q", package_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if version_result.returncode == 0: ret...
[ "Get a version of the package with 'rpm -q' command." ]
Please provide a description of the function:def is_rpm_installed(): try: version_result = subprocess.run(["rpm", "--usage"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) rpm_installed = not version_result.return...
[ "Tests if the rpm command is present." ]
Please provide a description of the function:def exit_after(s): def outer(fn): def inner(*args, **kwargs): timer = threading.Timer(s, thread.interrupt_main) timer.start() try: result = fn(*args, **kwargs) except KeyboardInterrupt: ...
[ "\n Use as decorator to exit process if\n function takes longer than s seconds.\n\n Direct call is available via exit_after(TIMEOUT_IN_S)(fce)(args).\n\n Inspired by https://stackoverflow.com/a/31667005\n " ]
Please provide a description of the function:def retry(retry_count=5, delay=2): if retry_count <= 0: raise ValueError("retry_count have to be positive") def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): for i in range(retry_count, 0, -1): ...
[ "\n Use as decorator to retry functions few times with delays\n\n Exception will be raised if last call fails\n\n :param retry_count: int could of retries in case of failures. It must be\n a positive number\n :param delay: int delay between retries\n " ]
Please provide a description of the function:def parse(cls, image_name): result = cls() # registry.org/namespace/repo:tag s = image_name.split('/', 2) if len(s) == 2: if '.' in s[0] or ':' in s[0]: result.registry = s[0] else: ...
[ "\n Get the instance of ImageName from the string representation.\n\n :param image_name: str (any possible form of image name)\n :return: ImageName instance\n " ]
Please provide a description of the function:def name(self): name_parts = [] if self.registry: name_parts.append(self.registry) if self.namespace: name_parts.append(self.namespace) if self.repository: name_parts.append(self.repository) ...
[ "\n Get the string representation of the image\n (registry, namespace, repository and digest together).\n\n :return: str\n " ]
Please provide a description of the function:def nicer_get(di, required, *path): r = di for p in path: try: r = r[p] except KeyError: if required: logger.error("can't locate %s in ruleset dict, keys present: %s", p, list(...
[ "\n this is a nicer way of doing dict.get()\n\n :param di: dict\n :param required: bool, raises an exc if value is not found, otherwise returns None\n :param path: list of str to navigate in the dict\n :return: your value\n " ]
Please provide a description of the function:def other_attributes(self): return {k: v for k, v in self.c.items() if k not in ["name", "names", "tags", "additional_tags", "usable_targets"]}
[ " return dict with all other data except for the described above" ]
Please provide a description of the function:def should_we_load(kls): # we don't load abstract classes if kls.__name__.endswith("AbstractCheck"): return False # and we only load checks if not kls.__name__.endswith("Check"): return False mro = kls.__mro__ # and the class need...
[ " should we load this class as a check? " ]
Please provide a description of the function:def obtain_check_classes(self): check_classes = set() for path in self.paths: for root, _, files in os.walk(path): for fi in files: if not fi.endswith(".py"): continue ...
[ " find children of AbstractCheck class and return them as a list " ]
Please provide a description of the function:def import_class(self, import_name): module_name, class_name = import_name.rsplit(".", 1) mod = import_module(module_name) check_class = getattr(mod, class_name) self.mapping[check_class.name] = check_class logger.info("succes...
[ "\n import selected class\n\n :param import_name, str, e.g. some.module.MyClass\n :return the class\n " ]
Please provide a description of the function:def _dict_of_results(self): result_json = {} result_list = [] for r in self.results: result_list.append({ 'name': r.check_name, 'ok': r.ok, 'status': r.status, 'desc...
[ "\n Get the dictionary representation of results\n\n :return: dict (str -> dict (str -> str))\n " ]
Please provide a description of the function:def statistics(self): result = {} for r in self.results: result.setdefault(r.status, 0) result[r.status] += 1 return result
[ "\n Get the dictionary with the count of the check-statuses\n\n :return: dict(str -> int)\n " ]
Please provide a description of the function:def generate_pretty_output(self, stat, verbose, output_function, logs=True): has_check = False for r in self.results: has_check = True if stat: output_function(OUTPUT_CHARS[r.status], ...
[ "\n Send the formated to the provided function\n\n :param stat: if True print stat instead of full output\n :param verbose: bool\n :param output_function: function to send output to\n " ]
Please provide a description of the function:def get_pretty_string(self, stat, verbose): pretty_output = _PrettyOutputToStr() self.generate_pretty_output(stat=stat, verbose=verbose, output_function=pretty_output.save_output...
[ "\n Pretty string representation of the results\n\n :param stat: bool\n :param verbose: bool\n :return: str\n " ]
Please provide a description of the function:def receive_fmf_metadata(name, path, object_list=False): output = {} fmf_tree = ExtendedTree(path) logger.debug("get FMF metadata for test (path:%s name=%s)", path, name) # ignore items with @ in names, to avoid using unreferenced items items = [x fo...
[ "\n search node identified by name fmfpath\n\n :param path: path to filesystem\n :param name: str - name as pattern to search - \"/name\" (prepended hierarchy item)\n :param object_list: bool, if true, return whole list of found items\n :return: Tree Object or list\n " ]
Please provide a description of the function:def check(target, ruleset, ruleset_file, debug, json, stat, skip, tag, verbose, checks_paths, target_type, timeout, pull, insecure): if ruleset and ruleset_file: raise click.BadOptionUsage( "Options '--ruleset' and '--file-ruleset' cann...
[ "\n Check the image/dockerfile (default).\n " ]
Please provide a description of the function:def list_checks(ruleset, ruleset_file, debug, json, skip, tag, verbose, checks_paths): if ruleset and ruleset_file: raise click.BadOptionUsage( "Options '--ruleset' and '--file-ruleset' cannot be used together.") try: if not debug: ...
[ "\n Print the checks.\n " ]
Please provide a description of the function:def list_rulesets(debug): try: rulesets = get_rulesets() max_len = max([len(r[0]) for r in rulesets]) for r in rulesets: click.echo('{0: <{1}} ({2})'.format(r[0], max_len, r[1])) except Exception as ex: logger.error("A...
[ "\n List available rulesets.\n " ]
Please provide a description of the function:def info(): installation_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) click.echo("colin {} {}".format(__version__, installation_path)) click.echo("colin-cli {}\n".format(os.path.realpath(__file__))) # click.echo(get_v...
[ "\n Show info about colin and its dependencies.\n " ]
Please provide a description of the function:def _print_results(results, stat=False, verbose=False): results.generate_pretty_output(stat=stat, verbose=verbose, output_function=click.secho)
[ "\n Prints the results to the stdout\n\n :type verbose: bool\n :param results: generator of results\n :param stat: if True print stat instead of full output\n " ]
Please provide a description of the function:def inspect_object(obj, refresh=True): if hasattr(obj, "inspect"): return obj.inspect(refresh=refresh) return obj.get_metadata(refresh=refresh)
[ "\n inspect provided object (container, image) and return raw dict with the metadata\n\n :param obj: instance of Container or an Image\n :param refresh: bool, refresh the metadata or return cached?\n :return: dict\n " ]
Please provide a description of the function:def get_instance(target_type, **kwargs): if target_type in TARGET_TYPES: cls = TARGET_TYPES[target_type] try: return cls(**kwargs) except Exception: logger.error("Please make sure that you p...
[ "\n :param target_type: string, either image, dockertar, ostree or dockerfile\n " ]
Please provide a description of the function:def labels(self): if self._labels is None: self._labels = self.instance.labels return self._labels
[ "\n Get list of labels from the target instance.\n\n :return: [str]\n " ]
Please provide a description of the function:def read_file(self, file_path): try: with open(self.cont_path(file_path)) as fd: return fd.read() except IOError as ex: logger.error("error while accessing file %s: %r", file_path, ex) raise ColinEx...
[ "\n read file specified via 'file_path' and return its content - raises an ConuException if\n there is an issue accessing the file\n :param file_path: str, path to the file to read\n :return: str (not bytes), content of the file\n " ]
Please provide a description of the function:def get_file(self, file_path, mode="r"): return open(self.cont_path(file_path), mode=mode)
[ "\n provide File object specified via 'file_path'\n :param file_path: str, path to the file\n :param mode: str, mode used when opening the file\n :return: File instance\n " ]
Please provide a description of the function:def file_is_present(self, file_path): real_path = self.cont_path(file_path) if not os.path.exists(real_path): return False if not os.path.isfile(real_path): raise IOError("%s is not a file" % file_path) return ...
[ "\n check if file 'file_path' is present, raises IOError if file_path\n is not a file\n :param file_path: str, path to the file\n :return: True if file exists, False if file does not exist\n " ]
Please provide a description of the function:def cont_path(self, path): if path.startswith("/"): path = path[1:] real_path = os.path.join(self.mount_point, path) logger.debug("path = %s", real_path) return real_path
[ "\n provide absolute path within the container\n\n :param path: path with container\n :return: str\n " ]
Please provide a description of the function:def mount_point(self): if self._mount_point is None: cmd_create = ["podman", "create", self.target_name, "some-cmd"] self._mounted_container_id = subprocess.check_output(cmd_create).decode().rstrip() cmd_mount = ["podman",...
[ " podman mount -- real filesystem " ]
Please provide a description of the function:def labels(self): if self._labels is None: cmd = ["skopeo", "inspect", self.skopeo_target] self._labels = json.loads(subprocess.check_output(cmd))["Labels"] return self._labels
[ "\n Provide labels without the need of dockerd. Instead skopeo is being used.\n\n :return: dict\n " ]
Please provide a description of the function:def layers_path(self): if self._layers_path is None: self._layers_path = os.path.join(self.tmpdir, "layers") return self._layers_path
[ " Directory with all the layers (docker save). " ]
Please provide a description of the function:def mount_point(self): if self._mount_point is None: self._mount_point = os.path.join(self.tmpdir, "checkout") os.makedirs(self._mount_point) self._checkout() return self._mount_point
[ " ostree checkout -- real filesystem " ]
Please provide a description of the function:def ostree_path(self): if self._ostree_path is None: self._ostree_path = os.path.join(self.tmpdir, "ostree-repo") subprocess.check_call(["ostree", "init", "--mode", "bare-user-only", "--repo", self._...
[ " ostree repository -- content " ]
Please provide a description of the function:def tmpdir(self): if self._tmpdir is None: self._tmpdir = mkdtemp(prefix="colin-", dir="/var/tmp") return self._tmpdir
[ " Temporary directory holding all the runtime data. " ]
Please provide a description of the function:def _checkout(self): cmd = ["atomic", "mount", "--storage", "ostree", self.ref_image_name, self.mount_point] # self.mount_point has to be created by us self._run_and_log(cmd, self.ostree_path, "Failed to mount select...
[ " check out the image filesystem on self.mount_point " ]
Please provide a description of the function:def _run_and_log(cmd, ostree_repo_path, error_msg, wd=None): logger.debug("running command %s", cmd) kwargs = { "stderr": subprocess.STDOUT, "env": os.environ.copy(), } if ostree_repo_path: # must n...
[ " run provided command and log all of its output; set path to ostree repo " ]
Please provide a description of the function:def __remove_append_items(self, whole=False): for node in self.climb(whole=whole): for key in sorted(node.data.keys()): if key.endswith('+'): del node.data[key]
[ "\n internal method, delete all append items (ends with +)\n :param whole: pass thru 'whole' param to climb\n :return: None\n " ]
Please provide a description of the function:def references(self, datatrees, whole=False): if not isinstance(datatrees, list): raise ValueError("datatrees argument has to be list of fmf trees") reference_nodes = self.prune(whole=whole, names=["@"]) for node in reference_node...
[ "\n Reference name resolver (eg. /a/b/c/d@.x.y or /a/b/c/@y will search data in .x.y or y nodes)\n there are used regular expressions (re.search) to match names\n it uses simple references schema, do not use references to another references,\n avoid usind / in reference because actual so...
Please provide a description of the function:def search(self, name): for node in self.climb(): if re.search(name, node.name): return node return None
[ " Search node with given name based on regexp, basic method (find) uses equality" ]
Please provide a description of the function:def login(self, email, password): params = { 'email': email, 'password': password } return self._get('login', params)
[ "Login to Todoist.\n\n :param email: The user's email address.\n :type email: str\n :param password: The user's password.\n :type password: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n\n >>> from pytodoist.api import Todoist...
Please provide a description of the function:def login_with_google(self, email, oauth2_token, **kwargs): params = { 'email': email, 'oauth2_token': oauth2_token } req_func = self._get if kwargs.get('auto_signup', 0) == 1: # POST if we're creating a user....
[ "Login to Todoist using Google's oauth2 authentication.\n\n :param email: The user's Google email address.\n :type email: str\n :param oauth2_token: The user's Google oauth2 token.\n :type oauth2_token: str\n :param auto_signup: If ``1`` register an account automatically.\n ...
Please provide a description of the function:def register(self, email, full_name, password, **kwargs): params = { 'email': email, 'full_name': full_name, 'password': password } return self._post('register', params, **kwargs)
[ "Register a new Todoist user.\n\n :param email: The user's email.\n :type email: str\n :param full_name: The user's full name.\n :type full_name: str\n :param password: The user's password.\n :type password: str\n :param lang: The user's language.\n :type lang...
Please provide a description of the function:def delete_user(self, api_token, password, **kwargs): params = { 'token': api_token, 'current_password': password } return self._post('delete_user', params, **kwargs)
[ "Delete a registered Todoist user's account.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param password: The user's password.\n :type password: str\n :param reason_for_delete: The reason for deletion.\n :type reason_for_delete: str\n :...
Please provide a description of the function:def sync(self, api_token, sync_token, resource_types='["all"]', **kwargs): params = { 'token': api_token, 'sync_token': sync_token, } req_func = self._post if 'commands' not in kwargs: # GET if we're not chang...
[ "Update and retrieve Todoist data.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param seq_no: The request sequence number. On initial request pass\n ``0``. On all others pass the last seq_no you received.\n :type seq_no: int\n :param seq_n...
Please provide a description of the function:def query(self, api_token, queries, **kwargs): params = { 'token': api_token, 'queries': queries } return self._get('query', params, **kwargs)
[ "Search all of a user's tasks using date, priority and label queries.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param queries: A JSON list of queries to search. See examples\n `here <https://todoist.com/Help/timeQuery>`_.\n :type queries: list...
Please provide a description of the function:def add_item(self, api_token, content, **kwargs): params = { 'token': api_token, 'content': content } return self._post('add_item', params, **kwargs)
[ "Add a task to a project.\n\n :param token: The user's login token.\n :type token: str\n :param content: The task description.\n :type content: str\n :param project_id: The project to add the task to. Default is ``Inbox``\n :type project_id: str\n :param date_string:...
Please provide a description of the function:def quick_add(self, api_token, text, **kwargs): params = { 'token': api_token, 'text': text } return self._post('quick/add', params, **kwargs)
[ "Add a task using the Todoist 'Quick Add Task' syntax.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param text: The text of the task that is parsed. A project\n name starts with the `#` character, a label starts with a `@`\n and an assignee s...
Please provide a description of the function:def get_all_completed_tasks(self, api_token, **kwargs): params = { 'token': api_token } return self._get('get_all_completed_items', params, **kwargs)
[ "Return a list of a user's completed tasks.\n\n .. warning:: Requires Todoist premium.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param project_id: Filter the tasks by project.\n :type project_id: str\n :param limit: The maximum number of ta...
Please provide a description of the function:def upload_file(self, api_token, file_path, **kwargs): params = { 'token': api_token, 'file_name': os.path.basename(file_path) } with open(file_path, 'rb') as f: files = {'file': f} return self....
[ "Upload a file suitable to be passed as a file_attachment.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param file_path: The path of the file to be uploaded.\n :type file_path: str\n :return: The HTTP response to the request.\n :rtype: :class:...
Please provide a description of the function:def get_productivity_stats(self, api_token, **kwargs): params = { 'token': api_token } return self._get('get_productivity_stats', params, **kwargs)
[ "Return a user's productivity stats.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :return: The HTTP response to the request.\n :rtype: :class:`requests.Response`\n " ]
Please provide a description of the function:def update_notification_settings(self, api_token, event, service, should_notify): params = { 'token': api_token, 'notification_type': event, 'service': service, 'dont_notify...
[ "Update a user's notification settings.\n\n :param api_token: The user's login api_token.\n :type api_token: str\n :param event: Update the notification settings of this event.\n :type event: str\n :param service: ``email`` or ``push``\n :type service: str\n :param s...
Please provide a description of the function:def get_redirect_link(self, api_token, **kwargs): params = { 'token': api_token } return self._get('get_redirect_link', params, **kwargs)
[ "Return the absolute URL to redirect or to open in\n a browser. The first time the link is used it logs in the user\n automatically and performs a redirect to a given page. Once used,\n the link keeps working as a plain redirect.\n\n :param api_token: The user's login api_token.\n ...
Please provide a description of the function:def _get(self, end_point, params=None, **kwargs): return self._request(requests.get, end_point, params, **kwargs)
[ "Send a HTTP GET request to a Todoist API end-point.\n\n :param end_point: The Todoist API end-point.\n :type end_point: str\n :param params: The required request parameters.\n :type params: dict\n :param kwargs: Any optional parameters.\n :type kwargs: dict\n :retur...
Please provide a description of the function:def _post(self, end_point, params=None, files=None, **kwargs): return self._request(requests.post, end_point, params, files, **kwargs)
[ "Send a HTTP POST request to a Todoist API end-point.\n\n :param end_point: The Todoist API end-point.\n :type end_point: str\n :param params: The required request parameters.\n :type params: dict\n :param files: Any files that are being sent as multipart/form-data.\n :type...
Please provide a description of the function:def _request(self, req_func, end_point, params=None, files=None, **kwargs): url = self.URL + end_point if params and kwargs: params.update(kwargs) return req_func(url, params=params, files=files)
[ "Send a HTTP request to a Todoist API end-point.\n\n :param req_func: The request function to use e.g. get or post.\n :type req_func: A request function from the :class:`requests` module.\n :param end_point: The Todoist API end-point.\n :type end_point: str\n :param params: The re...
Please provide a description of the function:def login(email, password): user = _login(API.login, email, password) user.password = password return user
[ "Login to Todoist.\n\n :param email: A Todoist user's email address.\n :type email: str\n :param password: A Todoist user's password.\n :type password: str\n :return: The Todoist user.\n :rtype: :class:`pytodoist.todoist.User`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login(...
Please provide a description of the function:def login_with_api_token(api_token): response = API.sync(api_token, '*', '["user"]') _fail_if_contains_errors(response) user_json = response.json()['user'] # Required as sync doesn't return the api_token. user_json['api_token'] = user_json['token'] ...
[ "Login to Todoist using a user's api token.\n\n .. note:: It is up to you to obtain the api token.\n\n :param api_token: A Todoist user's api token.\n :type api_token: str\n :return: The Todoist user.\n :rtype: :class:`pytodoist.todoist.User`\n\n >>> from pytodoist import todoist\n >>> api_toke...
Please provide a description of the function:def _login(login_func, *args): response = login_func(*args) _fail_if_contains_errors(response) user_json = response.json() return User(user_json)
[ "A helper function for logging in. It's purpose is to avoid duplicate\n code in the login functions.\n " ]
Please provide a description of the function:def register(full_name, email, password, lang=None, timezone=None): response = API.register(email, full_name, password, lang=lang, timezone=timezone) _fail_if_contains_errors(response) user_json = response.json() user = User(u...
[ "Register a new Todoist account.\n\n :param full_name: The user's full name.\n :type full_name: str\n :param email: The user's email address.\n :type email: str\n :param password: The user's password.\n :type password: str\n :param lang: The user's language.\n :type lang: str\n :param tim...
Please provide a description of the function:def register_with_google(full_name, email, oauth2_token, lang=None, timezone=None): response = API.login_with_google(email, oauth2_token, auto_signup=1, full_name=full_name, lang=lang, ...
[ "Register a new Todoist account by linking a Google account.\n\n :param full_name: The user's full name.\n :type full_name: str\n :param email: The user's email address.\n :type email: str\n :param oauth2_token: The oauth2 token associated with the email.\n :type oauth2_token: str\n :param lang...
Please provide a description of the function:def _fail_if_contains_errors(response, sync_uuid=None): if response.status_code != _HTTP_OK: raise RequestError(response) response_json = response.json() if sync_uuid and 'sync_status' in response_json: status = response_json['sync_status'] ...
[ "Raise a RequestError Exception if a given response\n does not denote a successful request.\n " ]
Please provide a description of the function:def _perform_command(user, command_type, command_args): command_uuid = _gen_uuid() command = { 'type': command_type, 'args': command_args, 'uuid': command_uuid, 'temp_id': _gen_uuid() } commands = json.dumps([command]) ...
[ "Perform an operation on Todoist using the API sync end-point." ]
Please provide a description of the function:def update(self): args = {attr: getattr(self, attr) for attr in self.to_update} _perform_command(self, 'user_update', args)
[ "Update the user's details on Todoist.\n\n This method must be called to register any local attribute changes\n with Todoist.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> user.full_name = 'John Smith'\n >>> # At th...
Please provide a description of the function:def sync(self, resource_types='["all"]'): response = API.sync(self.api_token, '*', resource_types) _fail_if_contains_errors(response) response_json = response.json() self.sync_token = response_json['sync_token'] if 'projects' ...
[ "Synchronize the user's data with the Todoist server.\n\n This function will pull data from the Todoist server and update the\n state of the user object such that they match. It does not *push* data\n to Todoist. If you want to do that use\n :func:`pytodoist.todoist.User.update`.\n\n ...
Please provide a description of the function:def _sync_projects(self, projects_json): for project_json in projects_json: project_id = project_json['id'] self.projects[project_id] = Project(project_json, self)
[ "\"Populate the user's projects from a JSON encoded list." ]
Please provide a description of the function:def _sync_tasks(self, tasks_json): for task_json in tasks_json: task_id = task_json['id'] project_id = task_json['project_id'] if project_id not in self.projects: # ignore orphan tasks conti...
[ "\"Populate the user's tasks from a JSON encoded list." ]
Please provide a description of the function:def _sync_notes(self, notes_json): for note_json in notes_json: note_id = note_json['id'] task_id = note_json['item_id'] if task_id not in self.tasks: # ignore orphan notes continue ...
[ "\"Populate the user's notes from a JSON encoded list." ]
Please provide a description of the function:def _sync_labels(self, labels_json): for label_json in labels_json: label_id = label_json['id'] self.labels[label_id] = Label(label_json, self)
[ "\"Populate the user's labels from a JSON encoded list." ]
Please provide a description of the function:def _sync_filters(self, filters_json): for filter_json in filters_json: filter_id = filter_json['id'] self.filters[filter_id] = Filter(filter_json, self)
[ "\"Populate the user's filters from a JSON encoded list." ]
Please provide a description of the function:def _sync_reminders(self, reminders_json): for reminder_json in reminders_json: reminder_id = reminder_json['id'] task_id = reminder_json['item_id'] if task_id not in self.tasks: # ignore orphan reminders ...
[ "\"Populate the user's reminders from a JSON encoded list." ]
Please provide a description of the function:def quick_add(self, text, note=None, reminder=None): response = API.quick_add(self.api_token, text, note=note, reminder=reminder) _fail_if_contains_errors(response) task_json = response.json() return T...
[ "Add a task using the 'Quick Add Task' syntax.\n\n :param text: The text of the task that is parsed. A project\n name starts with the `#` character, a label starts with a `@`\n and an assignee starts with a `+`.\n :type text: str\n :param note: The content of the note.\n ...
Please provide a description of the function:def add_project(self, name, color=None, indent=None, order=None): args = { 'name': name, 'color': color, 'indent': indent, 'order': order } args = {k: args[k] for k in args if args[k] is not Non...
[ "Add a project to the user's account.\n\n :param name: The project name.\n :type name: str\n :return: The project that was added.\n :rtype: :class:`pytodoist.todoist.Project`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\...
Please provide a description of the function:def get_project(self, project_name): for project in self.get_projects(): if project.name == project_name: return project
[ "Return the project with a given name.\n\n :param project_name: The name to search for.\n :type project_name: str\n :return: The project that has the name ``project_name`` or ``None``\n if no project is found.\n :rtype: :class:`pytodoist.todoist.Project`\n\n >>> from py...
Please provide a description of the function:def get_uncompleted_tasks(self): tasks = (p.get_uncompleted_tasks() for p in self.get_projects()) return list(itertools.chain.from_iterable(tasks))
[ "Return all of a user's uncompleted tasks.\n\n .. warning:: Requires Todoist premium.\n\n :return: A list of uncompleted tasks.\n :rtype: list of :class:`pytodoist.todoist.Task`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n ...
Please provide a description of the function:def search_tasks(self, *queries): queries = json.dumps(queries) response = API.query(self.api_token, queries) _fail_if_contains_errors(response) query_results = response.json() tasks = [] for result in query_results: ...
[ "Return a list of tasks that match some search criteria.\n\n .. note:: Example queries can be found\n `here <https://todoist.com/Help/timeQuery>`_.\n\n .. note:: A standard set of queries are available\n in the :class:`pytodoist.todoist.Query` class.\n\n :param queries: Re...
Please provide a description of the function:def add_label(self, name, color=None): args = { 'name': name, 'color': color } _perform_command(self, 'label_register', args) return self.get_label(name)
[ "Create a new label.\n\n .. warning:: Requires Todoist premium.\n\n :param name: The name of the label.\n :type name: str\n :param color: The color of the label.\n :type color: str\n :return: The newly created label.\n :rtype: :class:`pytodoist.todoist.Label`\n\n ...
Please provide a description of the function:def get_label(self, label_name): for label in self.get_labels(): if label.name == label_name: return label
[ "Return the user's label that has a given name.\n\n :param label_name: The name to search for.\n :type label_name: str\n :return: A label that has a matching name or ``None`` if not found.\n :rtype: :class:`pytodoist.todoist.Label`\n\n >>> from pytodoist import todoist\n >>...
Please provide a description of the function:def add_filter(self, name, query, color=None, item_order=None): args = { 'name': name, 'query': query, 'color': color, 'item_order': item_order } _perform_command(self, 'filter_add', args) ...
[ "Create a new filter.\n\n .. warning:: Requires Todoist premium.\n\n :param name: The name of the filter.\n :param query: The query to search for.\n :param color: The color of the filter.\n :param item_order: The filter's order in the filter list.\n :return: The newly creat...
Please provide a description of the function:def get_filter(self, name): for flter in self.get_filters(): if flter.name == name: return flter
[ "Return the filter that has the given filter name.\n\n :param name: The name to search for.\n :return: The filter with the given name.\n :rtype: :class:`pytodoist.todoist.Filter`\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n ...
Please provide a description of the function:def _update_notification_settings(self, event, service, should_notify): response = API.update_notification_settings(self.api_token, event, service, should_notify) ...
[ "Update the settings of a an events notifications.\n\n :param event: Update the notification settings of this event.\n :type event: str\n :param service: The notification service to update.\n :type service: str\n :param should_notify: Notify if this is ``1``.\n :type should...
Please provide a description of the function:def get_productivity_stats(self): response = API.get_productivity_stats(self.api_token) _fail_if_contains_errors(response) return response.json()
[ "Return the user's productivity stats.\n\n :return: A JSON-encoded representation of the user's productivity\n stats.\n :rtype: A JSON-encoded object.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> stats = user.g...
Please provide a description of the function:def get_redirect_link(self): response = API.get_redirect_link(self.api_token) _fail_if_contains_errors(response) link_json = response.json() return link_json['link']
[ "Return the absolute URL to redirect or to open in\n a browser. The first time the link is used it logs in the user\n automatically and performs a redirect to a given page. Once used,\n the link keeps working as a plain redirect.\n\n :return: The user's redirect link.\n :rtype: st...
Please provide a description of the function:def delete(self, reason=None): response = API.delete_user(self.api_token, self.password, reason=reason, in_background=0) _fail_if_contains_errors(response)
[ "Delete the user's account from Todoist.\n\n .. warning:: You cannot recover the user after deletion!\n\n :param reason: The reason for deletion.\n :type reason: str\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> use...
Please provide a description of the function:def archive(self): args = {'id': self.id} _perform_command(self.owner, 'project_archive', args) self.is_archived = '1'
[ "Archive the project.\n\n >>> from pytodoist import todoist\n >>> user = todoist.login('john.doe@gmail.com', 'password')\n >>> project = user.get_project('PyTodoist')\n >>> project.archive()\n " ]
Please provide a description of the function:def add_task(self, content, date=None, priority=None): response = API.add_item(self.owner.token, content, project_id=self.id, date_string=date, priority=priority) _fail_if_contains_errors(response) task_json = ...
[ "Add a task to the project\n\n :param content: The task description.\n :type content: str\n :param date: The task deadline.\n :type date: str\n :param priority: The priority of the task.\n :type priority: int\n :return: The added task.\n :rtype: :class:`pytodo...