desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Fetch a URL, optionally caching for a specified time.
Args:
url:
The URL to retrieve
post_data:
A dict of (str, unicode) key/value pairs.
If set, POST will be used.
parameters:
A dict whose key/value pairs should encoded and added
to the query string. [Optional]
no_cache:
If true, overrides the cache on the current re... | def _FetchUrl(self, url, post_data=None, parameters=None, no_cache=None, use_gzip_compression=None):
| extra_params = {}
if self._default_params:
extra_params.update(self._default_params)
if parameters:
extra_params.update(parameters)
if post_data:
http_method = 'POST'
else:
http_method = 'GET'
if self._debugHTTP:
_debug = 1
else:
_debug = 0
... |
'Attempt to find the username in a cross-platform fashion.'
| def _GetUsername(self):
| try:
return (os.getenv('USER') or os.getenv('LOGNAME') or os.getenv('USERNAME') or os.getlogin() or 'nobody')
except (AttributeError, IOError, OSError) as e:
return 'nobody'
|
'List subtitles with a single provider.
The video and languages are checked against the provider.
:param str provider: name of the provider.
:param video: video to list subtitles for.
:type video: :class:`~subliminal.video.Video`
:param languages: languages to search for.
:type languages: set of :class:`~babelfish.lang... | def list_subtitles_provider(self, provider, video, languages):
| if (not provider_manager[provider].plugin.check(video)):
logger.info('Skipping provider %r: not a valid video', provider)
return []
provider_languages = (provider_manager[provider].plugin.languages & languages)
if (not provider_languages):
logger.info('Skipping p... |
'List subtitles.
:param video: video to list subtitles for.
:type video: :class:`~subliminal.video.Video`
:param languages: languages to search for.
:type languages: set of :class:`~babelfish.language.Language`
:return: found subtitles.
:rtype: list of :class:`~subliminal.subtitle.Subtitle`'
| def list_subtitles(self, video, languages):
| subtitles = []
for name in self.providers:
if (name in self.discarded_providers):
logger.debug('Skipping discarded provider %r', name)
continue
provider_subtitles = self.list_subtitles_provider(name, video, languages)
if (provider_subtitles is None):
... |
'Download `subtitle`\'s :attr:`~subliminal.subtitle.Subtitle.content`.
:param subtitle: subtitle to download.
:type subtitle: :class:`~subliminal.subtitle.Subtitle`
:return: `True` if the subtitle has been successfully downloaded, `False` otherwise.
:rtype: bool'
| def download_subtitle(self, subtitle):
| if (subtitle.provider_name in self.discarded_providers):
logger.warning('Provider %r is discarded', subtitle.provider_name)
return False
logger.info('Downloading subtitle %r', subtitle)
try:
self[subtitle.provider_name].download_subtitle(subtitle)
except (requests.... |
'Download the best matching subtitles.
:param subtitles: the subtitles to use.
:type subtitles: list of :class:`~subliminal.subtitle.Subtitle`
:param video: video to download subtitles for.
:type video: :class:`~subliminal.video.Video`
:param languages: languages to download.
:type languages: set of :class:`~babelfish.... | def download_best_subtitles(self, subtitles, video, languages, min_score=0, hearing_impaired=False, only_one=False, compute_score=None):
| compute_score = (compute_score or default_compute_score)
scored_subtitles = sorted([(s, compute_score(s, video, hearing_impaired=hearing_impaired)) for s in subtitles], key=operator.itemgetter(1), reverse=True)
downloaded_subtitles = []
for (subtitle, score) in scored_subtitles:
if (score < min_... |
'Terminate all the :attr:`initialized_providers`.'
| def terminate(self):
| logger.debug('Terminating initialized providers')
for name in list(self.initialized_providers):
del self[name]
|
'Unique identifier of the subtitle'
| @property
def id(self):
| raise NotImplementedError
|
'Content as string
If :attr:`encoding` is None, the encoding is guessed with :meth:`guess_encoding`'
| @property
def text(self):
| if (not self.content):
return
if self.encoding:
return self.content.decode(self.encoding, errors='replace')
return self.content.decode(self.guess_encoding(), errors='replace')
|
'Check if a :attr:`text` is a valid SubRip format.
:return: whether or not the subtitle is valid.
:rtype: bool'
| def is_valid(self):
| if (not self.text):
return False
try:
pysrt.from_string(self.text, error_handling=pysrt.ERROR_RAISE)
except pysrt.Error as e:
if (e.args[0] < 80):
return False
return True
|
'Guess encoding using the language, falling back on chardet.
:return: the guessed encoding.
:rtype: str'
| def guess_encoding(self):
| logger.info('Guessing encoding for language %s', self.language)
encodings = ['utf-8']
if (self.language.alpha3 == 'zho'):
encodings.extend(['gb18030', 'big5'])
elif (self.language.alpha3 == 'jpn'):
encodings.append('shift-jis')
elif (self.language.alpha3 == 'ara'):
... |
'Get the matches against the `video`.
:param video: the video to get the matches with.
:type video: :class:`~subliminal.video.Video`
:return: matches of the subtitle.
:rtype: set'
| def get_matches(self, video):
| raise NotImplementedError
|
'Register an extension
:param str entry_point: extension to register (entry point syntax).
:raise: ValueError if already registered.'
| def register(self, entry_point):
| if (entry_point in self.registered_extensions):
raise ValueError('Extension already registered')
ep = EntryPoint.parse(entry_point)
if (ep.name in self.names()):
raise ValueError('An extension with the same name already exist')
ext = self._load_one_plugin(ep, F... |
'Unregister a provider
:param str entry_point: provider to unregister (entry point syntax).'
| def unregister(self, entry_point):
| if (entry_point not in self.registered_extensions):
raise ValueError('Extension not registered')
ep = EntryPoint.parse(entry_point)
self.registered_extensions.remove(entry_point)
if (self._extensions_by_name is not None):
del self._extensions_by_name[ep.name]
for (i, ext) in en... |
'Search the URL titles by kind for the given `title`.
:param str title: title to search for.
:return: the URL titles by kind.
:rtype: collections.defaultdict'
| @region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME)
def _search_url_titles(self, title):
| logger.info('Searching title name for %r', title)
r = self.session.get((self.server_url + 'subtitle/search/'), params={'q': title}, timeout=10)
r.raise_for_status()
if (r.history and all([(h.status_code == 302) for h in r.history])):
logger.debug('Redirected to the subtitles... |
'Initialize the provider.
Must be called when starting to work with the provider. This is the place for network initialization
or login operations.
.. note::
This is called automatically when entering the `with` statement'
| def initialize(self):
| raise NotImplementedError
|
'Terminate the provider.
Must be called when done with the provider. This is the place for network shutdown or logout operations.
.. note::
This is called automatically when exiting the `with` statement'
| def terminate(self):
| raise NotImplementedError
|
'Check if the `video` can be processed.
The `video` is considered invalid if not an instance of :attr:`video_types` or if the :attr:`required_hash` is
not present in :attr:`~subliminal.video.Video.hashes` attribute of the `video`.
:param video: the video to check.
:type video: :class:`~subliminal.video.Video`
:return: ... | @classmethod
def check(cls, video):
| if (not isinstance(video, cls.video_types)):
return False
if ((cls.required_hash is not None) and (cls.required_hash not in video.hashes)):
return False
return True
|
'Query the provider for subtitles.
Arguments should match as much as possible the actual parameters for querying the provider
:return: found subtitles.
:rtype: list of :class:`~subliminal.subtitle.Subtitle`
:raise: :class:`~subliminal.exceptions.ProviderError`'
| def query(self, *args, **kwargs):
| raise NotImplementedError
|
'List subtitles for the `video` with the given `languages`.
This will call the :meth:`query` method internally. The parameters passed to the :meth:`query` method may
vary depending on the amount of information available in the `video`.
:param video: video to list subtitles for.
:type video: :class:`~subliminal.video.Vi... | def list_subtitles(self, video, languages):
| raise NotImplementedError
|
'Download `subtitle`\'s :attr:`~subliminal.subtitle.Subtitle.content`.
:param subtitle: subtitle to download.
:type subtitle: :class:`~subliminal.subtitle.Subtitle`
:raise: :class:`~subliminal.exceptions.ProviderError`'
| def download_subtitle(self, subtitle):
| raise NotImplementedError
|
'Search for titles matching the `title`.
:param str title: the title to search for.
:return: found titles.
:rtype: dict'
| @region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME)
def search_titles(self, title):
| logger.info('Searching title %r', title)
r = self.session.get((self.server_url + 'legenda/sugestao/{}'.format(title)), timeout=10)
r.raise_for_status()
results = json.loads(r.text)
titles = {}
for result in results:
source = result['_source']
title_id = int(source['id_filme... |
'Get the archive list from a given `title_id` and `language_code`.
:param int title_id: title id.
:param int language_code: language code.
:return: the archives.
:rtype: list of :class:`LegendasTVArchive`'
| @region.cache_on_arguments(expiration_time=timedelta(minutes=15).total_seconds())
def get_archives(self, title_id, language_code):
| logger.info('Getting archives for title %d and language %d', title_id, language_code)
archives = []
page = 1
while True:
url = (self.server_url + 'util/carrega_legendas_busca_filme/{title}/{language}/-/{page}'.format(title=title_id, language=language_code, page=page))
... |
'Download an archive\'s :attr:`~LegendasTVArchive.content`.
:param archive: the archive to download :attr:`~LegendasTVArchive.content` of.
:type archive: :class:`LegendasTVArchive`'
| def download_archive(self, archive):
| logger.info('Downloading archive %s', archive.id)
r = self.session.get((self.server_url + 'downloadarquivo/{}'.format(archive.id)))
r.raise_for_status()
archive_stream = io.BytesIO(r.content)
if is_rarfile(archive_stream):
logger.debug('Identified rar archive')
archive.co... |
'Search the show id from the `series` and `year`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:return: the show id, if any.
:rtype: int'
| @region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME)
def search_show_id(self, series, year=None):
| logger.info('Searching show id for %r', series)
r = self.session.post((self.server_url + 'search.php'), data={'q': series}, timeout=10)
r.raise_for_status()
soup = ParserBeautifulSoup(r.content, ['lxml', 'html.parser'])
show_id = None
for suggestion in soup.select('div.left li ... |
'Get episode ids from the show id and the season.
:param int show_id: show id.
:param int season: season of the episode.
:return: episode ids per episode number.
:rtype: dict'
| @region.cache_on_arguments(expiration_time=EPISODE_EXPIRATION_TIME)
def get_episode_ids(self, show_id, season):
| logger.info('Getting the page of show id %d, season %d', show_id, season)
r = self.session.get((self.server_url + ('tvshow-%d-%d.html' % (show_id, season))), timeout=10)
soup = ParserBeautifulSoup(r.content, ['lxml', 'html.parser'])
episode_ids = {}
for row in soup.select('ta... |
'Get the ``dict`` of show ids per series by querying the `shows.php` page.
:return: show id per series, lower case and without quotes.
:rtype: dict'
| @region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME)
def _get_show_ids(self):
| logger.info('Getting show ids')
r = self.session.get((self.server_url + 'shows.php'), timeout=10)
r.raise_for_status()
soup = ParserBeautifulSoup(r.content, ['lxml', 'html.parser'])
show_ids = {}
for show in soup.select('td.version > h3 > a[href^="/show/"]'):
show_ids[s... |
'Search the show id from the `series` and `year`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:return: the show id, if found.
:rtype: int'
| @region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME)
def _search_show_id(self, series, year=None):
| series = series.replace("'", ' ')
series_year = (('%s %d' % (series, year)) if (year is not None) else series)
params = {'search': series_year, 'Submit': 'Search'}
logger.info('Searching show ids with %r', params)
r = self.session.get((self.server_url + 'search.php'), params=params... |
'Get the best matching show id for `series`, `year` and `country_code`.
First search in the result of :meth:`_get_show_ids` and fallback on a search with :meth:`_search_show_id`.
:param str series: series of the episode.
:param year: year of the series, if any.
:type year: int
:param country_code: country code of the s... | def get_show_id(self, series, year=None, country_code=None):
| series_sanitized = sanitize(series).lower()
show_ids = self._get_show_ids()
show_id = None
if ((not show_id) and country_code):
logger.debug('Getting show id with country')
show_id = show_ids.get(('%s %s' % (series_sanitized, country_code.lower())))
if ((not show_id) a... |
'Login'
| def login(self):
| data = {'apikey': self.apikey, 'username': self.username, 'password': self.password}
r = self.session.post((self.base_url + '/login'), json=data)
r.raise_for_status()
self.session.headers['Authorization'] = ('Bearer ' + r.json()['token'])
self.token_date = datetime.utcnow()
|
'Refresh token'
| def refresh_token(self):
| r = self.session.get((self.base_url + '/refresh_token'))
r.raise_for_status()
self.session.headers['Authorization'] = ('Bearer ' + r.json()['token'])
self.token_date = datetime.utcnow()
|
'Search series'
| @requires_auth
def search_series(self, name=None, imdb_id=None, zap2it_id=None):
| params = {'name': name, 'imdbId': imdb_id, 'zap2itId': zap2it_id}
r = self.session.get((self.base_url + '/search/series'), params=params)
if (r.status_code == 404):
return None
r.raise_for_status()
return r.json()['data']
|
'Get series'
| @requires_auth
def get_series(self, id):
| r = self.session.get((self.base_url + '/series/{}'.format(id)))
if (r.status_code == 404):
return None
r.raise_for_status()
return r.json()['data']
|
'Get series actors'
| @requires_auth
def get_series_actors(self, id):
| r = self.session.get((self.base_url + '/series/{}/actors'.format(id)))
if (r.status_code == 404):
return None
r.raise_for_status()
return r.json()['data']
|
'Get series episodes'
| @requires_auth
def get_series_episodes(self, id, page=1):
| params = {'page': page}
r = self.session.get((self.base_url + '/series/{}/episodes'.format(id)), params=params)
if (r.status_code == 404):
return None
r.raise_for_status()
return r.json()
|
'Query series episodes'
| @requires_auth
def query_series_episodes(self, id, absolute_number=None, aired_season=None, aired_episode=None, dvd_season=None, dvd_episode=None, imdb_id=None, page=1):
| params = {'absoluteNumber': absolute_number, 'airedSeason': aired_season, 'airedEpisode': aired_episode, 'dvdSeason': dvd_season, 'dvdEpisode': dvd_episode, 'imdbId': imdb_id, 'page': page}
r = self.session.get((self.base_url + '/series/{}/episodes/query'.format(id)), params=params)
if (r.status_code == 404... |
'Get episode'
| @requires_auth
def get_episode(self, id):
| r = self.session.get((self.base_url + '/episodes/{}'.format(id)))
if (r.status_code == 404):
return None
r.raise_for_status()
return r.json()['data']
|
'Read the configuration from :attr:`path`'
| def read(self):
| self.config.read(self.path)
|
'Write the configuration to :attr:`path`'
| def write(self):
| with open(self.path, 'w') as f:
self.config.write(f)
|
'Test whether the video exists'
| @property
def exists(self):
| return os.path.exists(self.name)
|
'Age of the video'
| @property
def age(self):
| if self.exists:
return (datetime.utcnow() - datetime.utcfromtimestamp(os.path.getmtime(self.name)))
return timedelta()
|
'Create an :class:`Episode` or a :class:`Movie` with the given `name` based on the `guess`.
:param str name: name of the video.
:param dict guess: guessed data.
:raise: :class:`ValueError` if the `type` of the `guess` is invalid'
| @classmethod
def fromguess(cls, name, guess):
| if (guess['type'] == 'episode'):
return Episode.fromguess(name, guess)
if (guess['type'] == 'movie'):
return Movie.fromguess(name, guess)
raise ValueError('The guess must be an episode or a movie guess')
|
'Shortcut for :meth:`fromguess` with a `guess` guessed from the `name`.
:param str name: name of the video.'
| @classmethod
def fromname(cls, name):
| return cls.fromguess(name, guessit(name))
|
'compile the given regexp, cache the reg, and call match_reg().'
| def match(self, regexp, flags=None):
| try:
reg = _regexp_cache[(regexp, flags)]
except KeyError:
if flags:
reg = re.compile(regexp, flags)
else:
reg = re.compile(regexp)
_regexp_cache[(regexp, flags)] = reg
return self.match_reg(reg)
|
'match the given regular expression object to the current text
position.
if a match occurs, update the current text and line position.'
| def match_reg(self, reg):
| mp = self.match_position
match = reg.match(self.text, self.match_position)
if match:
(start, end) = match.span()
if (end == start):
self.match_position = (end + 1)
else:
self.match_position = end
self.matched_lineno = self.lineno
lines = re.fin... |
'given string/unicode or bytes/string, determine encoding
from magic encoding comment, return body as unicode
or raw if decode_raw=False'
| def decode_raw_stream(self, text, decode_raw, known_encoding, filename):
| if isinstance(text, compat.text_type):
m = self._coding_re.match(text)
encoding = ((m and m.group(1)) or known_encoding or 'ascii')
return (encoding, text)
if text.startswith(codecs.BOM_UTF8):
text = text[len(codecs.BOM_UTF8):]
parsed_encoding = 'utf-8'
m = self._... |
'matches the multiline version of a comment'
| def match_comment(self):
| match = self.match('<%doc>(.*?)</%doc>', re.S)
if match:
self.append_node(parsetree.Comment, match.group(1))
return True
else:
return False
|
'Traverse a template structure for module-level directives and
generate the start of module-level code.'
| def write_toplevel(self):
| inherit = []
namespaces = {}
module_code = []
self.compiler.pagetag = None
class FindTopLevel(object, ):
def visitInheritTag(s, node):
inherit.append(node)
def visitNamespaceTag(s, node):
namespaces[node.name] = node
def visitPageTag(s, node):
... |
'write a top-level render callable.
this could be the main render() method or that of a top-level def.'
| def write_render_callable(self, node, name, args, buffered, filtered, cached):
| if self.in_def:
decorator = node.decorator
if decorator:
self.printer.writeline(('@runtime._decorate_toplevel(%s)' % decorator))
self.printer.start_source(node.lineno)
self.printer.writelines(('def %s(%s):' % (name, ','.join(args))), '__M_caller = context.caller_stack._p... |
'write module-level template code, i.e. that which
is enclosed in <%! %> tags in the template.'
| def write_module_code(self, module_code):
| for n in module_code:
self.printer.start_source(n.lineno)
self.printer.write_indented_block(n.text)
|
'write the module-level inheritance-determination callable.'
| def write_inherit(self, node):
| self.printer.writelines('def _mako_inherit(template, context):', '_mako_generate_namespaces(context)', ('return runtime._inherit_from(context, %s, _template_uri)' % node.parsed_attributes['file']), None)
|
'write the module-level namespace-generating callable.'
| def write_namespaces(self, namespaces):
| self.printer.writelines('def _mako_get_namespace(context, name):', 'try:', 'return context.namespaces[(__name__, name)]', 'except KeyError:', '_mako_generate_namespaces(context)', 'return context.namespaces[(__name__, name)]', None, None)
self.printer.writeline('def _mako_generate_namesp... |
'write variable declarations at the top of a function.
the variable declarations are in the form of callable
definitions for defs and/or name lookup within the
function\'s context argument. the names declared are based
on the names that are referenced in the function body,
which don\'t otherwise have any explicit assig... | def write_variable_declares(self, identifiers, toplevel=False, limit=None):
| comp_idents = dict([(c.funcname, c) for c in identifiers.defs])
to_write = set()
to_write = to_write.union(identifiers.undeclared)
to_write = to_write.union([c.funcname for c in identifiers.closuredefs.values()])
to_write = to_write.difference(identifiers.argument_declared)
to_write = to_write.d... |
'write a locally-available callable referencing a top-level def'
| def write_def_decl(self, node, identifiers):
| funcname = node.funcname
namedecls = node.get_argument_expressions()
nameargs = node.get_argument_expressions(as_call=True)
if ((not self.in_def) and ((len(self.identifiers.locally_assigned) > 0) or (len(self.identifiers.argument_declared) > 0))):
nameargs.insert(0, 'context._locals(__M_locals)'... |
'write a locally-available def callable inside an enclosing def.'
| def write_inline_def(self, node, identifiers, nested):
| namedecls = node.get_argument_expressions()
decorator = node.decorator
if decorator:
self.printer.writeline(('@runtime._decorate_inline(context, %s)' % decorator))
self.printer.writeline(('def %s(%s):' % (node.funcname, ','.join(namedecls))))
filtered = (len(node.filter_args.args) > 0)... |
'write the end section of a rendering function, either outermost or
inline.
this takes into account if the rendering function was filtered,
buffered, etc. and closes the corresponding try: block if any, and
writes code to retrieve captured content, apply filters, send proper
return value.'
| def write_def_finish(self, node, buffered, filtered, cached, callstack=True):
| if ((not buffered) and (not cached) and (not filtered)):
self.printer.writeline("return ''")
if callstack:
self.printer.writelines('finally:', 'context.caller_stack._pop_frame()', None)
if (buffered or filtered or cached):
if (buffered or cached):
self.printer.... |
'write a post-function decorator to replace a rendering
callable with a cached version of itself.'
| def write_cache_decorator(self, node_or_pagetag, name, args, buffered, identifiers, inline=False, toplevel=False):
| self.printer.writeline(('__M_%s = %s' % (name, name)))
cachekey = node_or_pagetag.parsed_attributes.get('cache_key', repr(name))
cache_args = {}
if (self.compiler.pagetag is not None):
cache_args.update(((pa[6:], self.compiler.pagetag.parsed_attributes[pa]) for pa in self.compiler.pagetag.... |
'write a filter-applying expression based on the filters
present in the given filter names, adjusting for the global
\'default\' filter aliases as needed.'
| def create_filter_callable(self, args, target, is_expression):
| def locate_encode(name):
if re.match('decode\\..+', name):
return ('filters.' + name)
elif self.compiler.disable_unicode:
return filters.NON_UNICODE_ESCAPES.get(name, name)
else:
return filters.DEFAULT_ESCAPES.get(name, name)
if ('n' not in args):
... |
'create a new Identifiers for a new Node, with
this Identifiers as the parent.'
| def branch(self, node, **kwargs):
| return _Identifiers(self.compiler, node, self, **kwargs)
|
'update the state of this Identifiers with the undeclared
and declared identifiers of the given node.'
| def check_declared(self, node):
| for ident in node.undeclared_identifiers():
if ((ident != 'context') and (ident not in self.declared.union(self.locally_declared))):
self.undeclared.add(ident)
for ident in node.declared_identifiers():
self.locally_declared.add(ident)
|
'return true if the given keyword is a ternary keyword
for this ControlLine'
| def is_ternary(self, keyword):
| return (keyword in {'if': set(['else', 'elif']), 'try': set(['except', 'finally']), 'for': set(['else'])}.get(self.keyword, []))
|
'construct a new Tag instance.
this constructor not called directly, and is only called
by subclasses.
:param keyword: the tag keyword
:param attributes: raw dictionary of attribute key/value pairs
:param expressions: a set of identifiers that are legal attributes,
which can also contain embedded expressions
:param non... | def __init__(self, keyword, attributes, expressions, nonexpressions, required, **kwargs):
| super(Tag, self).__init__(**kwargs)
self.keyword = keyword
self.attributes = attributes
self._parse_attributes(expressions, nonexpressions)
missing = [r for r in required if (r not in self.parsed_attributes)]
if len(missing):
raise exceptions.CompileException(('Missing attribute(s): ... |
'Return the argument declarations of this FunctionDecl as a printable
list.
By default the return value is appropriate for writing in a ``def``;
set `as_call` to true to build arguments to be passed to the function
instead (assuming locals with the same names as the arguments exist).'
| def get_argument_expressions(self, as_call=False):
| namedecls = []
argnames = self.argnames[::(-1)]
kwargnames = self.kwargnames[::(-1)]
defaults = self.defaults[::(-1)]
kwdefaults = self.kwdefaults[::(-1)]
if self.kwargs:
namedecls.append(('**' + kwargnames.pop(0)))
for name in kwargnames:
if as_call:
namedecls.ap... |
'produce a \'union\' of this dict and another (at the key level).
values in the second dict take precedence over that of the first'
| def union(self, other):
| x = SetLikeDict(**self)
x.update(other)
return x
|
'Find a unicode representation of self.error'
| def _init_message(self):
| try:
self.message = compat.text_type(self.error)
except UnicodeError:
try:
self.message = str(self.error)
except UnicodeEncodeError:
self.message = self.error.args[0]
if (not isinstance(self.message, compat.text_type)):
self.message = compat.text_type(... |
'Return a list of 4-tuple traceback records (i.e. normal python
format) with template-corresponding lines remapped to the originating
template.'
| @property
def traceback(self):
| return list(self._get_reformatted_records(self.records))
|
'Return the same data as traceback, except in reverse order.'
| @property
def reverse_traceback(self):
| return list(self._get_reformatted_records(self.reverse_records))
|
'format a traceback from sys.exc_info() into 7-item tuples,
containing the regular four traceback tuple items, plus the original
template filename, the line number adjusted relative to the template
source, and code line from that line number of the template.'
| def _init(self, trcback):
| import mako.template
mods = {}
rawrecords = traceback.extract_tb(trcback)
new_trcback = []
for (filename, lineno, function, line) in rawrecords:
if (not line):
line = ''
try:
(line_map, template_lines) = mods[filename]
except KeyError:
try:... |
'Return the template source code for this :class:`.Template`.'
| @property
def source(self):
| return _get_module_info_from_callable(self.callable_).source
|
'Return the module source code for this :class:`.Template`.'
| @property
def code(self):
| return _get_module_info_from_callable(self.callable_).code
|
'Render the output of this template as a string.
If the template specifies an output encoding, the string
will be encoded accordingly, else the output is raw (raw
output uses `cStringIO` and can\'t handle multibyte
characters). A :class:`.Context` object is created corresponding
to the given data. Arguments that are ex... | def render(self, *args, **data):
| return runtime._render(self, self.callable_, args, data)
|
'Render the output of this template as a unicode object.'
| def render_unicode(self, *args, **data):
| return runtime._render(self, self.callable_, args, data, as_unicode=True)
|
'Render this :class:`.Template` with the given context.
The data is written to the context\'s buffer.'
| def render_context(self, context, *args, **kwargs):
| if (getattr(context, '_with_template', None) is None):
context._set_with_template(self)
runtime._render_context(self, self.callable_, context, *args, **kwargs)
|
'Return a def of this template as a :class:`.DefTemplate`.'
| def get_def(self, name):
| return DefTemplate(self, getattr(self.module, ('render_%s' % name)))
|
'return a list of defs in the template.
.. versionadded:: 1.0.4'
| def list_defs(self):
| return [i[7:] for i in dir(self.module) if (i[:7] == 'render_')]
|
'Return the :class:`.TemplateLookup` associated
with this :class:`.Context`.'
| @property
def lookup(self):
| return self._with_template.lookup
|
'Return the dictionary of top level keyword arguments associated
with this :class:`.Context`.
This dictionary only includes the top-level arguments passed to
:meth:`.Template.render`. It does not include names produced within
the template execution such as local variable names or special names
such as ``self``, ``next... | @property
def kwargs(self):
| return self._kwargs.copy()
|
'Push a ``caller`` callable onto the callstack for
this :class:`.Context`.'
| def push_caller(self, caller):
| self.caller_stack.append(caller)
|
'Pop a ``caller`` callable onto the callstack for this
:class:`.Context`.'
| def pop_caller(self):
| del self.caller_stack[(-1)]
|
'Return a list of all names established in this :class:`.Context`.'
| def keys(self):
| return list(self._data.keys())
|
'push a capturing buffer onto this Context and return
the new writer function.'
| def _push_writer(self):
| buf = util.FastEncodingBuffer()
self._buffer_stack.append(buf)
return buf.write
|
'pop the most recent capturing buffer from this Context
and return the current writer after the pop.'
| def _pop_buffer_and_writer(self):
| buf = self._buffer_stack.pop()
return (buf, self._buffer_stack[(-1)].write)
|
'push a capturing buffer onto this Context.'
| def _push_buffer(self):
| self._push_writer()
|
'pop the most recent capturing buffer from this Context.'
| def _pop_buffer(self):
| return self._buffer_stack.pop()
|
'Return a value from this :class:`.Context`.'
| def get(self, key, default=None):
| return self._data.get(key, compat_builtins.__dict__.get(key, default))
|
'Write a string to this :class:`.Context` object\'s
underlying output buffer.'
| def write(self, string):
| self._buffer_stack[(-1)].write(string)
|
'Return the current writer function.'
| def writer(self):
| return self._buffer_stack[(-1)].write
|
'Create a new :class:`.Context` with a copy of this
:class:`.Context`\'s current state,
updated with the given dictionary.
The :attr:`.Context.kwargs` collection remains
unaffected.'
| def _locals(self, d):
| if (not d):
return self
c = self._copy()
c._data.update(d)
return c
|
'create a new copy of this :class:`.Context`. with
tokens related to inheritance state removed.'
| def _clean_inheritance_tokens(self):
| c = self._copy()
x = c._data
x.pop('self', None)
x.pop('parent', None)
x.pop('next', None)
return c
|
'Cycle through values as the loop progresses.'
| def cycle(self, *values):
| if (not values):
raise ValueError('You must provide values to cycle through')
return values[(self.index % len(values))]
|
'Access module level attributes by name.
This accessor allows templates to supply "scalar"
attributes which are particularly handy in inheritance
relationships.
.. seealso::
:ref:`inheritance_attr`
:ref:`namespace_attr_for_includes`'
| @util.memoized_property
def attr(self):
| return _NSAttr(self)
|
'Return a :class:`.Namespace` corresponding to the given ``uri``.
If the given ``uri`` is a relative URI (i.e. it does not
contain a leading slash ``/``), the ``uri`` is adjusted to
be relative to the ``uri`` of the namespace itself. This
method is therefore mostly useful off of the built-in
``local`` namespace, descri... | def get_namespace(self, uri):
| key = (self, uri)
if (key in self.context.namespaces):
return self.context.namespaces[key]
else:
ns = TemplateNamespace(uri, self.context._copy(), templateuri=uri, calling_uri=self._templateuri)
self.context.namespaces[key] = ns
return ns
|
'Return a :class:`.Template` from the given ``uri``.
The ``uri`` resolution is relative to the ``uri`` of this
:class:`.Namespace` object\'s :class:`.Template`.'
| def get_template(self, uri):
| return _lookup_template(self.context, uri, self._templateuri)
|
'Return a value from the :class:`.Cache` referenced by this
:class:`.Namespace` object\'s :class:`.Template`.
The advantage to this method versus direct access to the
:class:`.Cache` is that the configuration parameters
declared in ``<%page>`` take effect here, thereby calling
up the same configured backend as that con... | def get_cached(self, key, **kwargs):
| return self.cache.get(key, **kwargs)
|
'Return the :class:`.Cache` object referenced
by this :class:`.Namespace` object\'s
:class:`.Template`.'
| @property
def cache(self):
| return self.template.cache
|
'Include a file at the given ``uri``.'
| def include_file(self, uri, **kwargs):
| _include_file(self.context, uri, self._templateuri, **kwargs)
|
'The Python module referenced by this :class:`.Namespace`.
If the namespace references a :class:`.Template`, then
this module is the equivalent of ``template.module``,
i.e. the generated module for the template.'
| @property
def module(self):
| return self.template.module
|
'The path of the filesystem file used for this
:class:`.Namespace`\'s module or template.'
| @property
def filename(self):
| return self.template.filename
|
'The URI for this :class:`.Namespace`\'s template.
I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`.
This is the equivalent of :attr:`.Template.uri`.'
| @property
def uri(self):
| return self.template.uri
|
'The path of the filesystem file used for this
:class:`.Namespace`\'s module or template.'
| @property
def filename(self):
| return self.module.__file__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.