signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def __len__(self):
return len(self.__records)<EOL>
Return number of postponed records :return: int
f9836:c2:m6
def __iter__(self):
while len(self.__records) > <NUM_LIT:0>:<EOL><INDENT>yield self.__records.pop(<NUM_LIT:0>)<EOL><DEDENT>
Iterate over postponed records. Once record is yield from this method, this record is removed from registry immediately :return: None
f9836:c2:m7
def __init__(self):
self.__sources = {}<EOL>self.__next_start = None<EOL>self.__next_sources = []<EOL>
Create new registry
f9836:c3:m0
@verify_type(task_source=WTaskSourceProto)<EOL><INDENT>def add_source(self, task_source):<DEDENT>
next_start = task_source.next_start()<EOL>self.__sources[task_source] = next_start<EOL>self.__update(task_source)<EOL>
Add new tasks source :param task_source: :return: None
f9836:c3:m1
@verify_type(task_source=(WTaskSourceProto, None))<EOL><INDENT>def update(self, task_source=None):<DEDENT>
if task_source is not None:<EOL><INDENT>self.__update(task_source)<EOL><DEDENT>else:<EOL><INDENT>self.__update_all()<EOL><DEDENT>
Recheck next start of records from all the sources (or from the given one only) :param task_source: if defined - source to check :return: None
f9836:c3:m2
def __update_all(self):
self.__next_start = None<EOL>self.__next_sources = []<EOL>for source in self.__sources:<EOL><INDENT>self.__update(source)<EOL><DEDENT>
Recheck next start of records from all the sources :return: None
f9836:c3:m3
@verify_type(task_source=WTaskSourceProto)<EOL><INDENT>def __update(self, task_source):<DEDENT>
next_start = task_source.next_start()<EOL>if next_start is not None:<EOL><INDENT>if next_start.tzinfo is None or next_start.tzinfo != timezone.utc:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.__next_start is None or next_start < self.__next_start:<EOL><INDENT>self.__next_start = next_start<EOL>self.__next_sources = [task_source]<EOL><DEDENT>elif next_start == self.__next_start:<EOL><INDENT>self.__next_sources.append(task_source)<EOL><DEDENT><DEDENT>
Recheck next start of tasks from the given one only :param task_source: source to check :return: None
f9836:c3:m4
def check(self):
if self.__next_start is not None:<EOL><INDENT>utc_now = utc_datetime()<EOL>if utc_now >= self.__next_start:<EOL><INDENT>result = []<EOL>for task_source in self.__next_sources:<EOL><INDENT>records = task_source.has_records()<EOL>if records is not None:<EOL><INDENT>result.extend(records)<EOL><DEDENT><DEDENT>self.__update_all()<EOL>if len(result) > <NUM_LIT:0>:<EOL><INDENT>return tuple(result)<EOL><DEDENT><DEDENT><DEDENT>
Check if there are records that are ready to start and return them if there are any :return: tuple of WScheduleRecord or None (if there are no tasks to start)
f9836:c3:m5
def task_sources(self):
return tuple(self.__sources.keys())<EOL>
Return task sources that was added to this registry :return: tuple of WTaskSourceProto
f9836:c3:m6
@verify_type('<STR_LIT>', maximum_postponed_records=(int, None))<EOL><INDENT>@verify_value('<STR_LIT>', maximum_postponed_records=lambda x: x is None or x > <NUM_LIT:0>)<EOL>@verify_type(maximum_running_records=(int, None), running_record_registry=(WRunningRecordRegistry, None))<EOL>@verify_type(postponed_record_registry=(WPostponedRecordRegistry, None))<EOL>@verify_type(thread_name_suffix=(str, None))<EOL>@verify_value(maximum_running_records=lambda x: x is None or x > <NUM_LIT:0>)<EOL>def __init__(<EOL>self, maximum_running_records=None, running_record_registry=None, maximum_postponed_records=None,<EOL>postponed_record_registry=None, thread_name_suffix=None<EOL>):<DEDENT>
WCriticalResource.__init__(self)<EOL>WSchedulerServiceProto.__init__(self)<EOL>thread_name = self.__thread_name_prefix__<EOL>if thread_name_suffix is not None:<EOL><INDENT>thread_name += thread_name_suffix<EOL><DEDENT>WPollingThreadTask.__init__(self, thread_name=thread_name)<EOL>if maximum_postponed_records is not None and postponed_record_registry is not None:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>default = lambda x, y: x if x is not None else y<EOL>self.__maximum_running_records = default(<EOL>maximum_running_records, self.__class__.__default_maximum_running_records__<EOL>)<EOL>self.__running_record_registry = default(running_record_registry, WRunningRecordRegistry())<EOL>self.__postponed_record_registry = WPostponedRecordRegistry(maximum_postponed_records)<EOL>self.__sources_registry = WTaskSourceRegistry()<EOL>self.__awake_at = None<EOL>
Create new scheduler :param maximum_running_records: number of records that are able to run simultaneously \ (WSchedulerService.__default_maximum_running_records__ is used as default value) :param running_record_registry: registry for running records :param maximum_postponed_records: number of records that are able to be postponed (no limit by default) :param postponed_record_registry: registry for postponed records :param thread_name_suffix: suffix to thread name
f9836:c4:m0
def maximum_running_records(self):
return self.__maximum_running_records<EOL>
Return number of tasks that are able to run simultaneously :return: int
f9836:c4:m1
def maximum_postponed_records(self):
return self.__postponed_record_registry.maximum_records()<EOL>
Return number of tasks that are able to be postponed :return: int or None (for no limit)
f9836:c4:m2
@WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)<EOL><INDENT>@verify_type('<STR_LIT>', task_source=WTaskSourceProto)<EOL>def add_task_source(self, task_source):<DEDENT>
self.__sources_registry.add_source(task_source)<EOL>
Add tasks source :param task_source: task source to add :return: None
f9836:c4:m3
@WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)<EOL><INDENT>def task_sources(self):<DEDENT>
return self.__sources_registry.task_sources()<EOL>
Return task sources that was added to this scheduler :return: tuple of WTaskSourceProto
f9836:c4:m4
@WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)<EOL><INDENT>@verify_type('<STR_LIT>', task_source=(WTaskSourceProto, None))<EOL>def update(self, task_source=None):<DEDENT>
self.__sources_registry.update(task_source=task_source)<EOL>
Recheck next start of tasks from all the sources (or from the given one only) :param task_source: if defined - source to check :return: None
f9836:c4:m5
def running_records(self):
return self.__running_record_registry.running_records()<EOL>
Return scheduled tasks that are running at the moment :return: tuple of WScheduleRecord
f9836:c4:m6
def records_status(self):
return len(self.__running_record_registry), len(self.__postponed_record_registry)<EOL>
Return number of running and postponed tasks :return: tuple of two ints (first - running tasks, second - postponed tasks)
f9836:c4:m7
def thread_started(self):
self.__running_record_registry.start()<EOL>self.__running_record_registry.start_event().wait()<EOL>WPollingThreadTask.thread_started(self)<EOL>
Start required registries and start this scheduler :return: None
f9836:c4:m8
@WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)<EOL><INDENT>def _polling_iteration(self):<DEDENT>
scheduled_tasks = self.__sources_registry.check()<EOL>has_postponed_tasks = self.__postponed_record_registry.has_records()<EOL>maximum_tasks = self.maximum_running_records()<EOL>if scheduled_tasks is not None or has_postponed_tasks is not None:<EOL><INDENT>running_tasks = len(self.__running_record_registry)<EOL>if running_tasks >= maximum_tasks:<EOL><INDENT>if scheduled_tasks is not None:<EOL><INDENT>for task in scheduled_tasks:<EOL><INDENT>self.__postponed_record_registry.postpone(task)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if has_postponed_tasks is True:<EOL><INDENT>for postponed_task in self.__postponed_record_registry:<EOL><INDENT>self.__running_record_registry.exec(postponed_task)<EOL>running_tasks += <NUM_LIT:1><EOL>if running_tasks >= maximum_tasks:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if scheduled_tasks is not None:<EOL><INDENT>for task in scheduled_tasks:<EOL><INDENT>if running_tasks >= maximum_tasks:<EOL><INDENT>self.__postponed_record_registry.postpone(task)<EOL><DEDENT>else:<EOL><INDENT>self.__running_record_registry.exec(task)<EOL>running_tasks += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>
Poll for different scheduler events like: there are tasks to run, there are tasks to postpone there are postponed tasks that should be running :return: None
f9836:c4:m9
@WCriticalResource.critical_section(timeout=__lock_acquiring_timeout__)<EOL><INDENT>def thread_stopped(self):<DEDENT>
self.__running_record_registry.stop()<EOL>
Stop registries and this scheduler :return: None
f9836:c4:m10
@verify_type('<STR_LIT>', thread_join_timeout=(int, float, None))<EOL><INDENT>def __init__(self, thread_join_timeout=None):<DEDENT>
self.__uid = self.generate_uid()<EOL>WThreadTask.__init__(<EOL>self, thread_name=(self.__thread_name_prefix__ + str(self.__uid)), join_on_stop=True,<EOL>ready_to_stop=True, thread_join_timeout=thread_join_timeout<EOL>)<EOL>
Create new task :param thread_join_timeout: same as thread_join_timeout in :meth:`.WThreadTask.__init__` method
f9838:c0:m0
@classmethod<EOL><INDENT>def generate_uid(cls):<DEDENT>
return uuid.uuid4()<EOL>
Return "random" "unique" identifier :return: UUID
f9838:c0:m2
@verify_type(task=WScheduleTask, task_group_id=(str, None))<EOL><INDENT>@verify_value(on_drop=lambda x: x is None or callable(x), on_wait=lambda x: x is None or callable(x))<EOL>def __init__(self, task, policy=None, task_group_id=None, on_drop=None, on_wait=None):<DEDENT>
if policy is not None and isinstance(policy, WScheduleRecord.PostponePolicy) is False:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>self.__task = task<EOL>self.__policy = policy if policy is not None else WScheduleRecord.PostponePolicy.wait<EOL>self.__task_group_id = task_group_id<EOL>self.__on_drop = on_drop<EOL>self.__on_wait = on_wait<EOL>
Create new schedule record :param task: task to run :param policy: postpone policy :param task_group_id: identifier that groups different scheduler records and single postpone policy :param on_drop: callback, that must be called if this task is skipped :param on_wait: callback, that must be called if this task is postponed
f9838:c1:m0
def task(self):
return self.__task<EOL>
Return task that should be run :return: WScheduleTask
f9838:c1:m1
def task_uid(self):
return self.task().uid()<EOL>
Shortcut for self.task().uid()
f9838:c1:m2
def policy(self):
return self.__policy<EOL>
Return postpone policy :return: WScheduleRecord.PostponePolicy
f9838:c1:m3
def task_group_id(self):
return self.__task_group_id<EOL>
Return task id :return: str or None see :meth:`.WScheduleRecord.__init__`
f9838:c1:m4
def task_postponed(self):
if self.__on_wait is not None:<EOL><INDENT>return self.__on_wait()<EOL><DEDENT>
Call a "on_wait" callback. This method is executed by a scheduler when it postpone this task :return: None
f9838:c1:m5
def task_dropped(self):
if self.__on_drop is not None:<EOL><INDENT>return self.__on_drop()<EOL><DEDENT>
Call a "on_drop" callback. This method is executed by a scheduler when it skip this task :return: None
f9838:c1:m6
@abstractmethod<EOL><INDENT>def has_records(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return records that should be run at the moment. :return: tuple of WScheduleRecord (tuple with one element at least) or None
f9838:c2:m0
@abstractmethod<EOL><INDENT>def next_start(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return datetime when the next task should be executed. :return: datetime in UTC timezone
f9838:c2:m1
@abstractmethod<EOL><INDENT>def tasks_planned(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return number of records (tasks) that are planned to run :return: int
f9838:c2:m2
@abstractmethod<EOL><INDENT>def scheduler_service(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return associated scheduler service :return: WSchedulerServiceProto or None
f9838:c2:m3
@abstractmethod<EOL><INDENT>@verify_type(schedule_record=WScheduleRecord)<EOL>def exec(self, schedule_record):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Execute the given scheduler record (no time checks are made at this method, task executes as is) :param schedule_record: record to execute :return: None
f9838:c3:m0
@abstractmethod<EOL><INDENT>def running_records(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return tuple of running tasks :return: tuple of WScheduleRecord
f9838:c3:m1
@abstractmethod<EOL><INDENT>@verify_type(task_source=(WTaskSourceProto, None))<EOL>def update(self, task_source=None):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Update task sources information about next start. Update information for the specified source or for all of them :param task_source: if it is specified - then update information for this source only This method implementation must be thread-safe as different threads (different task source, different registries) may modify scheduler internal state. :return:
f9838:c4:m0
def __init__(cls, name, bases, namespace):
ABCMeta.__init__(cls, name, bases, namespace)<EOL>if cls.__auto_registry__ is not True:<EOL><INDENT>return<EOL><DEDENT>if cls.__registry__ is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if issubclass(cls.__registry__, WTaskRegistry) is False:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>if issubclass(cls, WTask) is False:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>cls.__registry__.add(cls)<EOL>
Construct new class. Derived class must redefine __registry__ property (and __registry_tag__ depends on registry storage - see :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__`) :param name: as name in type(cls, name, bases, namespace) :param bases: as bases in type(cls, name, bases, namespace) :param namespace: as namespace in type(cls, name, bases, namespace)
f9839:c0:m0
@abstractmethod<EOL><INDENT>def add(self, task):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Add task to storage :param task: task to add (WTask class with WRegisteredTask metaclass) :return: None
f9839:c1:m0
@abstractmethod<EOL><INDENT>def remove(self, task):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Remove task from storage :param task: task to remove (WTask class with WRegisteredTask metaclass) :return: None
f9839:c1:m1
@abstractmethod<EOL><INDENT>def clear(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Remove every task from storage :return: None
f9839:c1:m2
@abstractmethod<EOL><INDENT>def tasks_by_tag(self, registry_tag):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Get tasks from registry by its tag :param registry_tag: any hash-able object :return: Return task or list of tasks
f9839:c1:m3
@abstractmethod<EOL><INDENT>def tasks(self, task_cls=None):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return tasks that was added to this registry :param task_cls: if it is not None, then result will be consist of this subclass only (useful fo filtering tasks) :return: tuple of WRegisteredTask
f9839:c1:m4
@abstractmethod<EOL><INDENT>def count(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Registered task count :return: int
f9839:c1:m5
@abstractmethod<EOL><INDENT>def tags(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return available registry tags :return: tuple of str
f9839:c1:m6
def __init__(self):
self.__registry = {}<EOL>
Construct new registry storage
f9839:c2:m0
@verify_subclass(task_cls=WTask)<EOL><INDENT>@verify_type(task_cls=WRegisteredTask)<EOL>def add(self, task_cls):<DEDENT>
registry_tag = task_cls.__registry_tag__<EOL>if registry_tag not in self.__registry.keys():<EOL><INDENT>self.__registry[registry_tag] = [task_cls]<EOL><DEDENT>elif self.__multiple_tasks_per_tag__ is True:<EOL><INDENT>self.__registry[registry_tag].append(task_cls)<EOL><DEDENT>else:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>
Add task to this storage. Depends on :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` tasks with the same __registry_tag__ can be treated as error. :param task_cls: task to add :return: None
f9839:c2:m1
@verify_subclass(task_cls=WTask)<EOL><INDENT>@verify_type(task_cls=WRegisteredTask)<EOL>def remove(self, task_cls):<DEDENT>
registry_tag = task_cls.__registry_tag__<EOL>if registry_tag in self.__registry.keys():<EOL><INDENT>self.__registry[registry_tag] =list(filter(lambda x: x != task_cls, self.__registry[registry_tag]))<EOL>if len(self.__registry[registry_tag]) == <NUM_LIT:0>:<EOL><INDENT>self.__registry.pop(registry_tag)<EOL><DEDENT><DEDENT>
Remove task from the storage. If task class are stored multiple times (if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is True) - removes all of them. :param task_cls: task to remove :return: None
f9839:c2:m2
def clear(self):
self.__registry.clear()<EOL>
Removes every task from storage :return: None
f9839:c2:m3
def tasks_by_tag(self, registry_tag):
if registry_tag not in self.__registry.keys():<EOL><INDENT>return None<EOL><DEDENT>tasks = self.__registry[registry_tag]<EOL>return tasks if self.__multiple_tasks_per_tag__ is True else tasks[<NUM_LIT:0>]<EOL>
Get tasks from registry by its tag :param registry_tag: any hash-able object :return: Return task (if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is not True) or \ list of tasks
f9839:c2:m4
@verify_type(task_cls=(WRegisteredTask, None))<EOL><INDENT>def tasks(self, task_cls=None):<DEDENT>
result = []<EOL>for tasks in self.__registry.values():<EOL><INDENT>result.extend(tasks)<EOL><DEDENT>if task_cls is not None:<EOL><INDENT>result = filter(lambda x: issubclass(x, task_cls), result)<EOL><DEDENT>return tuple(result)<EOL>
:meth:`.WTaskRegistryBase.tasks` implementation
f9839:c2:m5
def tags(self):
return tuple(self.__registry.keys())<EOL>
:meth:`.WTaskRegistryBase.tags` implementation
f9839:c2:m6
def count(self):
result = <NUM_LIT:0><EOL>for tasks in self.__registry.values():<EOL><INDENT>result += len(tasks)<EOL><DEDENT>return result<EOL>
Registered task count :return: int
f9839:c2:m7
@classmethod<EOL><INDENT>def registry_storage(cls):<DEDENT>
if cls.__registry_storage__ is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(cls.__registry_storage__, WTaskRegistryBase) is False:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>return cls.__registry_storage__<EOL>
Get registry storage :return: WTaskRegistryBase
f9839:c3:m0
@classmethod<EOL><INDENT>@verify_subclass('<STR_LIT>', task_cls=WTask)<EOL>@verify_type('<STR_LIT>', task_cls=WRegisteredTask)<EOL>def add(cls, task_cls):<DEDENT>
if task_cls.__registry_tag__ is None and cls.__skip_none_registry_tag__ is True:<EOL><INDENT>return<EOL><DEDENT>cls.registry_storage().add(task_cls)<EOL>
Add task class to storage :param task_cls: task to add :return: None
f9839:c3:m1
@classmethod<EOL><INDENT>@verify_subclass('<STR_LIT>', task_cls=WTask)<EOL>@verify_type('<STR_LIT>', task_cls=WRegisteredTask)<EOL>def remove(cls, task_cls):<DEDENT>
cls.registry_storage().remove(task_cls)<EOL>
Remove task class to storage :param task_cls: task to remove :return: None
f9839:c3:m2
@classmethod<EOL><INDENT>def clear(cls):<DEDENT>
cls.registry_storage().clear()<EOL>
Remove every task from storage :return: None
f9839:c3:m3
@verify_type(thread_name=(str, None), join_on_stop=bool, ready_to_stop=bool)<EOL><INDENT>@verify_type(thread_join_timeout=(int, float, None))<EOL>def __init__(self, thread_name=None, join_on_stop=True, ready_to_stop=False, thread_join_timeout=None):<DEDENT>
WStoppableTask.__init__(self)<EOL>self.__thread_join_timeout = self.__class__.__thread_join_timeout__<EOL>if thread_join_timeout is not None:<EOL><INDENT>self.__thread_join_timeout = thread_join_timeout<EOL><DEDENT>self.__thread = None<EOL>self.__thread_name = thread_name if thread_name is not None else self.__class__.__thread_name__<EOL>self.__start_event = Event()<EOL>self.__stop_event = Event() if join_on_stop is True else None<EOL>self.__ready_event = Event() if ready_to_stop is True else None<EOL>self.__exception_event = Event()<EOL>
Construct new threaded task. If 'ready_to_stop' is True, then thread event object is created (can be accessed through :meth:`.WThreadTask.ready_event`). This event shows, that this thread task has been done and it is ready to be stopped correctly. This event is set automatically after :meth:`.WTask.thread_started` method call. So, it implies that this method doesn't call extra thread or process creation, or :meth:`.WTask.thread_started` method waits for a thread/process termination. It implies that there are no leftover threads or processes (which can be cleaned up later, in the :meth:`.WTask.thread_stopped` method). If 'join_on_stop' is True, then thread event object is created (can be accessed through :meth:`.WThreadTask.stop_event`). This event shows, that there was a request for task to stop. Since task can be requested to stop at any time (application terminated, task canceled, ...) , it is better to enable and poll this flag. This flag enables automatic call of thread cleanup. When this flag is False, then child class must do all the cleaning itself (like thread joining and :meth:`.WThreadTask.close_thread` method calling). There are two other events - :meth:`.WThreadTask.start_event` and :meth:`.WThreadTask.exception_event`. The first one shows that thread function was started (it means that new thread was already created). The second one is set when exception is raised inside :meth:`.WThreadTask.thread_started` method. All exceptions, that are raised inside thread function, are passed to the callback :meth:`.WThreadTask.thread_exception`. With both flags ('ready_to_stop' and 'join_on_stop') there can be a situation, when ready event wasn't set, but stop event has been set already. This situation shows, that task was terminated before completion. :note: With join_on_stop flag enabled, :meth:`.WThreadTask.stop` method can not be called from the same execution thread. It means, that it can not be called from :meth:`.WThreadTask.start` or :meth:`.WThreadTask.thread_started` methods in direct or indirect way. In that case it is better to use 'ready_to_stop' event polling. :param thread_name: name of the thread. It is used in thread constructor as name value only :param join_on_stop: define whether to create stop event object or not. :param ready_to_stop: define whether to create ready event object or not :param thread_join_timeout: timeout for joining operation. If it isn't set then default \ :attr:`.WThreadTask.__thread_join_timeout__` value will be used. This value is used in \ :meth:`.WThreadTask.close_thread` method and if thread wasn't stopped for this period of time, then \ :class:`.WThreadJoiningTimeoutError` exception will be raised. note: Most event objects are cleared at :meth:`.WThreadTask.start` method (such as 'ready_event', 'stop_event', 'exception_event'). But only 'start_event' is cleared at stopping process. It is made this way because there may be concurrency if multiple threads that will wait for this thread to stop and one of those threads will clear the flag/event before other threads will do their job.
f9840:c1:m0
def thread(self):
return self.__thread<EOL>
Return current Thread object (or None if task wasn't started) :return: Thread or None
f9840:c1:m1
def thread_name(self):
return self.__thread_name<EOL>
Return thread name with which this thread is or will be created :return: str
f9840:c1:m2
def start_event(self):
return self.__start_event<EOL>
Return event which is set after the thread creation. Shows that a separate thread has been created already :return: Event
f9840:c1:m3
def stop_event(self):
return self.__stop_event<EOL>
Return stop event object. Event will be available if object was constructed with join_on_stop flag :return: Event or None
f9840:c1:m4
def ready_event(self):
return self.__ready_event<EOL>
Return readiness event object. Event will be available if object was constructed with ready_to_stop flag :return: Event or None
f9840:c1:m5
def exception_event(self):
return self.__exception_event<EOL>
Return event which is set if exception is raised inside thread function :return: Event
f9840:c1:m6
def join_timeout(self):
return self.__thread_join_timeout<EOL>
Return task join timeout :return: int or float
f9840:c1:m7
def close_thread(self):
if self.__thread is not None and self.__thread.is_alive() is True:<EOL><INDENT>raise WThreadJoiningTimeoutError('<STR_LIT>' % self.__thread.name)<EOL><DEDENT>self.start_event().clear()<EOL>self.__thread = None<EOL>
Clear all object descriptors for stopped task. Task must be joined prior to calling this method. :return: None
f9840:c1:m8
def start(self):
start_event = self.start_event()<EOL>stop_event = self.stop_event()<EOL>ready_event = self.ready_event()<EOL>def thread_target():<EOL><INDENT>try:<EOL><INDENT>start_event.set()<EOL>self.thread_started()<EOL>if ready_event is not None:<EOL><INDENT>ready_event.set()<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>self.exception_event().set()<EOL>self.thread_exception(e)<EOL><DEDENT><DEDENT>if self.__thread is None:<EOL><INDENT>if stop_event is not None:<EOL><INDENT>stop_event.clear()<EOL><DEDENT>if ready_event is not None:<EOL><INDENT>ready_event.clear()<EOL><DEDENT>self.exception_event().clear()<EOL>self.__thread = Thread(target=thread_target, name=self.thread_name())<EOL>self.__thread.start()<EOL><DEDENT>
:meth:`WStoppableTask.start` implementation that creates new thread
f9840:c1:m9
def stop(self):
thread = self.thread()<EOL>if thread is not None:<EOL><INDENT>if self.stop_event() is not None:<EOL><INDENT>self.stop_event().set()<EOL><DEDENT>self.thread_stopped()<EOL>if self.stop_event() is not None:<EOL><INDENT>thread.join(self.join_timeout())<EOL>self.close_thread()<EOL><DEDENT><DEDENT>
:meth:`WStoppableTask.stop` implementation that sets stop even (if available), calls :meth:`WStoppableTask.threaded_stopped` and cleans up thread (if configured)
f9840:c1:m10
@abstractmethod<EOL><INDENT>def thread_started(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Real task that do all the work :return: None
f9840:c1:m11
@abstractmethod<EOL><INDENT>def thread_stopped(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Method is called when task is about to stop (is called before joining process). This method is called whenever exception was raised or not :return: None
f9840:c1:m12
def thread_exception(self, raised_exception):
print('<STR_LIT>' % str(raised_exception))<EOL>print('<STR_LIT>')<EOL>print(traceback.format_exc())<EOL>
Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started` :param raised_exception: raised exception :return: None
f9840:c1:m13
def check_events(self):
return (<EOL>self.ready_event().is_set() is True or<EOL>self.stop_event().is_set() is True or<EOL>self.exception_event().is_set() is True<EOL>)<EOL>
Check "stopping"-events ('ready_event', 'stop_event', 'exception_event') if one of them is set. Usually True value means that thread is meant to be stopped, means that it is finished its job or some error has happened or this thread was asked to stop :return: bool
f9840:c1:m14
@verify_type(task=WTask)<EOL><INDENT>@verify_type('<STR_LIT>', thread_name=(str, None), join_on_stop=bool, ready_to_stop=bool)<EOL>@verify_type('<STR_LIT>', thread_join_timeout=(int, float, None))<EOL>def __init__(self, task, thread_name=None, join_on_stop=True, ready_to_stop=False, thread_join_timeout=None):<DEDENT>
WThreadTask.__init__(<EOL>self, thread_name=thread_name, join_on_stop=join_on_stop, ready_to_stop=ready_to_stop,<EOL>thread_join_timeout=thread_join_timeout<EOL>)<EOL>self.__task = task<EOL>
Create new WThreadTask task for the given task :param task: task that must be started in a separate thread :param thread_name: same as thread_name in :meth:`.WThreadTask.__init__` method :param join_on_stop: same as join_on_stop in :meth:`.WThreadTask.__init__` method :param ready_to_stop: same as ready_to_stop in :meth:`.WThreadTask.__init__` method :param thread_join_timeout: same as thread_join_timeout in :meth:`.WThreadTask.__init__` method
f9840:c2:m0
def task(self):
return self.__task<EOL>
Return original task :return: WTask
f9840:c2:m1
def thread_started(self):
self.task().start()<EOL>
Start original task :return: None
f9840:c2:m2
def thread_stopped(self):
task = self.task()<EOL>if isinstance(task, WStoppableTask) is True:<EOL><INDENT>task.stop()<EOL><DEDENT>
If original task is :class:`.WStoppableTask` object, then stop it :return: None
f9840:c2:m3
@verify_type('<STR_LIT>', thread_name=(str, None), thread_join_timeout=(int, float, None))<EOL><INDENT>@verify_type(polling_timeout=(int, float, None))<EOL>def __init__(self, thread_name=None, thread_join_timeout=None, polling_timeout=None):<DEDENT>
WThreadTask.__init__(<EOL>self, thread_name=thread_name, join_on_stop=True, ready_to_stop=True,<EOL>thread_join_timeout=thread_join_timeout<EOL>)<EOL>self.__polling_timeout =polling_timeout if polling_timeout is not None else self.__class__.__thread_polling_timeout__<EOL>
Create new task :param thread_name: same as 'thread_name' in :meth:`.WThreadTask.__init__` :param thread_join_timeout: same as 'thread_join_timeout' in :meth:`.WThreadTask.__init__` :param polling_timeout: polling timeout for this task
f9840:c3:m0
def polling_timeout(self):
return self.__polling_timeout<EOL>
Task polling timeout :return: int or float
f9840:c3:m1
def thread_started(self):
while self.check_events() is False:<EOL><INDENT>self._polling_iteration()<EOL>self.stop_event().wait(self.polling_timeout())<EOL><DEDENT>
Start polling for a stop event or ready event and do small work via :meth:`.WPollingThreadTask._polling_iteration` method call :return: None
f9840:c3:m2
@abstractmethod<EOL><INDENT>def _polling_iteration(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Do small work :return: None
f9840:c3:m3
@verify_type(threaded_task_chain=WThreadTask)<EOL><INDENT>@verify_type('<STR_LIT>', thread_name=(str, None), thread_join_timeout=(int, float, None))<EOL>@verify_type('<STR_LIT>', polling_timeout=(int, float, None))<EOL>def __init__(<EOL>self, *threaded_task_chain, thread_name=None, thread_join_timeout=None, polling_timeout=None<EOL>):<DEDENT>
WPollingThreadTask.__init__(<EOL>self, thread_name=thread_name, thread_join_timeout=thread_join_timeout,<EOL>polling_timeout=polling_timeout<EOL>)<EOL>self.__task_chain = threaded_task_chain<EOL>for task in self.__task_chain:<EOL><INDENT>if task.ready_event() is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>self.__current_task = None<EOL>
Create threaded tasks :param threaded_task_chain: tasks to execute :param thread_name: same as thread_name in :meth:`WPollingThreadTask.__init__` :param thread_join_timeout: same as thread_join_timeout in :meth:`WPollingThreadTask.__init__` :param polling_timeout: same as polling_timeout in :meth:`WPollingThreadTask.__init__`
f9840:c4:m0
def _polling_iteration(self):
if len(self.__task_chain) > <NUM_LIT:0>:<EOL><INDENT>if self.__current_task is None:<EOL><INDENT>self.__current_task = <NUM_LIT:0><EOL><DEDENT>task = self.__task_chain[self.__current_task]<EOL>if task.thread() is None:<EOL><INDENT>task.start()<EOL><DEDENT>elif task.ready_event().is_set() is True:<EOL><INDENT>task.stop()<EOL>if self.__current_task < (len(self.__task_chain) - <NUM_LIT:1>):<EOL><INDENT>self.__current_task += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self.ready_event().set()<EOL><DEDENT><DEDENT>elif task.exception_event().is_set() is True:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.ready_event().set()<EOL><DEDENT>
:meth:`.WPollingThreadTask._polling_iteration` implementation
f9840:c4:m1
def thread_stopped(self):
if self.__current_task is not None:<EOL><INDENT>task = self.__task_chain[self.__current_task]<EOL>task.stop()<EOL>self.__current_task = None<EOL><DEDENT>
:meth:`.WThreadTask._polling_iteration` implementation
f9840:c4:m2
@verify_type(name=str, severity=WTaskSensorSeverity, description=(str, None))<EOL><INDENT>def __init__(self, name, severity, description=None):<DEDENT>
self.__name = name<EOL>self.__severity = severity<EOL>self.__description = description<EOL>
Construct new sensor :param name: sensor name :param severity: sensor severity :param description: sensor description
f9841:c0:m0
def name(self):
return self.__name<EOL>
Return sensor name :return: string
f9841:c0:m1
def description(self):
return self.__description<EOL>
Return sensor description :return: string (or None if there is no description)
f9841:c0:m2
def severity(self):
return self.__severity<EOL>
Return sensor severity :return: WTaskHealthSensor.WTaskSensorSeverity
f9841:c0:m3
@abstractmethod<EOL><INDENT>def healthy(self):<DEDENT>
raise NotImplementedError("<STR_LIT>")<EOL>
Return True if sensor is OK, else - False :return: bool
f9841:c0:m4
@verify_value(comparator=lambda x: x is None or callable(x))<EOL><INDENT>def __init__(self, name, severity, error_value, description=None, comparator=None):<DEDENT>
WTaskHealthSensor.__init__(self, name, severity, description=description)<EOL>self._error_value = error_value<EOL>self._comparator = comparator if comparator is not None else lambda x, y: x < y<EOL>
Construct new measurable sensor. :param name: sensor name (as in :meth:`.WTaskHealthSensor.__init__`) :param severity: sensor severity (as in :meth:`.WTaskHealthSensor.__init__`) :param error_value: sensor limit :param description: sensor description (as in :meth:`.WTaskHealthSensor.__init__`) :param comparator: callable, that compares sensor value with error_value (if result is True, then \ sensor threats as healthy, if False - unhealthy). If comparator is None, then default function \ is used (function compares if sensor value are less then error_value)
f9841:c1:m0
def healthy(self):
return self._comparator(self.value(), self._error_value)<EOL>
Return True if sensor is OK, else - False :return: bool
f9841:c1:m1
def error_value(self):
return self._error_value<EOL>
Return error_value :return: (any type)
f9841:c1:m2
@abstractmethod<EOL><INDENT>def value(self):<DEDENT>
raise NotImplementedError("<STR_LIT>")<EOL>
Return current value sensor :return: (any type)
f9841:c1:m3
def measurement_unit(self):
raise NotImplementedError("<STR_LIT>")<EOL>
Return measurement unit of sensor :return: string
f9841:c1:m4
def sensor(self, sensor_name):
return self._sensors[sensor_name]<EOL>
Return sensor by its name :param sensor_name: name of sensor :return: WMeasurableTaskHealthSensor instance
f9841:c2:m1
def sensors(self):
return list(self._sensors.keys())<EOL>
Return list of sensor names :return: list of strings
f9841:c2:m2
def healthy(self):
state = None<EOL>for sensor in self._sensors.values():<EOL><INDENT>if sensor.healthy() is False:<EOL><INDENT>if state is None or sensor.severity().value > state.value:<EOL><INDENT>state = sensor.severity()<EOL><DEDENT>if state == WTaskHealthSensor.WTaskSensorSeverity.critical:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return state<EOL>
Return task health. If None - task is healthy, otherwise - maximum severity of sensors :return: None or WTaskHealthSensor.WTaskSensorSeverity
f9841:c2:m3
def mime_type(filename):
<EOL>try:<EOL><INDENT>__mime_lock.acquire()<EOL>extension = filename.split("<STR_LIT:.>")<EOL>extension = extension[len(extension) - <NUM_LIT:1>]<EOL>if extension == "<STR_LIT>":<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if extension == "<STR_LIT>":<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>m = magic.from_file(filename, mime=True)<EOL>m = m.decode() if isinstance(m, bytes) else m <EOL>if m == "<STR_LIT>":<EOL><INDENT>guessed_type = mimetypes.guess_type(filename)[<NUM_LIT:0>] <EOL>if guessed_type:<EOL><INDENT>return guessed_type<EOL><DEDENT><DEDENT>return m<EOL><DEDENT>finally:<EOL><INDENT>__mime_lock.release()<EOL><DEDENT>
Guess mime type for the given file name Note: this implementation uses python_magic package which is not thread-safe, as a workaround global lock is used for the ability to work in threaded environment :param filename: file name to guess :return: str
f9843:m0
def __init__(self, **components):
self.__components = {x: None for x in WURI.Component}<EOL>for component_name, component_value in components.items():<EOL><INDENT>self.component(component_name, component_value)<EOL><DEDENT>
Create new WURI object. By default empty URI is created :param components: components that must be set for this URI. Keys - components names as they defined in :class:`.WURI.Component`, values - corresponding values
f9844:c0:m0
@verify_type(item=str)<EOL><INDENT>def __getattr__(self, item):<DEDENT>
try:<EOL><INDENT>components_fn = object.__getattribute__(self, WURI.component.__name__)<EOL>item = WURI.Component(item)<EOL>return lambda: components_fn(item)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>return object.__getattribute__(self, item)<EOL>
Return component value by its name :param item: component name :return: in case of component name - function, that returns str or None
f9844:c0:m1
def __str__(self):
netloc = '<STR_LIT>'<EOL>username = self.username()<EOL>if username is not None:<EOL><INDENT>netloc += username<EOL><DEDENT>password = self.password()<EOL>if password is not None:<EOL><INDENT>netloc += '<STR_LIT::>' + password<EOL><DEDENT>if len(netloc) > <NUM_LIT:0>:<EOL><INDENT>netloc += '<STR_LIT:@>'<EOL><DEDENT>hostname = self.hostname()<EOL>if hostname is not None:<EOL><INDENT>netloc += hostname<EOL><DEDENT>port = self.port()<EOL>if port is not None:<EOL><INDENT>netloc += '<STR_LIT::>' + str(port)<EOL><DEDENT>scheme = self.scheme()<EOL>path = self.path()<EOL>if len(netloc) == <NUM_LIT:0> and scheme is not None and path is not None:<EOL><INDENT>path = '<STR_LIT>' + path<EOL><DEDENT>return urlunsplit((<EOL>scheme if scheme is not None else '<STR_LIT>',<EOL>netloc,<EOL>path if path is not None else '<STR_LIT>',<EOL>self.query(),<EOL>self.fragment()<EOL>))<EOL>
Return string that represents this URI :return: str
f9844:c0:m2
@verify_type(component=(str, Component))<EOL><INDENT>def component(self, component, value=None):<DEDENT>
if isinstance(component, str) is True:<EOL><INDENT>component = WURI.Component(component)<EOL><DEDENT>if value is not None:<EOL><INDENT>self.__components[component] = value<EOL>return value<EOL><DEDENT>return self.__components[component]<EOL>
Set and/or get component value. :param component: component name to return :param value: if value is not None, this value will be set as a component value :return: str
f9844:c0:m3