signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def reverse(self):
self._data.reverse()<EOL>
In place reversing of the :class:`Sequence` items.
f12145:c26:m11
def extend(self, iterable):
self._data.extend(iterable)<EOL>
Extends the :class:`Sequence` by appending items from the *iterable*. :param iterable: any *iterable* that contains items of :class:`Structure`, :class:`Sequence`, :class:`Array` or :class:`Field` instances. If the *iterable* is one of these instances itself then the *iterable* itself is appended to the :class:`Sequence`.
f12145:c26:m12
def append(self):
self._data.append()<EOL>
Appends a new :class:`Array` element to the :class:`Array`.
f12145:c27:m1
def insert(self, index):
self._data.insert(index)<EOL>
Inserts a new :class:`Array` element before the *index* of the :class:`Array`. :param int index: :class:`Array` index.
f12145:c27:m2
def resize(self, size):
if isinstance(self._data, Array):<EOL><INDENT>self._data.resize(size)<EOL><DEDENT>
Re-sizes the :class:`Array` by appending new :class:`Array` elements or removing :class:`Array` elements from the end. :param int size: new size of the :class:`Array` in number of :class:`Array` elements.
f12145:c27:m3
def resize(self, size):
if isinstance(self._data, Stream):<EOL><INDENT>self._data.resize(size)<EOL><DEDENT>
Re-sizes the :class:`Stream` field by appending zero bytes or removing bytes from the end. :param int size: :class:`Stream` size in number of bytes.
f12145:c28:m5
@property<EOL><INDENT>def address(self):<DEDENT>
return self._value + self.base_address<EOL>
Returns the *data source* address of the :attr:`data` object referenced by the `RelativePointer` field (read-only).
f12145:c31:m1
@property<EOL><INDENT>def base_address(self):<DEDENT>
return self.index.base_address<EOL>
Returns the *data source* base address of the :attr:`data` object relative referenced by the `RelativePointer` field (read-only).
f12145:c31:m2
def append(self, item):
self._data.append(item)<EOL>
Appends the *item* to the end of the :class:`Sequence`. :param item: any :class:`Structure`, :class:`Sequence`, :class:`Array` or :class:`Field` instance.
f12145:c33:m6
def insert(self, index, item):
self._data.insert(index, item)<EOL>
Inserts the *item* before the *index* into the :class:`Sequence`. :param int index: :class:`Sequence` index. :param item: any :class:`Structure`, :class:`Sequence`, :class:`Array` or :class:`Field` instance.
f12145:c33:m7
def pop(self, index=-<NUM_LIT:1>):
return self._data.pop(index)<EOL>
Removes and returns the item at the *index* from the :class:`Sequence`. :param int index: :class:`Sequence` index
f12145:c33:m8
def clear(self):
self._data.clear()<EOL>
Remove all items from the :class:`Sequence`.
f12145:c33:m9
def remove(self, item):
self._data.remove(item)<EOL>
Removes the first occurrence of an *item* from the :class:`Sequence`. :param item: any :class:`Structure`, :class:`Sequence`, :class:`Array` or :class:`Field` instance.
f12145:c33:m10
def reverse(self):
self._data.reverse()<EOL>
In place reversing of the :class:`Sequence` items.
f12145:c33:m11
def extend(self, iterable):
self._data.extend(iterable)<EOL>
Extends the :class:`Sequence` by appending items from the *iterable*. :param iterable: any *iterable* that contains items of :class:`Structure`, :class:`Sequence`, :class:`Array` or :class:`Field` instances. If the *iterable* is one of these instances itself then the *iterable* itself is appended to the :class:`Sequence`.
f12145:c33:m12
def append(self):
self._data.append()<EOL>
Appends a new :class:`Array` element to the :class:`Array`.
f12145:c34:m1
def insert(self, index):
self._data.insert(index)<EOL>
Inserts a new :class:`Array` element before the *index* of the :class:`Array`. :param int index: :class:`Array` index.
f12145:c34:m2
def resize(self, size):
if isinstance(self._data, Array):<EOL><INDENT>self._data.resize(size)<EOL><DEDENT>
Re-sizes the :class:`Array` by appending new :class:`Array` elements or removing :class:`Array` elements from the end. :param int size: new size of the :class:`Array` in number of :class:`Array` elements.
f12145:c34:m3
def resize(self, size):
if isinstance(self._data, Stream):<EOL><INDENT>self._data.resize(size)<EOL><DEDENT>
Re-sizes the :class:`Stream` field by appending zero bytes or removing bytes from the end. :param int size: :class:`Stream` size in number of bytes.
f12145:c35:m5
def d3flare_json(metadata, file=None, **options):
def convert(root):<EOL><INDENT>dct = OrderedDict()<EOL>item_type = root.get('<STR_LIT:type>')<EOL>dct['<STR_LIT:class>'] = root.get('<STR_LIT:class>')<EOL>dct['<STR_LIT:name>'] = root.get('<STR_LIT:name>')<EOL>if item_type is ItemClass.Field.name:<EOL><INDENT>dct['<STR_LIT:size>'] = root.get('<STR_LIT:size>')<EOL>dct['<STR_LIT:value>'] = root.get('<STR_LIT:value>')<EOL><DEDENT>children = root.get('<STR_LIT>')<EOL>if children:<EOL><INDENT>dct['<STR_LIT>'] = list()<EOL>if item_type is ItemClass.Pointer.name:<EOL><INDENT>field = OrderedDict()<EOL>field['<STR_LIT:class>'] = dct['<STR_LIT:class>']<EOL>field['<STR_LIT:name>'] = '<STR_LIT:*>' + dct['<STR_LIT:name>']<EOL>field['<STR_LIT:size>'] = root.get('<STR_LIT:size>')<EOL>field['<STR_LIT:value>'] = root.get('<STR_LIT:value>')<EOL>dct['<STR_LIT>'].append(field)<EOL><DEDENT>for child in map(convert, children):<EOL><INDENT>dct['<STR_LIT>'].append(child)<EOL><DEDENT><DEDENT>elif item_type is ItemClass.Pointer.name:<EOL><INDENT>dct['<STR_LIT:size>'] = root.get('<STR_LIT:size>')<EOL>dct['<STR_LIT:value>'] = root.get('<STR_LIT:value>')<EOL><DEDENT>return dct<EOL><DEDENT>options['<STR_LIT>'] = options.get('<STR_LIT>', <NUM_LIT:2>)<EOL>if file:<EOL><INDENT>return json.dump(convert(metadata), file, **options)<EOL><DEDENT>else:<EOL><INDENT>return json.dumps(convert(metadata), **options)<EOL><DEDENT>
Converts the *metadata* dictionary of a container or field into a ``flare.json`` formatted string or formatted stream written to the *file* The ``flare.json`` format is defined by the `d3.js <https://d3js.org/>`_ graphic library. The ``flare.json`` format looks like this: .. code-block:: JSON { "class": "class of the field or container", "name": "name of the field or container", "size": "bit size of the field", "value": "value of the field", "children": [] } :param dict metadata: metadata generated from a :class:`Structure`, :class:`Sequence`, :class:`Array` or any :class:`Field` instance. :param file file: file-like object.
f12146:m0
@property<EOL><INDENT>def columns(self):<DEDENT>
return self._columns<EOL>
Number of output columns.
f12146:c0:m1
@staticmethod<EOL><INDENT>def _view_area(stream=bytes(), index=<NUM_LIT:0>, count=<NUM_LIT:0>):<DEDENT>
<EOL>size = len(stream)<EOL>start = max(min(index, size), -size)<EOL>if start < <NUM_LIT:0>:<EOL><INDENT>start += size<EOL><DEDENT>if not count:<EOL><INDENT>count = size<EOL><DEDENT>if count > <NUM_LIT:0>:<EOL><INDENT>stop = min(start + count, size)<EOL><DEDENT>else:<EOL><INDENT>stop = size<EOL><DEDENT>return start, stop<EOL>
Returns the (start, stop) index for the viewing area of the byte stream. :param int index: start index of the viewing area. Default is the begin of the stream. :param int count: number of bytes to view. Default is to the end of the stream.
f12146:c0:m3
def file_dump(self, source, index=<NUM_LIT:0>, count=<NUM_LIT:0>, output=str()):
stream = open(source, '<STR_LIT:rb>').read()<EOL>self.dump(stream, index, count, output)<EOL>
Dumps the content of the *source* file to the console or to the optional given *output* file. :param str source: location and name of the source file. :param int index: optional start index of the viewing area in bytes. Default is from the begin of the file. :param int count: optional number of bytes to view. Default is to the end of the file. :param str output: location and name for the optional output file.
f12146:c0:m4
def dump(self, stream, index=<NUM_LIT:0>, count=<NUM_LIT:0>, output=str()):
def numerate(pattern, _count):<EOL><INDENT>return '<STR_LIT>'.join(pattern.format(x) for x in range(_count))<EOL><DEDENT>def write_to(file_handle, content):<EOL><INDENT>if file_handle:<EOL><INDENT>file_handle.write(content + "<STR_LIT:\n>")<EOL><DEDENT>else:<EOL><INDENT>print(content)<EOL><DEDENT><DEDENT>dst = None<EOL>if output:<EOL><INDENT>dst = open(output, '<STR_LIT:w>')<EOL><DEDENT>start, stop = self._view_area(stream, index, count)<EOL>digits = max(len(hex(start + stop)) - <NUM_LIT:2>, <NUM_LIT:8>)<EOL>write_to(dst,<EOL>"<STR_LIT:U+0020>" * digits +<EOL>"<STR_LIT>" +<EOL>numerate("<STR_LIT>", self.columns) +<EOL>"<STR_LIT>")<EOL>write_to(dst,<EOL>"<STR_LIT:->" * digits +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT:->" * (self.columns * <NUM_LIT:3>) +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT:->" * self.columns)<EOL>row = int(start / self.columns)<EOL>column = int(start % self.columns)<EOL>output_line = "<STR_LIT>".format(row * self.columns,<EOL>digits)<EOL>output_line += "<STR_LIT>" * column<EOL>output_ascii = "<STR_LIT:.>" * column<EOL>for value in stream[start:stop]:<EOL><INDENT>column += <NUM_LIT:1><EOL>output_line += "<STR_LIT>".format(int(value))<EOL>if value in range(<NUM_LIT:32>, <NUM_LIT>):<EOL><INDENT>output_ascii += "<STR_LIT>".format(value)<EOL><DEDENT>else:<EOL><INDENT>output_ascii += "<STR_LIT:.>"<EOL><DEDENT>column %= self.columns<EOL>if not column:<EOL><INDENT>output_line += '<STR_LIT>' + output_ascii<EOL>write_to(dst, output_line)<EOL>row += <NUM_LIT:1><EOL>output_line = "<STR_LIT>".format(row * self.columns,<EOL>digits)<EOL>output_ascii = "<STR_LIT>"<EOL><DEDENT><DEDENT>if column:<EOL><INDENT>output_line += "<STR_LIT:U+0020>" * (self.columns - column) * <NUM_LIT:3><EOL>output_line += "<STR_LIT>" + output_ascii<EOL>write_to(dst, output_line)<EOL><DEDENT>
Dumps the content of the byte *stream* to the console or to the optional given *output* file. :param bytes stream: byte stream to view. :param int index: optional start index of the viewing area in bytes. Default is the begin of the stream. :param int count: optional number of bytes to view. Default is to the end of the stream. :param str output: location and name for the optional output file.
f12146:c0:m5
def version(path):
version_file = read(path)<EOL>version_match = re.search(r"""<STR_LIT>""",<EOL>version_file, re.M)<EOL>if version_match:<EOL><INDENT>return version_match.group(<NUM_LIT:1>)<EOL><DEDENT>raise RuntimeError("<STR_LIT>")<EOL>
Obtain the package version from a python file e.g. pkg/__init__.py See <https://packaging.python.org/en/latest/single_source_version.html>.
f12148:m1
def find_empty_redis_database():
for dbnum in range(<NUM_LIT:4>, <NUM_LIT>):<EOL><INDENT>testconn = StrictRedis(db=dbnum)<EOL>empty = testconn.dbsize() == <NUM_LIT:0><EOL>if empty:<EOL><INDENT>return testconn<EOL><DEDENT><DEDENT>assert False, '<STR_LIT>'<EOL>
Tries to connect to a random Redis database (starting from 4), and will use/connect it when no keys are in there.
f12150:m0
def say_hello(name=None):
if name is None:<EOL><INDENT>name = '<STR_LIT>'<EOL><DEDENT>return '<STR_LIT>' % (name,)<EOL>
A job with a single argument and a return value.
f12151:m0
def register_death(self):
self.log.info('<STR_LIT>')<EOL>with self.connection.pipeline() as p:<EOL><INDENT>p.hset(self.scheduler_key, '<STR_LIT>', time.time())<EOL>p.expire(self.scheduler_key, <NUM_LIT>)<EOL>p.execute()<EOL><DEDENT>
Registers its own death.
f12153:c0:m2
def acquire_lock(self):
key = '<STR_LIT>' % self.scheduler_key<EOL>now = time.time()<EOL>expires = int(self._interval) + <NUM_LIT:10><EOL>self._lock_acquired = self.connection.set(<EOL>key, now, ex=expires, nx=True)<EOL>return self._lock_acquired<EOL>
Acquire lock before scheduling jobs to prevent another scheduler from scheduling jobs at the same time. This function returns True if a lock is acquired. False otherwise.
f12153:c0:m3
def remove_lock(self):
key = '<STR_LIT>' % self.scheduler_key<EOL>if self._lock_acquired:<EOL><INDENT>self.connection.delete(key)<EOL><DEDENT>
Remove acquired lock.
f12153:c0:m4
def _install_signal_handlers(self):
def stop(signum, frame):<EOL><INDENT>"""<STR_LIT>"""<EOL>self.log.info('<STR_LIT>')<EOL>self.register_death()<EOL>self.remove_lock()<EOL>raise SystemExit()<EOL><DEDENT>signal.signal(signal.SIGINT, stop)<EOL>signal.signal(signal.SIGTERM, stop)<EOL>
Installs signal handlers for handling SIGINT and SIGTERM gracefully.
f12153:c0:m5
def _create_job(self, func, args=None, kwargs=None, commit=True,<EOL>result_ttl=None, ttl=None, id=None, description=None,<EOL>queue_name=None, timeout=None, meta=None):
if args is None:<EOL><INDENT>args = ()<EOL><DEDENT>if kwargs is None:<EOL><INDENT>kwargs = {}<EOL><DEDENT>job = self.job_class.create(<EOL>func, args=args, connection=self.connection,<EOL>kwargs=kwargs, result_ttl=result_ttl, ttl=ttl, id=id,<EOL>description=description, timeout=timeout, meta=meta)<EOL>if self._queue is not None:<EOL><INDENT>job.origin = self._queue.name<EOL><DEDENT>else:<EOL><INDENT>job.origin = queue_name or self.queue_name<EOL><DEDENT>if commit:<EOL><INDENT>job.save()<EOL><DEDENT>return job<EOL>
Creates an RQ job and saves it to Redis.
f12153:c0:m6
def enqueue_at(self, scheduled_time, func, *args, **kwargs):
timeout = kwargs.pop('<STR_LIT>', None)<EOL>job_id = kwargs.pop('<STR_LIT>', None)<EOL>job_ttl = kwargs.pop('<STR_LIT>', None)<EOL>job_result_ttl = kwargs.pop('<STR_LIT>', None)<EOL>job_description = kwargs.pop('<STR_LIT>', None)<EOL>meta = kwargs.pop('<STR_LIT>', None)<EOL>job = self._create_job(func, args=args, kwargs=kwargs, timeout=timeout,<EOL>id=job_id, result_ttl=job_result_ttl, ttl=job_ttl,<EOL>description=job_description, meta=meta)<EOL>self.connection.zadd(self.scheduled_jobs_key,<EOL>{job.id: to_unix(scheduled_time)})<EOL>return job<EOL>
Pushes a job to the scheduler queue. The scheduled queue is a Redis sorted set ordered by timestamp - which in this case is job's scheduled execution time. All args and kwargs are passed onto the job, except for the following kwarg keys (which affect the job creation itself): - timeout - job_id - job_ttl - job_result_ttl - job_description Usage: from datetime import datetime from redis import Redis from rq.scheduler import Scheduler from foo import func redis = Redis() scheduler = Scheduler(queue_name='default', connection=redis) scheduler.enqueue_at(datetime(2020, 1, 1), func, 'argument', keyword='argument')
f12153:c0:m7
def enqueue_in(self, time_delta, func, *args, **kwargs):
timeout = kwargs.pop('<STR_LIT>', None)<EOL>job_id = kwargs.pop('<STR_LIT>', None)<EOL>job_ttl = kwargs.pop('<STR_LIT>', None)<EOL>job_result_ttl = kwargs.pop('<STR_LIT>', None)<EOL>job_description = kwargs.pop('<STR_LIT>', None)<EOL>meta = kwargs.pop('<STR_LIT>', None)<EOL>job = self._create_job(func, args=args, kwargs=kwargs, timeout=timeout,<EOL>id=job_id, result_ttl=job_result_ttl, ttl=job_ttl,<EOL>description=job_description, meta=meta)<EOL>self.connection.zadd(self.scheduled_jobs_key,<EOL>{job.id: to_unix(datetime.utcnow() + time_delta)})<EOL>return job<EOL>
Similar to ``enqueue_at``, but accepts a timedelta instead of datetime object. The job's scheduled execution time will be calculated by adding the timedelta to datetime.utcnow().
f12153:c0:m8
def schedule(self, scheduled_time, func, args=None, kwargs=None,<EOL>interval=None, repeat=None, result_ttl=None, ttl=None,<EOL>timeout=None, id=None, description=None, queue_name=None,<EOL>meta=None):
<EOL>if interval is not None and result_ttl is None:<EOL><INDENT>result_ttl = -<NUM_LIT:1><EOL><DEDENT>job = self._create_job(func, args=args, kwargs=kwargs, commit=False,<EOL>result_ttl=result_ttl, ttl=ttl, id=id,<EOL>description=description, queue_name=queue_name,<EOL>timeout=timeout, meta=meta)<EOL>if interval is not None:<EOL><INDENT>job.meta['<STR_LIT>'] = int(interval)<EOL><DEDENT>if repeat is not None:<EOL><INDENT>job.meta['<STR_LIT>'] = int(repeat)<EOL><DEDENT>if repeat and interval is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>job.save()<EOL>self.connection.zadd(self.scheduled_jobs_key,<EOL>{job.id: to_unix(scheduled_time)})<EOL>return job<EOL>
Schedule a job to be periodically executed, at a certain interval.
f12153:c0:m9
def cron(self, cron_string, func, args=None, kwargs=None, repeat=None,<EOL>queue_name=None, id=None, timeout=None, description=None, meta=None):
scheduled_time = get_next_scheduled_time(cron_string)<EOL>job = self._create_job(func, args=args, kwargs=kwargs, commit=False,<EOL>result_ttl=-<NUM_LIT:1>, id=id, queue_name=queue_name,<EOL>description=description, timeout=timeout, meta=meta)<EOL>job.meta['<STR_LIT>'] = cron_string<EOL>if repeat is not None:<EOL><INDENT>job.meta['<STR_LIT>'] = int(repeat)<EOL><DEDENT>job.save()<EOL>self.connection.zadd(self.scheduled_jobs_key,<EOL>{job.id: to_unix(scheduled_time)})<EOL>return job<EOL>
Schedule a cronjob
f12153:c0:m10
def cancel(self, job):
if isinstance(job, self.job_class):<EOL><INDENT>self.connection.zrem(self.scheduled_jobs_key, job.id)<EOL><DEDENT>else:<EOL><INDENT>self.connection.zrem(self.scheduled_jobs_key, job)<EOL><DEDENT>
Pulls a job from the scheduler queue. This function accepts either a job_id or a job instance.
f12153:c0:m11
def __contains__(self, item):
job_id = item<EOL>if isinstance(item, self.job_class):<EOL><INDENT>job_id = item.id<EOL><DEDENT>return self.connection.zscore(self.scheduled_jobs_key, job_id) is not None<EOL>
Returns a boolean indicating whether the given job instance or job id is scheduled for execution.
f12153:c0:m12
def change_execution_time(self, job, date_time):
with self.connection.pipeline() as pipe:<EOL><INDENT>while <NUM_LIT:1>:<EOL><INDENT>try:<EOL><INDENT>pipe.watch(self.scheduled_jobs_key)<EOL>if pipe.zscore(self.scheduled_jobs_key, job.id) is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>pipe.zadd(self.scheduled_jobs_key, {job.id: to_unix(date_time)})<EOL>break<EOL><DEDENT>except WatchError:<EOL><INDENT>if pipe.zscore(self.scheduled_jobs_key, job.id) is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>continue<EOL><DEDENT><DEDENT><DEDENT>
Change a job's execution time.
f12153:c0:m13
def count(self, until=None):
until = rationalize_until(until)<EOL>return self.connection.zcount(self.scheduled_jobs_key, <NUM_LIT:0>, until)<EOL>
Returns the total number of jobs that are scheduled for all queues. This function accepts datetime, timedelta instances as well as integers representing epoch values.
f12153:c0:m14
def get_jobs(self, until=None, with_times=False, offset=None, length=None):
def epoch_to_datetime(epoch):<EOL><INDENT>return from_unix(float(epoch))<EOL><DEDENT>until = rationalize_until(until)<EOL>job_ids = self.connection.zrangebyscore(self.scheduled_jobs_key, <NUM_LIT:0>,<EOL>until, withscores=with_times,<EOL>score_cast_func=epoch_to_datetime,<EOL>start=offset, num=length)<EOL>if not with_times:<EOL><INDENT>job_ids = zip(job_ids, repeat(None))<EOL><DEDENT>for job_id, sched_time in job_ids:<EOL><INDENT>job_id = job_id.decode('<STR_LIT:utf-8>')<EOL>try:<EOL><INDENT>job = self.job_class.fetch(job_id, connection=self.connection)<EOL><DEDENT>except NoSuchJobError:<EOL><INDENT>self.cancel(job_id)<EOL>continue<EOL><DEDENT>if with_times:<EOL><INDENT>yield (job, sched_time)<EOL><DEDENT>else:<EOL><INDENT>yield job<EOL><DEDENT><DEDENT>
Returns a iterator of job instances that will be queued until the given time. If no 'until' argument is given all jobs are returned. If with_times is True, a list of tuples consisting of the job instance and it's scheduled execution time is returned. If offset and length are specified, a slice of the list starting at the specified zero-based offset of the specified length will be returned. If either of offset or length is specified, then both must be, or an exception will be raised.
f12153:c0:m15
def get_jobs_to_queue(self, with_times=False):
return self.get_jobs(to_unix(datetime.utcnow()), with_times=with_times)<EOL>
Returns a list of job instances that should be queued (score lower than current timestamp). If with_times is True a list of tuples consisting of the job instance and it's scheduled execution time is returned.
f12153:c0:m16
def get_queue_for_job(self, job):
if self._queue is not None:<EOL><INDENT>return self._queue<EOL><DEDENT>key = '<STR_LIT>'.format(self.queue_class.redis_queue_namespace_prefix,<EOL>job.origin)<EOL>return self.queue_class.from_queue_key(<EOL>key, connection=self.connection, job_class=self.job_class)<EOL>
Returns a queue to put job into.
f12153:c0:m17
def enqueue_job(self, job):
self.log.debug('<STR_LIT>'.format(job.id, job.origin))<EOL>interval = job.meta.get('<STR_LIT>', None)<EOL>repeat = job.meta.get('<STR_LIT>', None)<EOL>cron_string = job.meta.get('<STR_LIT>', None)<EOL>if repeat:<EOL><INDENT>job.meta['<STR_LIT>'] = int(repeat) - <NUM_LIT:1><EOL><DEDENT>queue = self.get_queue_for_job(job)<EOL>queue.enqueue_job(job)<EOL>self.connection.zrem(self.scheduled_jobs_key, job.id)<EOL>if interval:<EOL><INDENT>if repeat is not None:<EOL><INDENT>if job.meta['<STR_LIT>'] == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT><DEDENT>self.connection.zadd(self.scheduled_jobs_key,<EOL>{job.id: to_unix(datetime.utcnow()) + int(interval)})<EOL><DEDENT>elif cron_string:<EOL><INDENT>if repeat is not None:<EOL><INDENT>if job.meta['<STR_LIT>'] == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT><DEDENT>self.connection.zadd(self.scheduled_jobs_key,<EOL>{job.id: to_unix(get_next_scheduled_time(cron_string))})<EOL><DEDENT>
Move a scheduled job to a queue. In addition, it also does puts the job back into the scheduler if needed.
f12153:c0:m18
def enqueue_jobs(self):
self.log.debug('<STR_LIT>')<EOL>jobs = self.get_jobs_to_queue()<EOL>for job in jobs:<EOL><INDENT>self.enqueue_job(job)<EOL><DEDENT>self.connection.expire(self.scheduler_key, int(self._interval) + <NUM_LIT:10>)<EOL>return jobs<EOL>
Move scheduled jobs into queues.
f12153:c0:m19
def run(self, burst=False):
self.register_birth()<EOL>self._install_signal_handlers()<EOL>try:<EOL><INDENT>while True:<EOL><INDENT>self.log.debug("<STR_LIT>")<EOL>start_time = time.time()<EOL>if self.acquire_lock():<EOL><INDENT>self.enqueue_jobs()<EOL>self.remove_lock()<EOL>if burst:<EOL><INDENT>self.log.info('<STR_LIT>')<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.warning('<STR_LIT>')<EOL><DEDENT>seconds_elapsed_since_start = time.time() - start_time<EOL>seconds_until_next_scheduled_run = self._interval - seconds_elapsed_since_start<EOL>if seconds_until_next_scheduled_run > <NUM_LIT:0>:<EOL><INDENT>self.log.debug("<STR_LIT>" % seconds_until_next_scheduled_run)<EOL>time.sleep(seconds_until_next_scheduled_run)<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>self.remove_lock()<EOL>self.register_death()<EOL><DEDENT>
Periodically check whether there's any job that should be put in the queue (score lower than current time).
f12153:c0:m20
def from_unix(string):
return datetime.utcfromtimestamp(float(string))<EOL>
Convert a unix timestamp into a utc datetime
f12155:m0
def to_unix(dt):
return calendar.timegm(dt.utctimetuple())<EOL>
Converts a datetime object to unixtime
f12155:m1
def get_next_scheduled_time(cron_string):
itr = croniter.croniter(cron_string, datetime.utcnow())<EOL>return itr.get_next(datetime)<EOL>
Calculate the next scheduled time by creating a crontab object with a cron string
f12155:m2
def rationalize_until(until=None):
if until is None:<EOL><INDENT>until = "<STR_LIT>"<EOL><DEDENT>elif isinstance(until, datetime):<EOL><INDENT>until = to_unix(until)<EOL><DEDENT>elif isinstance(until, timedelta):<EOL><INDENT>until = to_unix((datetime.utcnow() + until))<EOL><DEDENT>return until<EOL>
Rationalizes the `until` argument used by other functions. This function accepts datetime and timedelta instances as well as integers representing epoch values.
f12155:m4
def __init__(self, area_code, service_key, mobile_os='<STR_LIT>', app_name='<STR_LIT>'):
self.tour_list_url = _URLS['<STR_LIT>'].format(area_code, service_key, mobile_os, app_name) + '<STR_LIT>'<EOL>self.detail_common_url = _URLS['<STR_LIT>'].format(area_code, service_key, mobile_os, app_name) + '<STR_LIT>'<EOL>self.detail_intro_url = _URLS['<STR_LIT>'].format(area_code, service_key, mobile_os, app_name) + '<STR_LIT>'<EOL>self.additional_images_url = _URLS['<STR_LIT>'].format(area_code, service_key, mobile_os, app_name) + '<STR_LIT>'<EOL>
:param area_code: Area code to initialize API :param service_key: Service code from data.go.kr :param mobile_os: Application os(AND, IOS, ETC) :param app_name: Service name :type area_code: int :type service_key: str :type mobile_os: str :type app_name: str
f12159:c1:m0
def get_tour_list(self):
resp = json.loads(urlopen(self.tour_list_url.format(<NUM_LIT:1>)).read().decode('<STR_LIT:utf-8>'))<EOL>total_count = resp['<STR_LIT>']['<STR_LIT:body>']['<STR_LIT>']<EOL>resp = json.loads(urlopen(self.tour_list_url.format(total_count)).read().decode('<STR_LIT:utf-8>'))<EOL>data = resp['<STR_LIT>']['<STR_LIT:body>']['<STR_LIT>']['<STR_LIT>']<EOL>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT:title>': ('<STR_LIT:title>', None),<EOL>'<STR_LIT>': ('<STR_LIT:address>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT:x>', None),<EOL>'<STR_LIT>': ('<STR_LIT:y>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', <NUM_LIT:0>),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT:image>', None),<EOL>}<EOL>for tour in data:<EOL><INDENT>_dict_key_changer(tour, keychain)<EOL>tour['<STR_LIT>'] = str(tour.pop('<STR_LIT>'))[:<NUM_LIT:8>] if '<STR_LIT>' in tour else None<EOL>tour['<STR_LIT>'] = str(tour.pop('<STR_LIT>'))[:<NUM_LIT:8>] if '<STR_LIT>' in tour else None<EOL>tour.pop('<STR_LIT>', None)<EOL>tour.pop('<STR_LIT>', None)<EOL>tour.pop('<STR_LIT>', None)<EOL><DEDENT>return data<EOL>
Inquire all tour list :rtype: list
f12159:c1:m1
def get_detail_common(self, content_id):
resp = json.loads(urlopen(self.detail_common_url.format(str(content_id))).read().decode('<STR_LIT:utf-8>'))<EOL>data = resp['<STR_LIT>']['<STR_LIT:body>']['<STR_LIT>']['<STR_LIT>']<EOL>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', <NUM_LIT:0>)<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL>try:<EOL><INDENT>data['<STR_LIT>'] = re.findall('<STR_LIT>', data.pop('<STR_LIT>'))[<NUM_LIT:0>] if '<STR_LIT>' in data else None<EOL><DEDENT>except IndexError:<EOL><INDENT>data['<STR_LIT>'] = None<EOL><DEDENT>data.pop('<STR_LIT>', None)<EOL>data.pop('<STR_LIT:title>', None)<EOL>data.pop('<STR_LIT>', None)<EOL>data.pop('<STR_LIT>', None)<EOL>return data<EOL>
Inquire common detail data :param content_id: Content ID to inquire :type content_id: str :rtype: dict
f12159:c1:m2
def get_detail_intro(self, content_id):
content_type_id = self.get_detail_common(content_id)['<STR_LIT>']<EOL>resp = json.loads(urlopen(self.detail_intro_url.format(content_id, content_type_id)).read().decode('<STR_LIT:utf-8>'))<EOL>data = resp['<STR_LIT>']['<STR_LIT:body>']['<STR_LIT>']['<STR_LIT>']<EOL>del data['<STR_LIT>']<EOL>del data['<STR_LIT>']<EOL>if content_type_id == <NUM_LIT:12>:<EOL><INDENT>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None)<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', None) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', None) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', None) == <NUM_LIT:1><EOL><DEDENT>elif content_type_id == <NUM_LIT>:<EOL><INDENT>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None)<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL><DEDENT>elif content_type_id == <NUM_LIT:15>:<EOL><INDENT>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT:host>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None)<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL>data.pop('<STR_LIT>', None)<EOL><DEDENT>elif content_type_id == <NUM_LIT>:<EOL><INDENT>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None)<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL><DEDENT>elif content_type_id == <NUM_LIT>:<EOL><INDENT>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL><DEDENT>elif content_type_id == <NUM_LIT:32>:<EOL><INDENT>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None)<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', False) == <NUM_LIT:1><EOL><DEDENT>elif content_type_id == <NUM_LIT>:<EOL><INDENT>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None)<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL><DEDENT>elif content_type_id == <NUM_LIT>:<EOL><INDENT>keychain = {<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None),<EOL>'<STR_LIT>': ('<STR_LIT>', None)<EOL>}<EOL>_dict_key_changer(data, keychain)<EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>') == <NUM_LIT:1> if '<STR_LIT>' in data else False<EOL><DEDENT>return data<EOL>
Inquire detail introduction :param content_id: Content ID to inquire :type content_id: str :rtype: dict
f12159:c1:m3
def get_detail_images(self, content_id):
resp = json.loads(urlopen(self.additional_images_url.format(content_id, <NUM_LIT:1>)).read().decode('<STR_LIT:utf-8>'))<EOL>total_count = resp['<STR_LIT>']['<STR_LIT:body>']['<STR_LIT>']<EOL>resp = json.loads(urlopen(self.additional_images_url.format(content_id, total_count)).read().decode('<STR_LIT:utf-8>'))<EOL>try:<EOL><INDENT>data = resp['<STR_LIT>']['<STR_LIT:body>']['<STR_LIT>']['<STR_LIT>']<EOL>if type(data) is dict:<EOL><INDENT>data.pop('<STR_LIT>', None)<EOL>data.pop('<STR_LIT>', None)<EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', None)<EOL>data['<STR_LIT>'] = data.pop('<STR_LIT>', None)<EOL><DEDENT>else:<EOL><INDENT>for img in data:<EOL><INDENT>if type(img) is dict:<EOL><INDENT>img.pop('<STR_LIT>', None)<EOL>img.pop('<STR_LIT>', None)<EOL>img['<STR_LIT>'] = img.pop('<STR_LIT>', None)<EOL>img['<STR_LIT>'] = img.pop('<STR_LIT>', None)<EOL><DEDENT>else:<EOL><INDENT>del img<EOL><DEDENT><DEDENT><DEDENT>return data if type(data) is list else [data]<EOL><DEDENT>except TypeError:<EOL><INDENT>return None<EOL><DEDENT>
Inquire detail images :param content_id: Content ID to inquire :type content_id: str :rtype: list
f12159:c1:m4
def mechanize_oauth2_approval(url):
br = mechanize.Browser()<EOL>br.open(url)<EOL>br.select_form(nr=<NUM_LIT:0>)<EOL>br["<STR_LIT>"] = username<EOL>br["<STR_LIT>"] = password<EOL>try:<EOL><INDENT>response1 = br.submit()<EOL>br.select_form(nr=<NUM_LIT:0>)<EOL>response2 = br.submit()<EOL><DEDENT>except Exception as e:<EOL><INDENT>pass<EOL><DEDENT>callback_url = br.geturl()<EOL>return callback_url.split('<STR_LIT>')[<NUM_LIT:1>]<EOL>
general process is: 1. assume user isn't logged in, so get redirected to google accounts login page. login using account credentials But, if the user has already granted access, the user is auto redirected without having to confirm again. 2. redirected back to oauth approval page. br.submit() should choose the first submit on that page, which is the "Accept" button 3. mechanize follows the redirect, and should throw 40X exception and we return the token
f12163:m1
def automated_oauth2_approval(url):
auth_url = url<EOL>headers = {'<STR_LIT>': auth_url}<EOL>s = requests.Session()<EOL>r1 = s.get(auth_url)<EOL>post_data = dict((x[<NUM_LIT:0>],x[<NUM_LIT:1>]) for x in re.findall('<STR_LIT>', str(r1.content), re.MULTILINE))<EOL>post_data['<STR_LIT>'] = username<EOL>post_data['<STR_LIT>'] = password<EOL>post_data['<STR_LIT>'] = '<STR_LIT>'<EOL>post_data['<STR_LIT>'] = '<STR_LIT>'<EOL>post_data['<STR_LIT>'] = '<STR_LIT>'<EOL>post_data['<STR_LIT>'] = s.cookies['<STR_LIT>']<EOL>r2 = s.post('<STR_LIT>', data=post_data, headers=headers, allow_redirects=False)<EOL>scope_url = r2.headers['<STR_LIT:location>'].replace('<STR_LIT>','<STR_LIT>')<EOL>r3 = s.get(scope_url)<EOL>if '<STR_LIT>' in r3.url:<EOL><INDENT>code = r3.url.split('<STR_LIT:=>')[<NUM_LIT:1>]<EOL>return code<EOL><DEDENT>post_data = dict((x[<NUM_LIT:0>],x[<NUM_LIT:1>]) for x in re.findall('<STR_LIT>', str(r3.content)))<EOL>post_data['<STR_LIT>'] = '<STR_LIT:true>'<EOL>post_data['<STR_LIT>'] = '<STR_LIT>'<EOL>action_url = re.findall('<STR_LIT>', str(r3.content))[<NUM_LIT:0>].replace('<STR_LIT>','<STR_LIT>')<EOL>r4 = s.post(action_url, data=post_data, headers=headers, allow_redirects=False)<EOL>code = r4.headers['<STR_LIT>'].split('<STR_LIT:=>')[<NUM_LIT:1>]<EOL>s.close()<EOL>return code<EOL>
general process is: 1. assume user isn't logged in, so get redirected to google accounts login page. login using account credentials 2. get redirected to oauth approval screen 3. authorize oauth app
f12163:m2
def toJSON(self):
pass<EOL>
TODO: build a json object to return via ajax
f12165:c0:m4
def getFeeds(self):
return self.feeds<EOL>
@Deprecated, see getSubscriptionList
f12165:c0:m5
def getSubscriptionList(self):
return self.feeds<EOL>
Returns a list of Feed objects containing all of a users subscriptions or None if buildSubscriptionList has not been called, to get the Feeds
f12165:c0:m6
def getCategories(self):
return self.categories<EOL>
Returns a list of all the categories or None if buildSubscriptionList has not been called, to get the Feeds
f12165:c0:m7
def buildSubscriptionList(self):
self._clearLists()<EOL>unreadById = {}<EOL>if not self.userId:<EOL><INDENT>self.getUserInfo()<EOL><DEDENT>unreadJson = self.httpGet(ReaderUrl.UNREAD_COUNT_URL, { '<STR_LIT>': '<STR_LIT>', })<EOL>unreadCounts = json.loads(unreadJson, strict=False)['<STR_LIT>']<EOL>for unread in unreadCounts:<EOL><INDENT>unreadById[unread['<STR_LIT:id>']] = unread['<STR_LIT:count>']<EOL><DEDENT>feedsJson = self.httpGet(ReaderUrl.SUBSCRIPTION_LIST_URL, { '<STR_LIT>': '<STR_LIT>', })<EOL>subscriptions = json.loads(feedsJson, strict=False)['<STR_LIT>']<EOL>for sub in subscriptions:<EOL><INDENT>categories = []<EOL>if '<STR_LIT>' in sub:<EOL><INDENT>for hCategory in sub['<STR_LIT>']:<EOL><INDENT>cId = hCategory['<STR_LIT:id>']<EOL>if not cId in self.categoriesById:<EOL><INDENT>category = Category(self, hCategory['<STR_LIT:label>'], cId)<EOL>self._addCategory(category)<EOL><DEDENT>categories.append(self.categoriesById[cId])<EOL><DEDENT><DEDENT>try:<EOL><INDENT>feed = self.getFeed(sub['<STR_LIT:id>'])<EOL>if not feed:<EOL><INDENT>raise<EOL><DEDENT>if not feed.title:<EOL><INDENT>feed.title = sub['<STR_LIT:title>']<EOL><DEDENT>for category in categories:<EOL><INDENT>feed.addCategory(category)<EOL><DEDENT>feed.unread = unreadById.get(sub['<STR_LIT:id>'], <NUM_LIT:0>)<EOL><DEDENT>except:<EOL><INDENT>feed = Feed(self,<EOL>sub['<STR_LIT:title>'],<EOL>sub['<STR_LIT:id>'],<EOL>sub.get('<STR_LIT>', None),<EOL>unreadById.get(sub['<STR_LIT:id>'], <NUM_LIT:0>),<EOL>categories)<EOL><DEDENT>if not categories:<EOL><INDENT>self.orphanFeeds.append(feed)<EOL><DEDENT>self._addFeed(feed)<EOL><DEDENT>specialUnreads = [id for id in unreadById<EOL>if id.find('<STR_LIT>' % self.userId) != -<NUM_LIT:1>]<EOL>for type in self.specialFeeds:<EOL><INDENT>feed = self.specialFeeds[type]<EOL>feed.unread = <NUM_LIT:0><EOL>for id in specialUnreads:<EOL><INDENT>if id.endswith('<STR_LIT>' % type):<EOL><INDENT>feed.unread = unreadById.get(id, <NUM_LIT:0>)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>return True<EOL>
Hits Google Reader for a users's alphabetically ordered list of feeds. Returns true if succesful.
f12165:c0:m10
def _getFeedContent(self, url, excludeRead=False, continuation=None, loadLimit=<NUM_LIT:20>, since=None, until=None):
parameters = {}<EOL>if excludeRead:<EOL><INDENT>parameters['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if continuation:<EOL><INDENT>parameters['<STR_LIT:c>'] = continuation<EOL><DEDENT>parameters['<STR_LIT:n>'] = loadLimit<EOL>if since:<EOL><INDENT>parameters['<STR_LIT>'] = since<EOL><DEDENT>if until:<EOL><INDENT>parameters['<STR_LIT>'] = until<EOL><DEDENT>contentJson = self.httpGet(url, parameters)<EOL>return json.loads(contentJson, strict=False)<EOL>
A list of items (from a feed, a category or from URLs made with SPECIAL_ITEMS_URL) Returns a dict with :param id: (str, feed's id) :param continuation: (str, to be used to fetch more items) :param items: array of dits with : - update (update timestamp) - author (str, username) - title (str, page title) - id (str) - content (dict with content and direction) - categories (list of categories including states or ones provided by the feed owner)
f12165:c0:m11
def getFeedContent(self, feed, excludeRead=False, continuation=None, loadLimit=<NUM_LIT:20>, since=None, until=None):
return self._getFeedContent(feed.fetchUrl, excludeRead, continuation, loadLimit, since, until)<EOL>
Return items for a particular feed
f12165:c0:m13
def getCategoryContent(self, category, excludeRead=False, continuation=None, loadLimit=<NUM_LIT:20>, since=None, until=None):
return self._getFeedContent(category.fetchUrl, excludeRead, continuation, loadLimit, since, until)<EOL>
Return items for a particular category
f12165:c0:m14
def _modifyItemTag(self, item_id, action, tag):
return self.httpPost(ReaderUrl.EDIT_TAG_URL,<EOL>{'<STR_LIT:i>': item_id, action: tag, '<STR_LIT>': '<STR_LIT>'})<EOL>
wrapper around actual HTTP POST string for modify tags
f12165:c0:m15
def removeItemTag(self, item, tag):
return self._modifyItemTag(item.id, '<STR_LIT:r>', tag)<EOL>
Remove a tag to an individal item. tag string must be in form "user/-/label/[tag]"
f12165:c0:m16
def addItemTag(self, item, tag):
if self.inItemTagTransaction:<EOL><INDENT>if not tag in self.addTagBacklog:<EOL><INDENT>self.addTagBacklog[tag] = [] <EOL><DEDENT>self.addTagBacklog[tag].append({'<STR_LIT:i>': item.id, '<STR_LIT:s>': item.parent.id})<EOL>return "<STR_LIT:OK>"<EOL><DEDENT>else:<EOL><INDENT>return self._modifyItemTag(item.id, '<STR_LIT:a>', tag)<EOL><DEDENT>
Add a tag to an individal item. tag string must be in form "user/-/label/[tag]"
f12165:c0:m18
def subscribe(self, feedUrl):
response = self.httpPost(<EOL>ReaderUrl.SUBSCRIPTION_EDIT_URL,<EOL>{'<STR_LIT>':'<STR_LIT>', '<STR_LIT:s>': feedUrl})<EOL>if response and '<STR_LIT:OK>' in response:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>
Adds a feed to the top-level subscription list Ubscribing seems idempotent, you can subscribe multiple times without error returns True or throws HTTPError
f12165:c0:m21
def unsubscribe(self, feedUrl):
response = self.httpPost(<EOL>ReaderUrl.SUBSCRIPTION_EDIT_URL,<EOL>{'<STR_LIT>':'<STR_LIT>', '<STR_LIT:s>': feedUrl})<EOL>if response and '<STR_LIT:OK>' in response:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>
Removes a feed url from the top-level subscription list Unsubscribing seems idempotent, you can unsubscribe multiple times without error returns True or throws HTTPError
f12165:c0:m22
def getUserInfo(self):
userJson = self.httpGet(ReaderUrl.USER_INFO_URL)<EOL>result = json.loads(userJson, strict=False)<EOL>self.userId = result['<STR_LIT>']<EOL>return result<EOL>
Returns a dictionary of user info that google stores.
f12165:c0:m23
def getUserSignupDate(self):
userinfo = self.getUserInfo()<EOL>timestamp = int(float(userinfo["<STR_LIT>"]))<EOL>return time.strftime("<STR_LIT>", time.gmtime(timestamp))<EOL>
Returns the human readable date of when the user signed up for google reader.
f12165:c0:m24
def httpGet(self, url, parameters=None):
return self.auth.get(url, parameters)<EOL>
Wrapper around AuthenticationMethod get()
f12165:c0:m25
def httpPost(self, url, post_parameters=None):
return self.auth.post(url, post_parameters)<EOL>
Wrapper around AuthenticationMethod post()
f12165:c0:m26
def _clearLists(self):
self.feedsById = {}<EOL>self.feeds = []<EOL>self.categoriesById = {}<EOL>self.categories = []<EOL>self.orphanFeeds = []<EOL>
Clear all list before sync : feeds and categories
f12165:c0:m31
def get(self, url, parameters=None):
getString = self.getParameters(parameters)<EOL>headers = {'<STR_LIT>':'<STR_LIT>' % self.auth_token}<EOL>req = requests.get(url + "<STR_LIT:?>" + getString, headers=headers)<EOL>return req.text<EOL>
Convenience method for requesting to google with proper cookies/params.
f12166:c1:m2
def post(self, url, postParameters=None, urlParameters=None):
if urlParameters:<EOL><INDENT>url = url + "<STR_LIT:?>" + self.getParameters(urlParameters)<EOL><DEDENT>headers = {'<STR_LIT>':'<STR_LIT>' % self.auth_token,<EOL>'<STR_LIT:Content-Type>': '<STR_LIT>'<EOL>}<EOL>postString = self.postParameters(postParameters)<EOL>req = requests.post(url, data=postString, headers=headers)<EOL>return req.text<EOL>
Convenience method for requesting to google with proper cookies/params.
f12166:c1:m3
def _getAuth(self):
parameters = {<EOL>'<STR_LIT>' : '<STR_LIT>',<EOL>'<STR_LIT>' : self.username,<EOL>'<STR_LIT>' : self.password,<EOL>'<STR_LIT>' : '<STR_LIT>'}<EOL>req = requests.post(ClientAuthMethod.CLIENT_URL, data=parameters)<EOL>if req.status_code != <NUM_LIT:200>:<EOL><INDENT>raise IOError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>data = req.text<EOL>token_dict = dict(x.split('<STR_LIT:=>') for x in data.split('<STR_LIT:\n>') if x)<EOL>return token_dict["<STR_LIT>"]<EOL>
Main step in authorizing with Reader. Sends request to Google ClientAuthMethod URL which returns an Auth token. Returns Auth token or raises IOError on error.
f12166:c1:m4
def _getToken(self):
headers = {'<STR_LIT>':'<STR_LIT>' % self.auth_token}<EOL>req = requests.get(ReaderUrl.API_URL + '<STR_LIT>', headers=headers)<EOL>if req.status_code != <NUM_LIT:200>:<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>return req.content<EOL>
Second step in authorizing with Reader. Sends authorized request to Reader token URL and returns a token value. Returns token or raises IOError on error.
f12166:c1:m5
def post(self, url, postParameters=None, urlParameters=None):
if self.authorized_client:<EOL><INDENT>if urlParameters:<EOL><INDENT>getString = self.getParameters(urlParameters)<EOL>req = urllib2.Request(url + "<STR_LIT:?>" + getString)<EOL><DEDENT>else:<EOL><INDENT>req = urllib2.Request(url)<EOL><DEDENT>postString = self.postParameters(postParameters)<EOL>resp,content = self.authorized_client.request(req, method="<STR_LIT:POST>", body=postString)<EOL>return toUnicode(content)<EOL><DEDENT>else:<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>
Convenience method for requesting to google with proper cookies/params.
f12166:c2:m10
def setActionToken(self):
self.action_token = self.get(ReaderUrl.ACTION_TOKEN_URL)<EOL>
Get action to prevent XSRF attacks http://code.google.com/p/google-reader-api/wiki/ActionToken TODO: mask token expiring? handle regenerating?
f12166:c3:m3
def get(self, url, parameters=None):
if not self.access_token:<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>if parameters is None:<EOL><INDENT>parameters = {}<EOL><DEDENT>parameters.update({'<STR_LIT>': self.access_token, '<STR_LIT>': '<STR_LIT>'})<EOL>request = requests.get(url + '<STR_LIT:?>' + self.getParameters(parameters))<EOL>if request.status_code != <NUM_LIT:200>:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return toUnicode(request.text)<EOL><DEDENT>
Convenience method for requesting to google with proper cookies/params.
f12166:c3:m6
def post(self, url, postParameters=None, urlParameters=None):
if not self.access_token:<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>if not self.action_token:<EOL><INDENT>raise IOError("<STR_LIT>")<EOL><DEDENT>if urlParameters is None:<EOL><INDENT>urlParameters = {}<EOL><DEDENT>headers = {'<STR_LIT>': '<STR_LIT>' + self.access_token,<EOL>'<STR_LIT:Content-Type>': '<STR_LIT>'}<EOL>postParameters.update({'<STR_LIT:T>':self.action_token})<EOL>request = requests.post(url + '<STR_LIT:?>' + self.getParameters(urlParameters),<EOL>data=postParameters, headers=headers)<EOL>if request.status_code != <NUM_LIT:200>:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return toUnicode(request.text)<EOL><DEDENT>
Convenience method for requesting to google with proper cookies/params.
f12166:c3:m7
def __init__(self, credentials):
if not has_httplib2:<EOL><INDENT>raise ImportError("<STR_LIT>")<EOL><DEDENT>super(GAPDecoratorAuthMethod, self).__init__()<EOL>self._http = None<EOL>self._credentials = credentials<EOL>self._action_token = None<EOL>
Initialize auth method with existing credentials. Args: credentials: OAuth2 credentials obtained via GAP OAuth2 library.
f12166:c4:m0
def _setupHttp(self):
if self._http == None:<EOL><INDENT>http = httplib2.Http()<EOL>self._http = self._credentials.authorize(http)<EOL><DEDENT>
Setup an HTTP session authorized by OAuth2.
f12166:c4:m1
def get(self, url, parameters=None):
if self._http == None:<EOL><INDENT>self._setupHttp()<EOL><DEDENT>uri = url + "<STR_LIT:?>" + self.getParameters(parameters)<EOL>response, content = self._http.request(uri, "<STR_LIT:GET>")<EOL>return content<EOL>
Implement libgreader's interface for authenticated GET request
f12166:c4:m2
def post(self, url, postParameters=None, urlParameters=None):
if self._action_token == None:<EOL><INDENT>self._action_token = self.get(ReaderUrl.ACTION_TOKEN_URL)<EOL><DEDENT>if self._http == None:<EOL><INDENT>self._setupHttp()<EOL><DEDENT>uri = url + "<STR_LIT:?>" + self.getParameters(urlParameters)<EOL>postParameters.update({'<STR_LIT:T>':self._action_token})<EOL>body = self.postParameters(postParameters)<EOL>response, content = self._http.request(uri, "<STR_LIT:POST>", body=body)<EOL>return content<EOL>
Implement libgreader's interface for authenticated POST request
f12166:c4:m3
def _getContent(self, excludeRead=False, continuation=None, loadLimit=<NUM_LIT:20>, since=None, until=None):
return None<EOL>
Get content from google reader with specified parameters. Must be overladed in inherited clases
f12169:c0:m1
def loadItems(self, excludeRead=False, loadLimit=<NUM_LIT:20>, since=None, until=None):
self.clearItems()<EOL>self.loadtLoadOk = False<EOL>self.lastLoadLength = <NUM_LIT:0><EOL>self._itemsLoadedDone(self._getContent(excludeRead, None, loadLimit, since, until))<EOL>
Load items and call itemsLoadedDone to transform data in objects
f12169:c0:m2
def loadMoreItems(self, excludeRead=False, continuation=None, loadLimit=<NUM_LIT:20>, since=None, until=None):
self.lastLoadOk = False<EOL>self.lastLoadLength = <NUM_LIT:0><EOL>if not continuation and not self.continuation:<EOL><INDENT>return<EOL><DEDENT>self._itemsLoadedDone(self._getContent(excludeRead, continuation or self.continuation, loadLimit, since, until))<EOL>
Load more items using the continuation parameters of previously loaded items.
f12169:c0:m3
def _itemsLoadedDone(self, data):
if data is None:<EOL><INDENT>return<EOL><DEDENT>self.continuation = data.get('<STR_LIT>', None)<EOL>self.lastUpdated = data.get('<STR_LIT>', None)<EOL>self.lastLoadLength = len(data.get('<STR_LIT>', []))<EOL>self.googleReader.itemsToObjects(self, data.get('<STR_LIT>', []))<EOL>self.lastLoadOk = True<EOL>
Called when all items are loaded
f12169:c0:m4
def __init__(self, googleReader, label, id):
super(Category, self).__init__()<EOL>self.googleReader = googleReader<EOL>self.label = label<EOL>self.id = id<EOL>self.feeds = []<EOL>self.fetchUrl = ReaderUrl.CATEGORY_URL + Category.urlQuote(self.label)<EOL>
:param label: (str) :param id: (str)
f12169:c1:m2
@staticmethod<EOL><INDENT>def urlQuote(string):<DEDENT>
return quote(string.encode("<STR_LIT:utf-8>"))<EOL>
Quote a string for being used in a HTTP URL
f12169:c1:m9
def __init__(self, googleReader, title, id, unread, categories=[]):
super(BaseFeed, self).__init__()<EOL>self.googleReader = googleReader<EOL>self.id = id<EOL>self.title = title<EOL>self.unread = unread<EOL>self.categories = []<EOL>for category in categories:<EOL><INDENT>self.addCategory(category)<EOL><DEDENT>self.continuation = None<EOL>
:param title: (str, name of the feed) :param id: (str, id for google reader) :param unread: (int, number of unread items, 0 by default) :param categories: (list) - list of all categories a feed belongs to, can be empty
f12169:c2:m2
def __init__(self, googleReader, type):
super(SpecialFeed, self).__init__(<EOL>googleReader,<EOL>title = type,<EOL>id = ReaderUrl.SPECIAL_FEEDS_PART_URL+type,<EOL>unread = <NUM_LIT:0>,<EOL>categories = [],<EOL>)<EOL>self.type = type<EOL>self.fetchUrl = ReaderUrl.CONTENT_BASE_URL + Category.urlQuote(self.id)<EOL>
type is one of ReaderUrl.SPECIAL_FEEDS
f12169:c3:m0
def __init__(self, googleReader, title, id, siteUrl=None, unread=<NUM_LIT:0>, categories=[]):
super(Feed, self).__init__(googleReader, title, id, unread, categories)<EOL>self.feedUrl = self.id.lstrip('<STR_LIT>')<EOL>self.siteUrl = siteUrl<EOL>self.fetchUrl = ReaderUrl.FEED_URL + Category.urlQuote(self.id)<EOL>
:param title: str name of the feed :param id: str, id for google reader :param siteUrl: str, can be empty :param unread: int, number of unread items, 0 by default :param categories: (list) - list of all categories a feed belongs to, can be empty
f12169:c4:m0
def __init__(self, googleReader, item, parent):
self.googleReader = googleReader<EOL>self.parent = parent<EOL>self.data = item <EOL>self.id = item['<STR_LIT:id>']<EOL>self.title = item.get('<STR_LIT:title>', '<STR_LIT>')<EOL>self.author = item.get('<STR_LIT>', None)<EOL>self.content = item.get('<STR_LIT:content>', item.get('<STR_LIT>', {})).get('<STR_LIT:content>', '<STR_LIT>')<EOL>self.origin = { '<STR_LIT:title>': '<STR_LIT>', '<STR_LIT:url>': '<STR_LIT>'}<EOL>if '<STR_LIT>' in item:<EOL><INDENT>self.time = int(item['<STR_LIT>']) // <NUM_LIT:1000><EOL><DEDENT>else:<EOL><INDENT>self.time = None<EOL><DEDENT>self.url = None<EOL>for alternate in item.get('<STR_LIT>', []):<EOL><INDENT>if alternate.get('<STR_LIT:type>', '<STR_LIT>') == '<STR_LIT>':<EOL><INDENT>self.url = alternate['<STR_LIT>']<EOL>break<EOL><DEDENT><DEDENT>self.read = False<EOL>self.starred = False<EOL>self.shared = False<EOL>for category in item.get('<STR_LIT>', []):<EOL><INDENT>if category.endswith('<STR_LIT>'):<EOL><INDENT>self.read = True<EOL><DEDENT>elif category.endswith('<STR_LIT>'):<EOL><INDENT>self.starred = True<EOL><DEDENT>elif category in ('<STR_LIT>',<EOL>'<STR_LIT>' % self.googleReader.userId):<EOL><INDENT>self.shared = True<EOL><DEDENT><DEDENT>self.canUnread = item.get('<STR_LIT>', '<STR_LIT:false>') != '<STR_LIT:true>'<EOL>try:<EOL><INDENT>f = item['<STR_LIT>']<EOL>self.origin = {<EOL>'<STR_LIT:title>': f.get('<STR_LIT:title>', '<STR_LIT>'),<EOL>'<STR_LIT:url>': f.get('<STR_LIT>', '<STR_LIT>'),<EOL>}<EOL>self.feed = self.googleReader.getFeed(f['<STR_LIT>'])<EOL>if not self.feed:<EOL><INDENT>raise<EOL><DEDENT>if not self.feed.title and '<STR_LIT:title>' in f:<EOL><INDENT>self.feed.title = f['<STR_LIT:title>']<EOL><DEDENT><DEDENT>except:<EOL><INDENT>try:<EOL><INDENT>self.feed = Feed(self, f.get('<STR_LIT:title>', '<STR_LIT>'), f['<STR_LIT>'], f.get('<STR_LIT>', None), <NUM_LIT:0>, [])<EOL>try:<EOL><INDENT>self.googleReader._addFeed(self.feed)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self.feed = None<EOL><DEDENT><DEDENT>self.parent._addItem(self)<EOL>
:param item: An item loaded from json :param parent: the object (Feed of Category) containing the Item
f12169:c5:m2
def isfile(path):
filename = os.path.basename(path)<EOL>try:<EOL><INDENT>__builtin__.open(os.path.join(BASEDIR, '<STR_LIT:data>', filename))<EOL><DEDENT>except IOError:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
Mock ``isfile`` to check existence of test files. Args: path (str): File to check for existence Returns: bool: `True` if file exists
f12176:m0
def open(filename, mode='<STR_LIT:rb>'):
if '<STR_LIT:r>' in mode:<EOL><INDENT>return _get_test_file(os.path.basename(filename))<EOL><DEDENT>elif '<STR_LIT:w>' in mode:<EOL><INDENT>return StringIO.StringIO()<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError<EOL><DEDENT>
Mock ``open`` function to open test data files. Args: filename (str): File to simulate, basename is used as local file name mode (str): Valid `file` mode string Returns:: file: File object opened from test data directory, or ``StringIO.StringIO`` object if a writable file is expected Raises: NotImplementedError: When attempting to use an unhandled file mode
f12176:m2
def urlopen(url, data=None, proxies=None):
return _get_test_file(os.path.basename(url))<EOL>
Mock ``urlopen`` to open test data files. Args: url (str): URL to simulate, basename is used as local file name data (any): Ignored, just for compatibility with `urlopen` callers proxies (any): Ignored, just for compatibility with `urlopen` callers Returns: file: File object from test data directory
f12176:m3