desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Get any non-OAuth parameters.'
| def get_nonoauth_parameters(self):
| return dict([(k, v) for (k, v) in self.iteritems() if (not k.startswith('oauth_'))])
|
'Serialize as a header for an HTTPAuth request.'
| def to_header(self, realm=''):
| oauth_params = ((k, v) for (k, v) in self.items() if k.startswith('oauth_'))
stringy_params = ((k, escape(str(v))) for (k, v) in oauth_params)
header_params = (('%s="%s"' % (k, v)) for (k, v) in stringy_params)
params_header = ', '.join(header_params)
auth_header = ('OAuth realm="%s"' % realm)... |
'Serialize as post data for a POST request.'
| def to_postdata(self):
| return self.encode_postdata(self)
|
'Serialize as a URL for a GET request.'
| def to_url(self):
| return ('%s?%s' % (self.url, self.to_postdata()))
|
'Return a string that contains the parameters that must be signed.'
| def get_normalized_parameters(self):
| items = [(k, v) for (k, v) in self.items() if (k != 'oauth_signature')]
encoded_str = urllib.urlencode(sorted(items), True)
return encoded_str.replace('+', '%20')
|
'Set the signature parameter to the result of sign.'
| def sign_request(self, signature_method, consumer, token):
| if ('oauth_consumer_key' not in self):
self['oauth_consumer_key'] = consumer.key
if (token and ('oauth_token' not in self)):
self['oauth_token'] = token.key
self['oauth_signature_method'] = signature_method.name
self['oauth_signature'] = signature_method.sign(self, consumer, token)
|
'Get seconds since epoch (UTC).'
| @classmethod
def make_timestamp(cls):
| return str(int(time.time()))
|
'Generate pseudorandom number.'
| @classmethod
def make_nonce(cls):
| return str(random.randint(0, 100000000))
|
'Combines multiple parameter sources.'
| @classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None):
| if (parameters is None):
parameters = {}
if (headers and ('Authorization' in headers)):
auth_header = headers['Authorization']
if (auth_header[:6] == 'OAuth '):
auth_header = auth_header[6:]
try:
header_params = cls._split_header(auth_header)
... |
'Turn Authorization: header into parameters.'
| @staticmethod
def _split_header(header):
| params = {}
parts = header.split(',')
for param in parts:
if (param.find('realm') > (-1)):
continue
param = param.strip()
param_parts = param.split('=', 1)
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('"'))
return params
|
'Turn URL string into parameters.'
| @staticmethod
def _split_url_string(param_str):
| parameters = parse_qs(param_str, keep_blank_values=False)
for (k, v) in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
|
'Verifies an api call and checks all the parameters.'
| def verify_request(self, request, consumer, token):
| version = self._get_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters
|
'Optional support for the authenticate header.'
| def build_authenticate_header(self, realm=''):
| return {'WWW-Authenticate': ('OAuth realm="%s"' % realm)}
|
'Verify the correct version request for this server.'
| def _get_version(self, request):
| try:
version = request.get_parameter('oauth_version')
except:
version = VERSION
if (version and (version != self.version)):
raise Error(('OAuth version %s not supported.' % str(version)))
return version
|
'Figure out the signature with some defaults.'
| def _get_signature_method(self, request):
| try:
signature_method = request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise ... |
'Verify that timestamp is recentish.'
| def _check_timestamp(self, timestamp):
| timestamp = int(timestamp)
now = int(time.time())
lapsed = (now - timestamp)
if (lapsed > self.timestamp_threshold):
raise Error(('Expired timestamp: given %d and now %s has a greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold... |
'Calculates the string that needs to be signed.
This method returns a 2-tuple containing the starting key for the
signing and the message to be signed. The latter may be used in error
messages to help clients debug their software.'
| def signing_base(self, request, consumer, token):
| raise NotImplementedError
|
'Returns the signature for the given request, based on the consumer
and token also provided.
You should use your implementation of `signing_base()` to build the
message to sign. Otherwise it may be less useful for debugging.'
| def sign(self, request, consumer, token):
| raise NotImplementedError
|
'Returns whether the given signature is the correct signature for
the given consumer and token signing the given request.'
| def check(self, request, consumer, token, signature):
| built = self.sign(request, consumer, token)
return (built == signature)
|
'Builds the base signature string.'
| def sign(self, request, consumer, token):
| (key, raw) = self.signing_base(request, consumer, token)
try:
import hashlib
hashed = hmac.new(key, raw, hashlib.sha1)
except ImportError:
import sha
hashed = hmac.new(key, raw, sha)
return binascii.b2a_base64(hashed.digest())[:(-1)]
|
'Concatenates the consumer key and secret with the token\'s
secret.'
| def signing_base(self, request, consumer, token):
| sig = ('%s&' % escape(consumer.secret))
if token:
sig = (sig + escape(token.secret))
return (sig, sig)
|
'Makes the given changes to this job and saves it in the associated job store.
Accepted keyword arguments are the same as the variables on this class.
.. seealso:: :meth:`~apscheduler.schedulers.base.BaseScheduler.modify_job`'
| def modify(self, **changes):
| self._scheduler.modify_job(self.id, self._jobstore_alias, **changes)
|
'Shortcut for switching the trigger on this job.
.. seealso:: :meth:`~apscheduler.schedulers.base.BaseScheduler.reschedule_job`'
| def reschedule(self, trigger, **trigger_args):
| self._scheduler.reschedule_job(self.id, self._jobstore_alias, trigger, **trigger_args)
|
'Temporarily suspend the execution of this job.
.. seealso:: :meth:`~apscheduler.schedulers.base.BaseScheduler.pause_job`'
| def pause(self):
| self._scheduler.pause_job(self.id, self._jobstore_alias)
|
'Resume the schedule of this job if previously paused.
.. seealso:: :meth:`~apscheduler.schedulers.base.BaseScheduler.resume_job`'
| def resume(self):
| self._scheduler.resume_job(self.id, self._jobstore_alias)
|
'Unschedules this job and removes it from its associated job store.
.. seealso:: :meth:`~apscheduler.schedulers.base.BaseScheduler.remove_job`'
| def remove(self):
| self._scheduler.remove_job(self.id, self._jobstore_alias)
|
'Returns ``True`` if the referenced job is still waiting to be added to its designated job store.'
| @property
def pending(self):
| return (self._jobstore_alias is None)
|
'Computes the scheduled run times between ``next_run_time`` and ``now`` (inclusive).
:type now: datetime.datetime
:rtype: list[datetime.datetime]'
| def _get_run_times(self, now):
| run_times = []
next_run_time = self.next_run_time
while (next_run_time and (next_run_time <= now)):
run_times.append(next_run_time)
next_run_time = self.trigger.get_next_fire_time(next_run_time, now)
return run_times
|
'Validates the changes to the Job and makes the modifications if and only if all of them validate.'
| def _modify(self, **changes):
| approved = {}
if ('id' in changes):
value = changes.pop('id')
if (not isinstance(value, six.string_types)):
raise TypeError('id must be a nonempty string')
if hasattr(self, 'id'):
raise ValueError('The job ID may not be changed')
... |
'Called by the scheduler when the scheduler is being started or when the executor is being added to an already
running scheduler.
:param apscheduler.schedulers.base.BaseScheduler scheduler: the scheduler that is starting this executor
:param str|unicode alias: alias of this executor as it was assigned to the scheduler'... | def start(self, scheduler, alias):
| self._scheduler = scheduler
self._lock = scheduler._create_lock()
self._logger = logging.getLogger(('apscheduler.executors.%s' % alias))
|
'Submits job for execution.
:param Job job: job to execute
:param list[datetime] run_times: list of datetimes specifying when the job should have been run
:raises MaxInstancesReachedError: if the maximum number of allowed instances for this job has been reached'
| def submit_job(self, job, run_times):
| assert (self._lock is not None), 'This executor has not been started yet'
with self._lock:
if (self._instances[job.id] >= job.max_instances):
raise MaxInstancesReachedError(job)
self._do_submit_job(job, run_times)
self._instances[job.id] += 1
|
'Called by the executor with the list of generated events when `run_job` has been successfully called.'
| def _run_job_success(self, job_id, events):
| with self._lock:
self._instances[job_id] -= 1
for event in events:
self._scheduler._dispatch_event(event)
|
'Called by the executor with the exception if there is an error calling `run_job`.'
| def _run_job_error(self, job_id, exc, traceback=None):
| with self._lock:
self._instances[job_id] -= 1
exc_info = (exc.__class__, exc, traceback)
self._logger.error('Error running job %s', job_id, exc_info=exc_info)
|
'Called by the scheduler when the scheduler is being started or when the job store is being added to an already
running scheduler.
:param apscheduler.schedulers.base.BaseScheduler scheduler: the scheduler that is starting this job store
:param str|unicode alias: alias of this job store as it was assigned to the schedul... | def start(self, scheduler, alias):
| self._scheduler = scheduler
self._alias = alias
self._logger = logging.getLogger(('apscheduler.jobstores.%s' % alias))
|
'Returns the index of the given job, or if it\'s not found, the index where the job should be inserted based on
the given timestamp.
:type timestamp: int
:type job_id: str'
| def _get_job_index(self, timestamp, job_id):
| (lo, hi) = (0, len(self._jobs))
timestamp = (float('inf') if (timestamp is None) else timestamp)
while (lo < hi):
mid = ((lo + hi) // 2)
(mid_job, mid_timestamp) = self._jobs[mid]
mid_timestamp = (float('inf') if (mid_timestamp is None) else mid_timestamp)
if (mid_timestamp >... |
'Increments the designated field and resets all less significant fields to their minimum values.
:type dateval: datetime
:type fieldnum: int
:return: a tuple containing the new date, and the number of the field that was actually incremented
:rtype: tuple'
| def _increment_field_value(self, dateval, fieldnum):
| values = {}
i = 0
while (i < len(self.fields)):
field = self.fields[i]
if (not field.REAL):
if (i == fieldnum):
fieldnum -= 1
i -= 1
else:
i += 1
continue
if (i < fieldnum):
values[field.n... |
'Reconfigures the scheduler with the given options. Can only be done when the scheduler isn\'t running.
:param dict gconfig: a "global" configuration dictionary whose values can be overridden by keyword arguments to
this method
:param str|unicode prefix: pick only those keys from ``gconfig`` that are prefixed with this... | def configure(self, gconfig={}, prefix='apscheduler.', **options):
| if self.running:
raise SchedulerAlreadyRunningError
if prefix:
prefixlen = len(prefix)
gconfig = dict(((key[prefixlen:], value) for (key, value) in six.iteritems(gconfig) if key.startswith(prefix)))
config = {}
for (key, value) in six.iteritems(gconfig):
parts = key.split... |
'Starts the scheduler. The details of this process depend on the implementation.
:raises SchedulerAlreadyRunningError: if the scheduler is already running'
| @abstractmethod
def start(self):
| if self.running:
raise SchedulerAlreadyRunningError
with self._executors_lock:
if ('default' not in self._executors):
self.add_executor(self._create_default_executor(), 'default')
for (alias, executor) in six.iteritems(self._executors):
executor.start(self, alias)... |
'Shuts down the scheduler. Does not interrupt any currently running jobs.
:param bool wait: ``True`` to wait until all currently executing jobs have finished
:raises SchedulerNotRunningError: if the scheduler has not been started yet'
| @abstractmethod
def shutdown(self, wait=True):
| if (not self.running):
raise SchedulerNotRunningError
self._stopped = True
for executor in six.itervalues(self._executors):
executor.shutdown(wait)
for jobstore in six.itervalues(self._jobstores):
jobstore.shutdown()
self._logger.info('Scheduler has been shut down... |
'Adds an executor to this scheduler. Any extra keyword arguments will be passed to the executor plugin\'s
constructor, assuming that the first argument is the name of an executor plugin.
:param str|unicode|apscheduler.executors.base.BaseExecutor executor: either an executor instance or the name of
an executor plugin
:p... | def add_executor(self, executor, alias='default', **executor_opts):
| with self._executors_lock:
if (alias in self._executors):
raise ValueError(('This scheduler already has an executor by the alias of "%s"' % alias))
if isinstance(executor, BaseExecutor):
self._executors[alias] = executor
elif isinstance(e... |
'Removes the executor by the given alias from this scheduler.
:param str|unicode alias: alias of the executor
:param bool shutdown: ``True`` to shut down the executor after removing it'
| def remove_executor(self, alias, shutdown=True):
| with self._jobstores_lock:
executor = self._lookup_executor(alias)
del self._executors[alias]
if shutdown:
executor.shutdown()
self._dispatch_event(SchedulerEvent(EVENT_EXECUTOR_REMOVED, alias))
|
'Adds a job store to this scheduler. Any extra keyword arguments will be passed to the job store plugin\'s
constructor, assuming that the first argument is the name of a job store plugin.
:param str|unicode|apscheduler.jobstores.base.BaseJobStore jobstore: job store to be added
:param str|unicode alias: alias for the j... | def add_jobstore(self, jobstore, alias='default', **jobstore_opts):
| with self._jobstores_lock:
if (alias in self._jobstores):
raise ValueError(('This scheduler already has a job store by the alias of "%s"' % alias))
if isinstance(jobstore, BaseJobStore):
self._jobstores[alias] = jobstore
elif isinstanc... |
'Removes the job store by the given alias from this scheduler.
:param str|unicode alias: alias of the job store
:param bool shutdown: ``True`` to shut down the job store after removing it'
| def remove_jobstore(self, alias, shutdown=True):
| with self._jobstores_lock:
jobstore = self._lookup_jobstore(alias)
del self._jobstores[alias]
if shutdown:
jobstore.shutdown()
self._dispatch_event(SchedulerEvent(EVENT_JOBSTORE_REMOVED, alias))
|
'add_listener(callback, mask=EVENT_ALL)
Adds a listener for scheduler events. When a matching event occurs, ``callback`` is executed with the event
object as its sole argument. If the ``mask`` parameter is not provided, the callback will receive events of all
types.
:param callback: any callable that takes one argument... | def add_listener(self, callback, mask=EVENT_ALL):
| with self._listeners_lock:
self._listeners.append((callback, mask))
|
'Removes a previously added event listener.'
| def remove_listener(self, callback):
| with self._listeners_lock:
for (i, (cb, _)) in enumerate(self._listeners):
if (callback == cb):
del self._listeners[i]
|
'add_job(func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore=\'default\', executor=\'default\', replace_existing=False, **trigger_args)
Adds the given job to the job list and ... | def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', replace_existing=False, **trigger_args):
| job_kwargs = {'trigger': self._create_trigger(trigger, trigger_args), 'executor': executor, 'func': func, 'args': (tuple(args) if (args is not None) else ()), 'kwargs': (dict(kwargs) if (kwargs is not None) else {}), 'id': id, 'name': name, 'misfire_grace_time': misfire_grace_time, 'coalesce': coalesce, 'max_instan... |
'scheduled_job(trigger, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore=\'default\', executor=\'default\',**trigger_args)
A decorator version of :meth:`add_job`, except that ``replace_existin... | def scheduled_job(self, trigger, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', **trigger_args):
| def inner(func):
self.add_job(func, trigger, args, kwargs, id, name, misfire_grace_time, coalesce, max_instances, next_run_time, jobstore, executor, True, **trigger_args)
return func
return inner
|
'Modifies the properties of a single job. Modifications are passed to this method as extra keyword arguments.
:param str|unicode job_id: the identifier of the job
:param str|unicode jobstore: alias of the job store that contains the job'
| def modify_job(self, job_id, jobstore=None, **changes):
| with self._jobstores_lock:
(job, jobstore) = self._lookup_job(job_id, jobstore)
job._modify(**changes)
if jobstore:
self._lookup_jobstore(jobstore).update_job(job)
self._dispatch_event(JobEvent(EVENT_JOB_MODIFIED, job_id, jobstore))
self.wakeup()
|
'Constructs a new trigger for a job and updates its next run time.
Extra keyword arguments are passed directly to the trigger\'s constructor.
:param str|unicode job_id: the identifier of the job
:param str|unicode jobstore: alias of the job store that contains the job
:param trigger: alias of the trigger type or a trig... | def reschedule_job(self, job_id, jobstore=None, trigger=None, **trigger_args):
| trigger = self._create_trigger(trigger, trigger_args)
now = datetime.now(self.timezone)
next_run_time = trigger.get_next_fire_time(None, now)
self.modify_job(job_id, jobstore, trigger=trigger, next_run_time=next_run_time)
|
'Causes the given job not to be executed until it is explicitly resumed.
:param str|unicode job_id: the identifier of the job
:param str|unicode jobstore: alias of the job store that contains the job'
| def pause_job(self, job_id, jobstore=None):
| self.modify_job(job_id, jobstore, next_run_time=None)
|
'Resumes the schedule of the given job, or removes the job if its schedule is finished.
:param str|unicode job_id: the identifier of the job
:param str|unicode jobstore: alias of the job store that contains the job'
| def resume_job(self, job_id, jobstore=None):
| with self._jobstores_lock:
(job, jobstore) = self._lookup_job(job_id, jobstore)
now = datetime.now(self.timezone)
next_run_time = job.trigger.get_next_fire_time(None, now)
if next_run_time:
self.modify_job(job_id, jobstore, next_run_time=next_run_time)
else:
... |
'Returns a list of pending jobs (if the scheduler hasn\'t been started yet) and scheduled jobs, either from a
specific job store or from all of them.
:param str|unicode jobstore: alias of the job store
:param bool pending: ``False`` to leave out pending jobs (jobs that are waiting for the scheduler start to be
added to... | def get_jobs(self, jobstore=None, pending=None):
| with self._jobstores_lock:
jobs = []
if (pending is not False):
for (job, alias, replace_existing) in self._pending_jobs:
if ((jobstore is None) or (alias == jobstore)):
jobs.append(job)
if (pending is not True):
for (alias, store) ... |
'Returns the Job that matches the given ``job_id``.
:param str|unicode job_id: the identifier of the job
:param str|unicode jobstore: alias of the job store that most likely contains the job
:return: the Job by the given ID, or ``None`` if it wasn\'t found
:rtype: Job'
| def get_job(self, job_id, jobstore=None):
| with self._jobstores_lock:
try:
return self._lookup_job(job_id, jobstore)[0]
except JobLookupError:
return
|
'Removes a job, preventing it from being run any more.
:param str|unicode job_id: the identifier of the job
:param str|unicode jobstore: alias of the job store that contains the job
:raises JobLookupError: if the job was not found'
| def remove_job(self, job_id, jobstore=None):
| with self._jobstores_lock:
for (i, (job, jobstore_alias, replace_existing)) in enumerate(self._pending_jobs):
if (job.id == job_id):
del self._pending_jobs[i]
jobstore = jobstore_alias
break
else:
for (alias, store) in six.iteri... |
'Removes all jobs from the specified job store, or all job stores if none is given.
:param str|unicode jobstore: alias of the job store'
| def remove_all_jobs(self, jobstore=None):
| with self._jobstores_lock:
if jobstore:
self._pending_jobs = [pending for pending in self._pending_jobs if (pending[1] != jobstore)]
else:
self._pending_jobs = []
for (alias, store) in six.iteritems(self._jobstores):
if (jobstore in (None, alias)):
... |
'print_jobs(jobstore=None, out=sys.stdout)
Prints out a textual listing of all jobs currently scheduled on either all job stores or just a specific one.
:param str|unicode jobstore: alias of the job store, ``None`` to list jobs from all stores
:param file out: a file-like object to print to (defaults to **sys.stdout** ... | def print_jobs(self, jobstore=None, out=None):
| out = (out or sys.stdout)
with self._jobstores_lock:
if self._pending_jobs:
print(six.u('Pending jobs:'), file=out)
for (job, jobstore_alias, replace_existing) in self._pending_jobs:
if (jobstore in (None, jobstore_alias)):
print((six.u(' ... |
'Creates a default executor store, specific to the particular scheduler type.'
| def _create_default_executor(self):
| return ThreadPoolExecutor()
|
'Creates a default job store, specific to the particular scheduler type.'
| def _create_default_jobstore(self):
| return MemoryJobStore()
|
'Returns the executor instance by the given name from the list of executors that were added to this scheduler.
:type alias: str
:raises KeyError: if no executor by the given alias is not found'
| def _lookup_executor(self, alias):
| try:
return self._executors[alias]
except KeyError:
raise KeyError(('No such executor: %s' % alias))
|
'Returns the job store instance by the given name from the list of job stores that were added to this scheduler.
:type alias: str
:raises KeyError: if no job store by the given alias is not found'
| def _lookup_jobstore(self, alias):
| try:
return self._jobstores[alias]
except KeyError:
raise KeyError(('No such job store: %s' % alias))
|
'Finds a job by its ID.
:type job_id: str
:param str jobstore_alias: alias of a job store to look in
:return tuple[Job, str]: a tuple of job, jobstore alias (jobstore alias is None in case of a pending job)
:raises JobLookupError: if no job by the given ID is found.'
| def _lookup_job(self, job_id, jobstore_alias):
| for (job, alias, replace_existing) in self._pending_jobs:
if (job.id == job_id):
return (job, None)
for (alias, store) in six.iteritems(self._jobstores):
if (jobstore_alias in (None, alias)):
job = store.lookup_job(job_id)
if (job is not None):
... |
'Dispatches the given event to interested listeners.
:param SchedulerEvent event: the event to send'
| def _dispatch_event(self, event):
| with self._listeners_lock:
listeners = tuple(self._listeners)
for (cb, mask) in listeners:
if (event.code & mask):
try:
cb(event)
except:
self._logger.exception('Error notifying listener')
|
':param Job job: the job to add
:param bool replace_existing: ``True`` to use update_job() in case the job already exists in the store
:param bool wakeup: ``True`` to wake up the scheduler after adding the job'
| def _real_add_job(self, job, jobstore_alias, replace_existing, wakeup):
| replacements = {}
for (key, value) in six.iteritems(self._job_defaults):
if (not hasattr(job, key)):
replacements[key] = value
if (not hasattr(job, 'next_run_time')):
now = datetime.now(self.timezone)
replacements['next_run_time'] = job.trigger.get_next_fire_time(None, no... |
'Creates an instance of the given plugin type, loading the plugin first if necessary.'
| def _create_plugin_instance(self, type_, alias, constructor_kwargs):
| (plugin_container, class_container, base_class) = {'trigger': (self._trigger_plugins, self._trigger_classes, BaseTrigger), 'jobstore': (self._jobstore_plugins, self._jobstore_classes, BaseJobStore), 'executor': (self._executor_plugins, self._executor_classes, BaseExecutor)}[type_]
try:
plugin_cls = clas... |
'Creates a reentrant lock object.'
| def _create_lock(self):
| return RLock()
|
'Iterates through jobs in every jobstore, starts jobs that are due and figures out how long to wait for the next
round.'
| def _process_jobs(self):
| self._logger.debug('Looking for jobs to run')
now = datetime.now(self.timezone)
next_wakeup_time = None
with self._jobstores_lock:
for (jobstore_alias, jobstore) in six.iteritems(self._jobstores):
for job in jobstore.get_due_jobs(now):
try:
... |
'Raises NotBinaryPlistException.'
| def __init__(self, fileOrStream):
| self.reset()
self.file = fileOrStream
|
'Numbers of 8 bytes are signed integers when they refer to numbers, but unsigned otherwise.'
| def getSizedInteger(self, data, byteSize, as_number=False):
| result = 0
if (byteSize == 1):
result = unpack('>B', data)[0]
elif (byteSize == 2):
result = unpack('>H', data)[0]
elif (byteSize == 4):
result = unpack('>L', data)[0]
elif (byteSize == 8):
if as_number:
result = unpack('>q', data)[0]
else:
... |
'If the given object has been written already, return its
position in the offset table. Otherwise, return None.'
| def positionOfObjectReference(self, obj):
| return self.writtenReferences.get(obj)
|
'Strategy is:
- write header
- wrap root object so everything is hashable
- compute size of objects which will be written
- need to do this in order to know how large the object refs
will be in the list/dict/set reference lists
- write objects
- keep objects in writtenReferences
- keep positions of object references in... | def writeRoot(self, root):
| output = self.header
wrapped_root = self.wrapRoot(root)
should_reference_root = True
self.computeOffsets(wrapped_root, asReference=should_reference_root, isRoot=True)
self.trailer = self.trailer._replace(**{'objectRefSize': self.intSize(len(self.computedUniques))})
(_, output) = self.writeObject... |
'Tries to write an object reference, adding it to the references
table. Does not write the actual object bytes or set the reference
position. Returns a tuple of whether the object was a new reference
(True if it was, False if it already was in the reference table)
and the new output.'
| def writeObjectReference(self, obj, output):
| position = self.positionOfObjectReference(obj)
if (position is None):
self.writtenReferences[obj] = len(self.writtenReferences)
output += self.binaryInt((len(self.writtenReferences) - 1), byteSize=self.trailer.objectRefSize)
return (True, output)
else:
output += self.binaryIn... |
'Serializes the given object to the output. Returns output.
If setReferencePosition is True, will set the position the
object was written.'
| def writeObject(self, obj, output, setReferencePosition=False):
| def proc_variable_length(format, length):
result = ''
if (length > 14):
result += pack('!B', ((format << 4) | 15))
result = self.writeObject(length, result)
else:
result += pack('!B', ((format << 4) | length))
return result
if (isinstance(obj, ... |
'Writes all of the object reference offsets.'
| def writeOffsetTable(self, output):
| all_positions = []
writtenReferences = list(self.writtenReferences.items())
writtenReferences.sort(key=(lambda x: x[1]))
for (obj, order) in writtenReferences:
if ((bytes != str) and (obj == unicodeEmpty)):
obj = ''
position = self.referencePositions.get(obj)
if (posi... |
'Returns the number of bytes necessary to store the given integer.'
| def intSize(self, obj):
| if (obj < 0):
return 8
elif (obj <= 255):
return 1
elif (obj <= 65535):
return 2
elif (obj <= 4294967295):
return 4
elif (obj <= 9223372036854775807):
return 8
elif (obj <= 18446744073709551615L):
return 16
else:
raise InvalidPlistExcep... |
'Dequeue and return a record.'
| def dequeue(self, block):
| if block:
s = self.queue.blpop(self.key)[1]
else:
s = self.queue.lpop(self.key)
if (not s):
record = None
else:
record = pickle.loads(s)
return record
|
'Initialise an instance, using the passed queue.'
| def __init__(self, queue):
| logging.Handler.__init__(self)
self.queue = queue
|
'Enqueue a record.
The base implementation uses :meth:`~queue.Queue.put_nowait`. You may
want to override this method if you want to use blocking, timeouts or
custom queue implementations.
:param record: The record to enqueue.'
| def enqueue(self, record):
| self.queue.put_nowait(record)
|
'Prepares a record for queuing. The object returned by this method is
enqueued.
The base implementation formats the record to merge the message
and arguments, and removes unpickleable items from the record
in-place.
You might want to override this method if you want to convert
the record to a dict or JSON string, or se... | def prepare(self, record):
| self.format(record)
record.msg = record.message
record.args = None
record.exc_info = None
return record
|
'Emit a record.
Writes the LogRecord to the queue, preparing it for pickling first.
:param record: The record to emit.'
| def emit(self, record):
| try:
self.enqueue(self.prepare(record))
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
|
'Initialise an instance with the specified queue and
handlers.'
| def __init__(self, queue, *handlers):
| self.queue = queue
self.handlers = handlers
self._stop = threading.Event()
self._thread = None
|
'Dequeue a record and return it, optionally blocking.
The base implementation uses :meth:`~queue.Queue.get`. You may want to
override this method if you want to use timeouts or work with custom
queue implementations.
:param block: Whether to block if the queue is empty. If `False` and
the queue is empty, an :class:`~qu... | def dequeue(self, block):
| return self.queue.get(block)
|
'Start the listener.
This starts up a background thread to monitor the queue for
LogRecords to process.'
| def start(self):
| self._thread = t = threading.Thread(target=self._monitor)
t.setDaemon(True)
t.start()
|
'Prepare a record for handling.
This method just returns the passed-in record. You may want to
override this method if you need to do any custom marshalling or
manipulation of the record before passing it to the handlers.
:param record: The record to prepare.'
| def prepare(self, record):
| return record
|
'Handle a record.
This just loops through the handlers offering them the record
to handle.
:param record: The record to handle.'
| def handle(self, record):
| record = self.prepare(record)
for handler in self.handlers:
handler.handle(record)
|
'Monitor the queue for records, and ask the handler
to deal with them.
This method runs on a separate, internal thread.
The thread will terminate if it sees a sentinel object in the queue.'
| def _monitor(self):
| q = self.queue
has_task_done = hasattr(q, 'task_done')
while (not self._stop.isSet()):
try:
record = self.dequeue(True)
if (record is self._sentinel):
break
self.handle(record)
if has_task_done:
q.task_done()
exc... |
'Writes a sentinel to the queue to tell the listener to quit. This
implementation uses ``put_nowait()``. You may want to override this
method if you want to use timeouts or work with custom queue
implementations.'
| def enqueue_sentinel(self):
| self.queue.put_nowait(self._sentinel)
|
'Stop the listener.
This asks the thread to terminate, and then waits for it to do so.
Note that if you don\'t call this before your application exits, there
may be some records still left on the queue, which won\'t be processed.'
| def stop(self):
| self._stop.set()
self.enqueue_sentinel()
self._thread.join()
self._thread = None
|
'Initialise an instance with the specified configuration
dictionary.'
| def __init__(self, config):
| self.config = ConvertingDict(config)
self.config.configurator = self
|
'Resolve strings to objects using standard import and attribute
syntax.'
| def resolve(self, s):
| name = s.split('.')
used = name.pop(0)
try:
found = self.importer(used)
for frag in name:
used += ('.' + frag)
try:
found = getattr(found, frag)
except AttributeError:
self.importer(used)
found = getattr(foun... |
'Default converter for the ext:// protocol.'
| def ext_convert(self, value):
| return self.resolve(value)
|
'Default converter for the cfg:// protocol.'
| def cfg_convert(self, value):
| rest = value
m = self.WORD_PATTERN.match(rest)
if (m is None):
raise ValueError(('Unable to convert %r' % value))
else:
rest = rest[m.end():]
d = self.config[m.groups()[0]]
while rest:
m = self.DOT_PATTERN.match(rest)
if m:
... |
'Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.'
| def convert(self, value):
| if ((not isinstance(value, ConvertingDict)) and isinstance(value, dict)):
value = ConvertingDict(value)
value.configurator = self
elif ((not isinstance(value, ConvertingList)) and isinstance(value, list)):
value = ConvertingList(value)
value.configurator = self
elif ((not isi... |
'Configure an object with a user-supplied factory.'
| def configure_custom(self, config):
| c = config.pop('()')
if isinstance(c, basestring):
c = self.resolve(c)
props = config.pop('.', None)
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
result = c(**kwargs)
if props:
for (name, value) in props.items():
setattr(result, name, value)
r... |
'Utility function which converts lists to tuples.'
| def as_tuple(self, value):
| if isinstance(value, list):
value = tuple(value)
return value
|
'Do the configuration.'
| def configure(self):
| config = self.config
if ('version' not in config):
raise ValueError("dictionary doesn't specify a version")
if (config['version'] != 1):
raise ValueError(('Unsupported version: %s' % config['version']))
incremental = config.pop('incremental', False)
EMPTY_DICT = {}
... |
'Configure a formatter from a dictionary.'
| def configure_formatter(self, config):
| if ('()' in config):
factory = config['()']
try:
result = self.configure_custom(config)
except TypeError:
te = sys.exc_info()[1]
if ("'format'" not in str(te)):
raise
config['fmt'] = config.pop('format')
config['()']... |
'Configure a filter from a dictionary.'
| def configure_filter(self, config):
| if ('()' in config):
result = self.configure_custom(config)
else:
name = config.get('name', '')
result = logging.Filter(name)
return result
|
'Add filters to a filterer from a list of names.'
| def add_filters(self, filterer, filters):
| for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError:
e = sys.exc_info()[1]
raise ValueError(('Unable to add filter %r: %s' % (f, e)))
|
'Configure a handler from a dictionary.'
| def configure_handler(self, config):
| formatter = config.pop('formatter', None)
if formatter:
try:
formatter = self.config['formatters'][formatter]
except StandardError:
e = sys.exc_info()[1]
raise ValueError(('Unable to set formatter %r: %s' % (formatter, e)))
level = config.po... |
'Add handlers to a logger from a list of names.'
| def add_handlers(self, logger, handlers):
| for h in handlers:
try:
logger.addHandler(self.config['handlers'][h])
except StandardError:
e = sys.exc_info()[1]
raise ValueError(('Unable to add handler %r: %s' % (h, e)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.