INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Executes all macros and returns result string Executes macros only when not in safe_mode
def execute_macros(self): """Executes all macros and returns result string Executes macros only when not in safe_mode """ if self.safe_mode: return '', "Safe mode activated. Code not executed." # Windows exec does not like Windows newline self.macros = sel...
Generator that yields sorted keys starting with startkey Parameters ---------- keys: Iterable of tuple/list \tKey sequence that is sorted startkey: Tuple/list \tFirst key to be yielded reverse: Bool \tSort direction reversed if True
def _sorted_keys(self, keys, startkey, reverse=False): """Generator that yields sorted keys starting with startkey Parameters ---------- keys: Iterable of tuple/list \tKey sequence that is sorted startkey: Tuple/list \tFirst key to be yielded reverse: Bo...
Returns position of findstring in datastring or None if not found. Flags is a list of strings. Supported strings are: * "MATCH_CASE": The case has to match for valid find * "WHOLE_WORD": The word has to be surrounded by whitespace characters if in the middle of the str...
def string_match(self, datastring, findstring, flags=None): """ Returns position of findstring in datastring or None if not found. Flags is a list of strings. Supported strings are: * "MATCH_CASE": The case has to match for valid find * "WHOLE_WORD": The word has to be surround...
Returns a tuple with the position of the next match of find_string Returns None if string not found. Parameters: ----------- startkey: Start position of search find_string:String to be searched for flags: List of strings, out of ["UP" xor "DOW...
def findnextmatch(self, startkey, find_string, flags, search_result=True): """ Returns a tuple with the position of the next match of find_string Returns None if string not found. Parameters: ----------- startkey: Start position of search find_string:String to be sear...
Returns True if Value in digits, False otherwise
def Validate(self, win): """Returns True if Value in digits, False otherwise""" val = self.GetWindow().GetValue() for x in val: if x not in string.digits: return False return True
Eats event if key not in digits
def OnChar(self, event): """Eats event if key not in digits""" key = event.GetKeyCode() if key < wx.WXK_SPACE or key == wx.WXK_DELETE or key > 255 or \ chr(key) in string.digits: event.Skip()
Draws the text and the combobox icon
def Draw(self, grid, attr, dc, rect, row, col, is_selected): """Draws the text and the combobox icon""" render = wx.RendererNative.Get() # clear the background dc.SetBackgroundMode(wx.SOLID) if is_selected: dc.SetBrush(wx.Brush(wx.BLUE, wx.SOLID)) dc.Se...
Creates the parameter entry widgets and binds them to methods
def _setup_param_widgets(self): """Creates the parameter entry widgets and binds them to methods""" for parameter in self.csv_params: pname, ptype, plabel, phelp = parameter label = wx.StaticText(self.parent, -1, plabel) widget = self.type2widget[ptype](self.parent)...
Sizer hell, returns a sizer that contains all widgets
def _do_layout(self): """Sizer hell, returns a sizer that contains all widgets""" sizer_csvoptions = wx.FlexGridSizer(5, 4, 5, 5) # Adding parameter widgets to sizer_csvoptions leftpos = wx.LEFT | wx.ADJUST_MINSIZE rightpos = wx.RIGHT | wx.EXPAND current_label_margin =...
Sets the widget settings to those of the chosen dialect
def _update_settings(self, dialect): """Sets the widget settings to those of the chosen dialect""" # the first parameter is the dialect itself --> ignore for parameter in self.csv_params[2:]: pname, ptype, plabel, phelp = parameter widget = self._widget_from_p(pname, pt...
Returns a widget from its ptype and pname
def _widget_from_p(self, pname, ptype): """Returns a widget from its ptype and pname""" widget_name = self.type2widget[ptype].__name__.lower() widget_name = "_".join([widget_name, pname]) return getattr(self, widget_name)
Updates all param widgets confirming to the selcted dialect
def OnDialectChoice(self, event): """Updates all param widgets confirming to the selcted dialect""" dialect_name = event.GetString() value = list(self.choices['dialects']).index(dialect_name) if dialect_name == 'sniffer': if self.csvfilepath is None: event.S...
Update the dialect widget to 'user
def OnWidget(self, event): """Update the dialect widget to 'user'""" self.choice_dialects.SetValue(len(self.choices['dialects']) - 1) event.Skip()
Returns a new dialect that implements the current selection
def get_dialect(self): """Returns a new dialect that implements the current selection""" parameters = {} for parameter in self.csv_params[2:]: pname, ptype, plabel, phelp = parameter widget = self._widget_from_p(pname, ptype) if ptype is types.StringType o...
Reduces clicks to enter an edit control
def OnMouse(self, event): """Reduces clicks to enter an edit control""" self.SetGridCursor(event.Row, event.Col) self.EnableCellEditControl(True) event.Skip()
Used to capture Editor close events
def OnGridEditorCreated(self, event): """Used to capture Editor close events""" editor = event.GetControl() editor.Bind(wx.EVT_KILL_FOCUS, self.OnGridEditorClosed) event.Skip()
Event handler for end of output type choice
def OnGridEditorClosed(self, event): """Event handler for end of output type choice""" try: dialect, self.has_header = \ self.parent.csvwidgets.get_dialect() except TypeError: event.Skip() return 0 self.fill_cells(dialect, self.has_he...
Fills the grid for preview of csv data Parameters ---------- dialect: csv,dialect \tDialect used for csv reader choices: Bool \tCreate and show choices
def fill_cells(self, dialect, has_header, choices=True): """Fills the grid for preview of csv data Parameters ---------- dialect: csv,dialect \tDialect used for csv reader choices: Bool \tCreate and show choices """ # Get columns from csv ...
Returns a list of the type choices
def get_digest_keys(self): """Returns a list of the type choices""" digest_keys = [] for col in xrange(self.GetNumberCols()): digest_key = self.GetCellValue(self.has_header, col) if digest_key == "": digest_key = self.digest_types.keys()[0] di...
Fills the grid for preview of csv data Parameters ---------- data: 2-dim array of strings \tData that is written to preview TextCtrl dialect: csv,dialect \tDialect used for csv reader
def fill(self, data, dialect): """Fills the grid for preview of csv data Parameters ---------- data: 2-dim array of strings \tData that is written to preview TextCtrl dialect: csv,dialect \tDialect used for csv reader """ csvfile = cStringIO.Str...
Sets dialog title and size limitations of the widgets
def _set_properties(self): """Sets dialog title and size limitations of the widgets""" title = _("CSV Import: {filepath}").format(filepath=self.csvfilename) self.SetTitle(title) self.SetSize((600, 600)) for button in [self.button_cancel, self.button_ok]: button.SetM...
Sets dialog title and size limitations of the widgets
def _set_properties(self): """Sets dialog title and size limitations of the widgets""" self.SetTitle("CSV Export") self.SetSize((600, 600)) for button in [self.button_cancel, self.button_apply, self.button_ok]: button.SetMinSize((80, 28))
Set sizers
def _do_layout(self): """Set sizers""" sizer_dialog = wx.FlexGridSizer(3, 1, 0, 0) # Sub sizers sizer_buttons = wx.FlexGridSizer(1, 3, 5, 5) # Adding buttons to sizer_buttons for button in [self.button_cancel, self.button_apply, self.button_ok]: sizer_butto...
Updates the preview_textctrl
def OnButtonApply(self, event): """Updates the preview_textctrl""" try: dialect, self.has_header = self.csvwidgets.get_dialect() except TypeError: event.Skip() return 0 self.preview_textctrl.fill(data=self.data, dialect=dialect) event.Skip()
Layout sizers
def _do_layout(self): """Layout sizers""" dialog_main_sizer = wx.BoxSizer(wx.HORIZONTAL) upper_sizer = wx.BoxSizer(wx.HORIZONTAL) lower_sizer = wx.FlexGridSizer(2, 1, 5, 0) lower_sizer.AddGrowableRow(0) lower_sizer.AddGrowableCol(0) button_sizer = wx.BoxSizer(wx....
Setup title, size and tooltips
def _set_properties(self): """Setup title, size and tooltips""" self.codetext_ctrl.SetToolTipString(_("Enter python code here.")) self.apply_button.SetToolTipString(_("Apply changes to current macro")) self.splitter.SetBackgroundStyle(wx.BG_STYLE_COLOUR) self.result_ctrl.SetMinS...
Event handler for Apply button
def OnApply(self, event): """Event handler for Apply button""" # See if we have valid python try: ast.parse(self.macros) except: # Grab the traceback and print it for the user s = StringIO() e = exc_info() # usr_tb will more th...
Update event result following execution by main window
def update_result_ctrl(self, event): """Update event result following execution by main window""" # Check to see if macro window still exists if not self: return printLen = 0 self.result_ctrl.SetValue('') if hasattr(event, 'msg'): # Output of scr...
Layout sizers
def _do_layout(self): """Layout sizers""" label_style = wx.LEFT | wx.ALIGN_CENTER_VERTICAL button_style = wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | \ wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE grid_sizer_1 = wx.GridSizer(4, 2, 3, 3) grid_sizer_1.Add(self.R...
Converts valuestring to int and assigns result to self.dim If there is an error (such as an empty valuestring) or if the value is < 1, the value 1 is assigned to self.dim Parameters ---------- dimension: int \tDimension that is to be updated. Must be in [1:4] v...
def _ondim(self, dimension, valuestring): """Converts valuestring to int and assigns result to self.dim If there is an error (such as an empty valuestring) or if the value is < 1, the value 1 is assigned to self.dim Parameters ---------- dimension: int \tDimens...
Posts a command event that makes the grid show the entered cell
def OnOk(self, event): """Posts a command event that makes the grid show the entered cell""" # Get key values from textctrls key_strings = [self.row_textctrl.GetValue(), self.col_textctrl.GetValue(), self.tab_textctrl.GetValue()] key = [] ...
Setup title and label
def _set_properties(self): """Setup title and label""" self.SetTitle(_("About pyspread")) label = _("pyspread {version}\nCopyright Martin Manns") label = label.format(version=VERSION) self.about_label.SetLabel(label)
Layout sizers
def _do_layout(self): """Layout sizers""" sizer_v = wx.BoxSizer(wx.VERTICAL) sizer_h = wx.BoxSizer(wx.HORIZONTAL) style = wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL sizer_h.Add(self.logo_pyspread, 0, style, 10) sizer_h.Add(self.about_label, 0, style,...
Returns maximum dimensionality over which obj is iterable <= 2
def get_max_dim(self, obj): """Returns maximum dimensionality over which obj is iterable <= 2""" try: iter(obj) except TypeError: return 0 try: for o in obj: iter(o) break except TypeError: return...
Runs alter operation.
def alter(self, operation, timeout=None, metadata=None, credentials=None): """Runs alter operation.""" return self.stub.Alter(operation, timeout=timeout, metadata=metadata, credentials=credentials)
Runs query operation.
def query(self, req, timeout=None, metadata=None, credentials=None): """Runs query operation.""" return self.stub.Query(req, timeout=timeout, metadata=metadata, credentials=credentials)
Runs mutate operation.
def mutate(self, mutation, timeout=None, metadata=None, credentials=None): """Runs mutate operation.""" return self.stub.Mutate(mutation, timeout=timeout, metadata=metadata, credentials=credentials)
Runs commit or abort operation.
def commit_or_abort(self, ctx, timeout=None, metadata=None, credentials=None): """Runs commit or abort operation.""" return self.stub.CommitOrAbort(ctx, timeout=timeout, metadata=metadata, credentials=credentials)
Returns the version of the Dgraph instance.
def check_version(self, check, timeout=None, metadata=None, credentials=None): """Returns the version of the Dgraph instance.""" return self.stub.CheckVersion(check, timeout=timeout, metadata=metadata, cred...
Runs a modification via this client.
def alter(self, operation, timeout=None, metadata=None, credentials=None): """Runs a modification via this client.""" new_metadata = self.add_login_metadata(metadata) try: return self.any_client().alter(operation, timeout=timeout, metadata=...
Creates a transaction.
def txn(self, read_only=False, best_effort=False): """Creates a transaction.""" return txn.Txn(self, read_only=read_only, best_effort=best_effort)
Adds a query operation to the transaction.
def query(self, query, variables=None, timeout=None, metadata=None, credentials=None): """Adds a query operation to the transaction.""" new_metadata = self._dg.add_login_metadata(metadata) req = self._common_query(query, variables=variables) try: res = self._dc....
Adds a mutate operation to the transaction.
def mutate(self, mutation=None, set_obj=None, del_obj=None, set_nquads=None, del_nquads=None, commit_now=None, ignore_index_conflict=None, timeout=None, metadata=None, credentials=None): """Adds a mutate operation to the transaction.""" mutation = self._common_mutate( ...
Commits the transaction.
def commit(self, timeout=None, metadata=None, credentials=None): """Commits the transaction.""" if not self._common_commit(): return new_metadata = self._dg.add_login_metadata(metadata) try: self._dc.commit_or_abort(self._ctx, timeout=timeout, ...
Discards the transaction.
def discard(self, timeout=None, metadata=None, credentials=None): """Discards the transaction.""" if not self._common_discard(): return new_metadata = self._dg.add_login_metadata(metadata) try: self._dc.commit_or_abort(self._ctx, timeout=timeout, ...
Merges context from this instance with src.
def merge_context(self, src=None): """Merges context from this instance with src.""" if src is None: # This condition will be true only if the server doesn't return a # txn context after a query or mutation. return if self._ctx.start_ts == 0: self...
Returns the token generator class based on the configuration in DJANGO_REST_PASSWORDRESET_TOKEN_CONFIG.CLASS and DJANGO_REST_PASSWORDRESET_TOKEN_CONFIG.OPTIONS :return:
def get_token_generator(): """ Returns the token generator class based on the configuration in DJANGO_REST_PASSWORDRESET_TOKEN_CONFIG.CLASS and DJANGO_REST_PASSWORDRESET_TOKEN_CONFIG.OPTIONS :return: """ # by default, we are using the String Token Generator token_class = RandomStringTokenGen...
generates a pseudo random code using os.urandom and binascii.hexlify
def generate_token(self, *args, **kwargs): """ generates a pseudo random code using os.urandom and binascii.hexlify """ # determine the length based on min_length and max_length length = random.randint(self.min_length, self.max_length) # generate the token using os.urandom and hexlify ...
Try to emit whatever text is in the node.
def get_text(self, node): """Try to emit whatever text is in the node.""" try: return node.children[0].content or "" except (AttributeError, IndexError): return node.content or ""
Emit all the children of a node.
def emit_children(self, node): """Emit all the children of a node.""" return "".join([self.emit_node(child) for child in node.children])
Emit a single node.
def emit_node(self, node): """Emit a single node.""" emit = getattr(self, "%s_emit" % node.kind, self.default_emit) return emit(node)
Currently only supports markdown
def ajax_preview(request, **kwargs): """ Currently only supports markdown """ data = { "html": render_to_string("pinax/blog/_preview.html", { "content": parse(request.POST.get("markup")) }) } return JsonResponse(data)
Set system lock for the semaphore. Sets a system lock that will expire in timeout seconds. This overrides all other locks. Existing locks cannot be renewed and no new locks will be permitted until the system lock expires. Arguments: redis: Redis client n...
def set_system_lock(cls, redis, name, timeout): """ Set system lock for the semaphore. Sets a system lock that will expire in timeout seconds. This overrides all other locks. Existing locks cannot be renewed and no new locks will be permitted until the system lock expire...
Obtain a semaphore lock. Returns: Tuple that contains True/False if the lock was acquired and number of locks in semaphore.
def acquire(self): """ Obtain a semaphore lock. Returns: Tuple that contains True/False if the lock was acquired and number of locks in semaphore. """ acquired, locks = self._semaphore(keys=[self.name], args=[self.lock_...
Use Redis to hold a shared, distributed lock named ``name``. Returns True once the lock is acquired. If ``blocking`` is False, always return immediately. If the lock was acquired, return True, otherwise return False.
def acquire(self, blocking=True): """ Use Redis to hold a shared, distributed lock named ``name``. Returns True once the lock is acquired. If ``blocking`` is False, always return immediately. If the lock was acquired, return True, otherwise return False. """ slee...
Releases the already acquired lock
def release(self): "Releases the already acquired lock" if self.acquired_until is None: raise ValueError("Cannot release an unlocked lock") existing = float(self.redis.get(self.name) or 1) # if the lock time is in the future, delete the lock if existing >= self.acquir...
Sets a new timeout for an already acquired lock. ``new_timeout`` can be specified as an integer or a float, both representing the number of seconds.
def renew(self, new_timeout): """ Sets a new timeout for an already acquired lock. ``new_timeout`` can be specified as an integer or a float, both representing the number of seconds. """ if self.local.token is None: raise LockError("Cannot extend an unlocked ...
Function decorator that defines the behavior of the function when it is used as a task. To use the default behavior, tasks don't need to be decorated. See README.rst for an explanation of the options.
def task(self, _fn=None, queue=None, hard_timeout=None, unique=None, lock=None, lock_key=None, retry=None, retry_on=None, retry_method=None, schedule=None, batch=False, max_queue_size=None): """ Function decorator that defines the behavior of the function when it i...
Main worker entry point method. The arguments are explained in the module-level run_worker() method's click options.
def run_worker(self, queues=None, module=None, exclude_queues=None, max_workers_per_queue=None, store_tracebacks=None): """ Main worker entry point method. The arguments are explained in the module-level run_worker() method's click options. """ try: ...
Queues a task. See README.rst for an explanation of the options.
def delay(self, func, args=None, kwargs=None, queue=None, hard_timeout=None, unique=None, lock=None, lock_key=None, when=None, retry=None, retry_on=None, retry_method=None, max_queue_size=None): """ Queues a task. See README.rst for an explanation of the options...
Get the queue's number of tasks in each state. Returns dict with queue size for the QUEUED, SCHEDULED, and ACTIVE states. Does not include size of error queue.
def get_queue_sizes(self, queue): """ Get the queue's number of tasks in each state. Returns dict with queue size for the QUEUED, SCHEDULED, and ACTIVE states. Does not include size of error queue. """ states = [QUEUED, SCHEDULED, ACTIVE] pipeline = self.connect...
Get system lock timeout Returns time system lock expires or None if lock does not exist
def get_queue_system_lock(self, queue): """ Get system lock timeout Returns time system lock expires or None if lock does not exist """ key = self._key(LOCK_REDIS_KEY, queue) return Semaphore.get_system_lock(self.connection, key)
Set system lock on a queue. Max workers for this queue must be used for this to have any effect. This will keep workers from processing tasks for this queue until the timeout has expired. Active tasks will continue processing their current task. timeout is number of seconds to...
def set_queue_system_lock(self, queue, timeout): """ Set system lock on a queue. Max workers for this queue must be used for this to have any effect. This will keep workers from processing tasks for this queue until the timeout has expired. Active tasks will continue processing...
Returns a dict with stats about all the queues. The keys are the queue names, the values are dicts representing how many tasks are in a given status ("queued", "active", "error" or "scheduled"). Example return value: { "default": { "queued": 1, "error": 2 } }
def get_queue_stats(self): """ Returns a dict with stats about all the queues. The keys are the queue names, the values are dicts representing how many tasks are in a given status ("queued", "active", "error" or "scheduled"). Example return value: { "default": { "queued"...
Sets up signal handlers for safely stopping the worker.
def _install_signal_handlers(self): """ Sets up signal handlers for safely stopping the worker. """ def request_stop(signum, frame): self._stop_requested = True self.log.info('stop requested, waiting for task to finish') signal.signal(signal.SIGINT, reques...
Restores default signal handlers.
def _uninstall_signal_handlers(self): """ Restores default signal handlers. """ signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGTERM, signal.SIG_DFL)
Applies the queue filter to the given list of queues and returns the queues that match. Note that a queue name matches any subqueues starting with the name, followed by a date. For example, "foo" will match both "foo" and "foo.bar".
def _filter_queues(self, queues): """ Applies the queue filter to the given list of queues and returns the queues that match. Note that a queue name matches any subqueues starting with the name, followed by a date. For example, "foo" will match both "foo" and "foo.bar". "...
Helper method that takes due tasks from the SCHEDULED queue and puts them in the QUEUED queue for execution. This should be called periodically.
def _worker_queue_scheduled_tasks(self): """ Helper method that takes due tasks from the SCHEDULED queue and puts them in the QUEUED queue for execution. This should be called periodically. """ queues = set(self._filter_queues(self.connection.smembers( sel...
Check activity channel and wait as necessary. This method is also used to slow down the main processing loop to reduce the effects of rapidly sending Redis commands. This method will exit for any of these conditions: 1. _did_work is True, suggests there could be more work pending ...
def _wait_for_new_tasks(self, timeout=0, batch_timeout=0): """ Check activity channel and wait as necessary. This method is also used to slow down the main processing loop to reduce the effects of rapidly sending Redis commands. This method will exit for any of these conditions...
Helper method that takes expired tasks (where we didn't get a heartbeat until we reached a timeout) and puts them back into the QUEUED queue for re-execution if they're idempotent, i.e. retriable on JobTimeoutException. Otherwise, tasks are moved to the ERROR queue and an exception is lo...
def _worker_queue_expired_tasks(self): """ Helper method that takes expired tasks (where we didn't get a heartbeat until we reached a timeout) and puts them back into the QUEUED queue for re-execution if they're idempotent, i.e. retriable on JobTimeoutException. Otherwise, tasks ...
Executes the tasks in the forked process. Multiple tasks can be passed for batch processing. However, they must all use the same function and will share the execution entry.
def _execute_forked(self, tasks, log): """ Executes the tasks in the forked process. Multiple tasks can be passed for batch processing. However, they must all use the same function and will share the execution entry. """ success = False execution = {} as...
Get queue batch size.
def _get_queue_batch_size(self, queue): """Get queue batch size.""" # Fetch one item unless this is a batch queue. # XXX: It would be more efficient to loop in reverse order and break. batch_queues = self.config['BATCH_QUEUES'] batch_size = 1 for part in dotted_parts(que...
Get queue lock for max worker queues. For max worker queues it returns a Lock if acquired and whether it failed to acquire the lock.
def _get_queue_lock(self, queue, log): """Get queue lock for max worker queues. For max worker queues it returns a Lock if acquired and whether it failed to acquire the lock. """ max_workers = self.max_workers_per_queue # Check if this is single worker queue for...
Updates the heartbeat for the given task IDs to prevent them from timing out and being requeued.
def _heartbeat(self, queue, task_ids): """ Updates the heartbeat for the given task IDs to prevent them from timing out and being requeued. """ now = time.time() self.connection.zadd(self._key(ACTIVE, queue), **{task_id: now for task_id in tas...
Executes the given tasks. Returns a boolean indicating whether the tasks were executed successfully.
def _execute(self, queue, tasks, log, locks, queue_lock, all_task_ids): """ Executes the given tasks. Returns a boolean indicating whether the tasks were executed successfully. """ # The tasks must use the same function. assert len(tasks) task_func = tasks[0].ser...
Process a queue message from activity channel.
def _process_queue_message(self, message_queue, new_queue_found, batch_exit, start_time, timeout, batch_timeout): """Process a queue message from activity channel.""" for queue in self._filter_queues([message_queue]): if queue not in self._queue_set: ...
Process tasks in queue.
def _process_queue_tasks(self, queue, queue_lock, task_ids, now, log): """Process tasks in queue.""" processed_count = 0 # Get all tasks serialized_tasks = self.connection.mget([ self._key('task', task_id) for task_id in task_ids ]) # Parse tasks ta...
Internal method to process a task batch from the given queue. Args: queue: Queue name to be processed Returns: Task IDs: List of tasks that were processed (even if there was an error so that client code can assume the queue is empty ...
def _process_from_queue(self, queue): """ Internal method to process a task batch from the given queue. Args: queue: Queue name to be processed Returns: Task IDs: List of tasks that were processed (even if there was an error so that cli...
Executes the given tasks in the queue. Updates the heartbeat for task IDs passed in all_task_ids. This internal method is only meant to be called from within _process_from_queue.
def _execute_task_group(self, queue, tasks, all_task_ids, queue_lock): """ Executes the given tasks in the queue. Updates the heartbeat for task IDs passed in all_task_ids. This internal method is only meant to be called from within _process_from_queue. """ log = self.log...
After a task is executed, this method is called and ensures that the task gets properly removed from the ACTIVE queue and, in case of an error, retried or marked as failed.
def _finish_task_processing(self, queue, task, success): """ After a task is executed, this method is called and ensures that the task gets properly removed from the ACTIVE queue and, in case of an error, retried or marked as failed. """ log = self.log.bind(queue=queue, t...
Performs one worker run: * Processes a set of messages from each queue and removes any empty queues from the working set. * Move any expired items from the active queue to the queued queue. * Move any scheduled items from the scheduled queue to the queued queue.
def _worker_run(self): """ Performs one worker run: * Processes a set of messages from each queue and removes any empty queues from the working set. * Move any expired items from the active queue to the queued queue. * Move any scheduled items from the scheduled queue t...
Main loop of the worker. Use once=True to execute any queued tasks and then exit. Use force_once=True with once=True to always exit after one processing loop even if tasks remain queued.
def run(self, once=False, force_once=False): """ Main loop of the worker. Use once=True to execute any queued tasks and then exit. Use force_once=True with once=True to always exit after one processing loop even if tasks remain queued. """ self.log.info('ready',...
Whether Redis supports single command replication.
def can_replicate_commands(self): """ Whether Redis supports single command replication. """ if not hasattr(self, '_can_replicate_commands'): info = self.redis.info('server') version_info = info['redis_version'].split('.') major, minor = int(version_in...
Like ZADD, but supports different score update modes, in case the member already exists in the ZSET: - "nx": Don't update the score - "xx": Only update elements that already exist. Never add elements. - "min": Use the smaller of the given and existing score - "max": Use the large...
def zadd(self, key, score, member, mode, client=None): """ Like ZADD, but supports different score update modes, in case the member already exists in the ZSET: - "nx": Don't update the score - "xx": Only update elements that already exist. Never add elements. - "min": Use...
Pops the first ``count`` members from the ZSET ``source`` and adds them to the ZSET ``destination`` with a score of ``new_score``. If ``score`` is not None, only members up to a score of ``score`` are used. Returns the members that were moved and, if ``withscores`` is True, their origina...
def zpoppush(self, source, destination, count, score, new_score, client=None, withscores=False, on_success=None, if_exists=None): """ Pops the first ``count`` members from the ZSET ``source`` and adds them to the ZSET ``destination`` with a score of ``new_score`...
Removes ``member`` from the set ``key`` if ``other_key`` does not exist (i.e. is empty). Returns the number of removed elements (0 or 1).
def srem_if_not_exists(self, key, member, other_key, client=None): """ Removes ``member`` from the set ``key`` if ``other_key`` does not exist (i.e. is empty). Returns the number of removed elements (0 or 1). """ return self._srem_if_not_exists( keys=[key, other_key],...
Removes ``key`` only if ``member`` is not member of any sets in the ``set_list``. Returns the number of removed elements (0 or 1).
def delete_if_not_in_zsets(self, key, member, set_list, client=None): """ Removes ``key`` only if ``member`` is not member of any sets in the ``set_list``. Returns the number of removed elements (0 or 1). """ return self._delete_if_not_in_zsets( keys=[key]+set_list, ...
Fails with an error containing the string '<FAIL_IF_NOT_IN_ZSET>' if the given ``member`` is not in the ZSET ``key``. This can be used in a pipeline to assert that the member is in the ZSET and cancel the execution otherwise.
def fail_if_not_in_zset(self, key, member, client=None): """ Fails with an error containing the string '<FAIL_IF_NOT_IN_ZSET>' if the given ``member`` is not in the ZSET ``key``. This can be used in a pipeline to assert that the member is in the ZSET and cancel the execution othe...
Returns a list of expired tasks (older than ``time``) by looking at all active queues. The list is capped at ``batch_size``. The list contains tuples (queue, task_id).
def get_expired_tasks(self, key_prefix, time, batch_size, client=None): """ Returns a list of expired tasks (older than ``time``) by looking at all active queues. The list is capped at ``batch_size``. The list contains tuples (queue, task_id). """ result = self._get_expir...
Executes the given Redis pipeline as a Lua script. When an error occurs, the transaction stops executing, and an exception is raised. This differs from Redis transactions, where execution continues after an error. On success, a list of results is returned. The pipeline is cleared after e...
def execute_pipeline(self, pipeline, client=None): """ Executes the given Redis pipeline as a Lua script. When an error occurs, the transaction stops executing, and an exception is raised. This differs from Redis transactions, where execution continues after an error. On success,...
Periodic task schedule: Use to schedule a task to run periodically, starting from start_date (or None to be active immediately) until end_date (or None to repeat forever). The period starts at the given start_date, or on Jan 1st 2000. For more details, see README.
def periodic(seconds=0, minutes=0, hours=0, days=0, weeks=0, start_date=None, end_date=None): """ Periodic task schedule: Use to schedule a task to run periodically, starting from start_date (or None to be active immediately) until end_date (or None to repeat forever). The period start...
Return an attribute from a dotted path name (e.g. "path.to.func").
def import_attribute(name): """Return an attribute from a dotted path name (e.g. "path.to.func").""" try: sep = ':' if ':' in name else '.' # For backwards compatibility module_name, attribute = name.rsplit(sep, 1) module = importlib.import_module(module_name) return operator.at...
Generates and returns a hex-encoded 256-bit ID for the given task name and args. Used to generate IDs for unique tasks or for task locks.
def gen_unique_id(serialized_name, args, kwargs): """ Generates and returns a hex-encoded 256-bit ID for the given task name and args. Used to generate IDs for unique tasks or for task locks. """ return hashlib.sha256(json.dumps({ 'func': serialized_name, 'args': args, 'kwarg...
Returns the dotted serialized path to the passed function.
def serialize_func_name(func): """ Returns the dotted serialized path to the passed function. """ if func.__module__ == '__main__': raise ValueError('Functions from the __main__ module cannot be ' 'processed by workers.') try: # This will only work on Python ...
For a string "a.b.c", yields "a", "a.b", "a.b.c".
def dotted_parts(s): """ For a string "a.b.c", yields "a", "a.b", "a.b.c". """ idx = -1 while s: idx = s.find('.', idx+1) if idx == -1: yield s break yield s[:idx]
For a string "a.b.c", yields "a.b.c", "a.b", "a".
def reversed_dotted_parts(s): """ For a string "a.b.c", yields "a.b.c", "a.b", "a". """ idx = -1 if s: yield s while s: idx = s.rfind('.', 0, idx) if idx == -1: break yield s[:idx]
TaskTiger structlog processor. Inject the current task id for non-batch tasks.
def tasktiger_processor(logger, method_name, event_dict): """ TaskTiger structlog processor. Inject the current task id for non-batch tasks. """ if g['current_tasks'] is not None and not g['current_task_is_batch']: event_dict['task_id'] = g['current_tasks'][0].id return event_dict
Whether this task should be retried when the given exception occurs.
def should_retry_on(self, exception_class, logger=None): """ Whether this task should be retried when the given exception occurs. """ for n in (self.retry_on or []): try: if issubclass(exception_class, import_attribute(n)): return True ...
Internal helper to move a task from one state to another (e.g. from QUEUED to DELAYED). The "when" argument indicates the timestamp of the task in the new state. If no to_state is specified, the task will be simply removed from the original state. The "mode" param can be specified to de...
def _move(self, from_state=None, to_state=None, when=None, mode=None): """ Internal helper to move a task from one state to another (e.g. from QUEUED to DELAYED). The "when" argument indicates the timestamp of the task in the new state. If no to_state is specified, the task will be ...
Updates a scheduled task's date to the given date. If the task is not scheduled, a TaskNotFound exception is raised.
def update_scheduled_time(self, when): """ Updates a scheduled task's date to the given date. If the task is not scheduled, a TaskNotFound exception is raised. """ tiger = self.tiger ts = get_timestamp(when) assert ts pipeline = tiger.connection.pipeline...