INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Dump the macro definition for the def created by macro_body.
def macro_def(self, node, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in node.args) name = getattr(node, 'name', None) if len(node.args) == 1: arg_tuple += ',' self.write('Macro(environment, macro...
Call a block and register it for the template.
def visit_Block(self, node, frame): """Call a block and register it for the template.""" level = 1 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return ...
Visit regular imports.
def visit_Import(self, node, frame): """Visit regular imports.""" if node.with_context: self.unoptimize_scope(frame) self.writeline('l_%s = ' % node.target, node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) self.write('environment.ge...
A range that can't generate ranges with a length of more than MAX_RANGE items.
def safe_range(*args): """A range that can't generate ranges with a length of more than MAX_RANGE items. """ rng = xrange(*args) if len(rng) > MAX_RANGE: raise OverflowError('range too big, maximum size for range is %d' % MAX_RANGE) return rng
Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overriden. >>> from jinja2.sandbox import is_internal_attr...
def is_internal_attribute(obj, attr): """Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overriden. >>...
Subscribe an object from sandboxed code.
def getitem(self, obj, argument): """Subscribe an object from sandboxed code.""" try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, basestring): try: attr = str(argument) except: ...
Call an object from sandboxed code.
def call(__self, __context, __obj, *args, **kwargs): """Call an object from sandboxed code.""" # the double prefixes are to avoid double keyword argument # errors when proxying the call. if not __self.is_safe_callable(__obj): raise SecurityError('%r is not safely callable' % ...
Returns a file descriptor for the filename if that file exists, otherwise `None`.
def open_if_exists(filename, mode='rb'): """Returns a file descriptor for the filename if that file exists, otherwise `None`. """ try: return open(filename, mode) except IOError, e: if e.errno not in (errno.ENOENT, errno.EISDIR): raise
Returns the name of the object's type. For some recognized singletons the name of the object is returned instead. (For example for `None` and `Ellipsis`).
def object_type_repr(obj): """Returns the name of the object's type. For some recognized singletons the name of the object is returned instead. (For example for `None` and `Ellipsis`). """ if obj is None: return 'None' elif obj is Ellipsis: return 'Ellipsis' if obj.__class__...
Converts any URLs in text into clickable links. Works on http://, https:// and www. links. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in link text will be limite...
def urlize(text, trim_url_limit=None, nofollow=False): """Converts any URLs in text into clickable links. Works on http://, https:// and www. links. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If tr...
Generate some lorem impsum for the template.
def generate_lorem_ipsum(n=5, html=True, min=20, max=100): """Generate some lorem impsum for the template.""" from jinja2.constants import LOREM_IPSUM_WORDS from random import choice, randrange words = LOREM_IPSUM_WORDS.split() result = [] for _ in xrange(n): next_capitalized = True ...
r"""Unescape markup again into an unicode string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>'
def unescape(self): r"""Unescape markup again into an unicode string. This also resolves known HTML4 and XHTML entities: >>> Markup("Main &raquo; <em>About</em>").unescape() u'Main \xbb <em>About</em>' """ from jinja2.constants import HTML_ENTITIES def handle_ma...
r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About'
def striptags(self): r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About' """ stripped = u' '...
Python 2.4 compatibility.
def _remove(self, obj): """Python 2.4 compatibility.""" for idx, item in enumerate(self._queue): if item == obj: del self._queue[idx] break
Goes one item ahead and returns it.
def next(self): """Goes one item ahead and returns it.""" rv = self.current self.pos = (self.pos + 1) % len(self.items) return rv
Scan directories recursively until find any file with the given extension. The default extension to search is ``.so``.
def get_lib_from(search_directory, lib_extension='.so'): '''Scan directories recursively until find any file with the given extension. The default extension to search is ``.so``.''' for root, dirs, files in walk(search_directory): for file in files: if file.endswith(lib_extension): ...
Parse an assign statement.
def parse_set(self): """Parse an assign statement.""" lineno = next(self.stream).lineno target = self.parse_assign_target() self.stream.expect('assign') expr = self.parse_tuple() return nodes.Assign(target, expr, lineno=lineno)
Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that can be disable however by setting `with_tuple` to `False`. If only assignments to names are wanted `name_only`...
def parse_assign_target(self, with_tuple=True, name_only=False, extra_end_rules=None): """Parse an assignment target. As Jinja2 allows assignments to tuples, this function can parse all allowed assignment targets. Per default assignments to tuples are parsed, that c...
Works like `parse_expression` but if multiple expressions are delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created. This method could also return a regular expression instead of a tuple if no commas where found. The default parsing mode is a full tuple. If `simplified` i...
def parse_tuple(self, simplified=False, with_condexpr=True, extra_end_rules=None, explicit_parentheses=False): """Works like `parse_expression` but if multiple expressions are delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created. This method could also return a...
Takes information about the distribution, and decides what kind of distribution it will be. If parameters conflict (e.g. a dist with that name already exists, but doesn't have the right set of recipes), an error is thrown. Parameters ---------- name : str ...
def get_distribution(cls, ctx, name=None, recipes=[], ndk_api=None, force_build=False, extra_dist_dirs=[], require_perfect_match=False, allow_replace_dist=True): '''Takes information abou...
Returns all the distributions found locally.
def get_distributions(cls, ctx, extra_dist_dirs=[]): '''Returns all the distributions found locally.''' if extra_dist_dirs: raise BuildInterruptingException( 'extra_dist_dirs argument to get_distributions ' 'is not yet implemented') dist_dir = ctx.dist...
Save information about the distribution in its dist_dir.
def save_info(self, dirn): ''' Save information about the distribution in its dist_dir. ''' with current_directory(dirn): info('Saving distribution info') with open('dist_info.json', 'w') as fileh: json.dump({'dist_name': self.ctx.dist_name, ...
Loads bytecode from a file or file like object.
def load_bytecode(self, f): """Loads bytecode from a file or file like object.""" # make sure the magic header is correct magic = f.read(len(bc_magic)) if magic != bc_magic: self.reset() return # the source code of the file changed, we need to reload ...
Dump the bytecode into the file or file like object passed.
def write_bytecode(self, f): """Dump the bytecode into the file or file like object passed.""" if self.code is None: raise TypeError('can\'t write empty bucket') f.write(bc_magic) pickle.dump(self.checksum, f, 2) if isinstance(f, file): marshal.dump(self.c...
Automate the installation of a Python package (or a cython package where the cython components are pre-built).
def install_python_package(self, arch, name=None, env=None, is_dir=True): '''Automate the installation of a Python package (or a cython package where the cython components are pre-built).''' if env is None: env = self.get_recipe_env(arch) with current_directory(self.get_buil...
If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames.
def translate_exception(exc_info, initial_skip=0): """If passed an exc_info it will automatically rewrite the exceptions all the way down to the correct line numbers and frames. """ tb = exc_info[2] frames = [] # skip some internal frames if wanted for x in xrange(initial_skip): if ...
Helper for `translate_exception`.
def fake_exc_info(exc_info, filename, lineno): """Helper for `translate_exception`.""" exc_type, exc_value, tb = exc_info # figure the real context out if tb is not None: real_locals = tb.tb_frame.f_locals.copy() ctx = real_locals.get('context') if ctx: locals = ctx....
This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object.
def _init_ugly_crap(): """This function implements a few ugly things so that we can patch the traceback objects. The function returned allows resetting `tb_next` on any python traceback object. """ import ctypes from types import TracebackType # figure out side of _Py_ssize_t if hasatt...
Chains the frames. Requires ctypes or the speedups extension.
def chain_frames(self): """Chains the frames. Requires ctypes or the speedups extension.""" prev_tb = None for tb in self.frames: if prev_tb is not None: prev_tb.tb_next = tb prev_tb = tb prev_tb.tb_next = None
Compiles all the rules from the environment into a list of rules.
def compile_rules(environment): """Compiles all the rules from the environment into a list of rules.""" e = re.escape rules = [ (len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environm...
Look at the next token.
def look(self): """Look at the next token.""" old_token = next(self) result = self.current self.push(result) self.current = old_token return result
Go one token ahead and return the old one
def next(self): """Go one token ahead and return the old one""" rv = self.current if self._pushed: self.current = self._pushed.popleft() elif self.current.type is not TOKEN_EOF: try: self.current = self._next() except StopIteration: ...
Close the stream.
def close(self): """Close the stream.""" self.current = Token(self.current.lineno, TOKEN_EOF, '') self._next = None self.closed = True
Expect a given token type and return it. This accepts the same argument as :meth:`jinja2.lexer.Token.test`.
def expect(self, expr): """Expect a given token type and return it. This accepts the same argument as :meth:`jinja2.lexer.Token.test`. """ if not self.current.test(expr): expr = describe_token_expr(expr) if self.current.type is TOKEN_EOF: raise Te...
This method tokenizes the text and returns the tokens in a generator. Use this method if you just want to tokenize a template.
def tokeniter(self, source, name, filename=None, state=None): """This method tokenizes the text and returns the tokens in a generator. Use this method if you just want to tokenize a template. """ source = '\n'.join(unicode(source).splitlines()) pos = 0 lineno = 1 ...
Add libgeos headers to path
def get_recipe_env(self, arch, with_flags_in_cc=True): """ Add libgeos headers to path """ env = super(ShapelyRecipe, self).get_recipe_env(arch, with_flags_in_cc) libgeos_dir = Recipe.get_recipe('libgeos', self.ctx).get_build_dir(arch.arch) env['CFLAGS'] += " -I{}/dist/include".format(li...
Warn if the user's target API is less than the current minimum recommendation
def check_target_api(api, arch): """Warn if the user's target API is less than the current minimum recommendation """ if api >= ARMEABI_MAX_TARGET_API and arch == 'armeabi': raise BuildInterruptingException( 'Asked to build for armeabi architecture with API ' '{}, but AP...
Warn if the user's NDK is too high or low.
def check_ndk_api(ndk_api, android_api): """Warn if the user's NDK is too high or low.""" if ndk_api > android_api: raise BuildInterruptingException( 'Target NDK API is {}, higher than the target Android API {}.'.format( ndk_api, android_api), instructions=('The N...
Eliminate dead code.
def visit_If(self, node): """Eliminate dead code.""" # do not optimize ifs that have a block inside so that it doesn't # break super(). if node.find(nodes.Block) is not None: return self.generic_visit(node) try: val = self.visit(node.test).as_const() ...
Do constant folding.
def fold(self, node): """Do constant folding.""" node = self.generic_visit(node) try: return nodes.Const.from_untrusted(node.as_const(), lineno=node.lineno, environment=self.environment) ...
Enforce HTML escaping. This will probably double escape variables.
def do_forceescape(value): """Enforce HTML escaping. This will probably double escape variables.""" if hasattr(value, '__html__'): value = value.__html__() return escape(unicode(value))
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced: .. sourcec...
def do_replace(eval_ctx, s, old, new, count=None): """Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the fir...
Create an SGML/XML attribute string based on the items in a dict. All values that are neither `none` nor `undefined` are automatically escaped: .. sourcecode:: html+jinja <ul{{ {'class': 'my_list', 'missing': none, 'id': 'list-%d'|format(variable)}|xmlattr }}> ... <...
def do_xmlattr(_eval_ctx, d, autospace=True): """Create an SGML/XML attribute string based on the items in a dict. All values that are neither `none` nor `undefined` are automatically escaped: .. sourcecode:: html+jinja <ul{{ {'class': 'my_list', 'missing': none, 'id': 'list-%d...
Sort an iterable. If the iterable is made of strings the second parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {% endfor %}
def do_sort(value, case_sensitive=False): """Sort an iterable. If the iterable is made of strings the second parameter can be used to control the case sensitiveness of the comparison which is disabled by default. .. sourcecode:: jinja {% for item in iterable|sort %} ... {%...
If the value is undefined it will return the passed default value, otherwise the value of the variable: .. sourcecode:: jinja {{ my_variable|default('my_variable is not defined') }} This will output the value of ``my_variable`` if the variable was defined, otherwise ``'my_variable is not defi...
def do_default(value, default_value=u'', boolean=False): """If the value is undefined it will return the passed default value, otherwise the value of the variable: .. sourcecode:: jinja {{ my_variable|default('my_variable is not defined') }} This will output the value of ``my_variable`` if th...
Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 {{ [1, 2, 3]|join }} ->...
def do_join(eval_ctx, value, d=u''): """Return a string which is the concatenation of the strings in the sequence. The separator between elements is an empty string per default, you can define it with the optional parameter: .. sourcecode:: jinja {{ [1, 2, 3]|join('|') }} -> 1|2|3 ...
Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). Per default decimal prefixes are used (mega, giga, etc.), if the second parameter is set to `True` the binary prefixes are used (mebi, gibi).
def do_filesizeformat(value, binary=False): """Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc). Per default decimal prefixes are used (mega, giga, etc.), if the second parameter is set to `True` the binary prefixes are used (mebi, gibi). """ bytes = float...
Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja {{ mytext|urlize(40, true) }} links are shortened to 40 chars ...
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False): """Converts URLs in plain text into clickable links. If you pass the filter an additional integer it will shorten the urls to that number. Also a third argument exists that makes the urls "nofollow": .. sourcecode:: jinja ...
Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional parameters to the filter: .. sourcecode:: jinja {{ mytext|indent(2, true) }} indent by...
def do_indent(s, width=4, indentfirst=False): """Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too you can pass additional parameters to the filter: .. sourcecode:: jinja ...
Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will try to save the last word. If the text was in fact truncated it will append an ellipsis sign (`...
def do_truncate(s, length=255, killwords=False, end='...'): """Return a truncated copy of the string. The length is specified with the first parameter which defaults to ``255``. If the second parameter is ``true`` the filter will cut the text at length. Otherwise it will try to save the last word. If th...
Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `width`.
def do_wordwrap(s, width=79, break_long_words=True): """ Return a copy of the string passed to the filter wrapped after ``79`` characters. You can override this default using the first parameter. If you set the second parameter to `false` Jinja will not split words apart if they are longer than `w...
Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter.
def do_int(value, default=0): """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. """ try: return int(value) except (TypeError, ValueError): # this quirk is necessary so that "42.23"|i...
Strip SGML/XML tags and replace adjacent whitespace by one space.
def do_striptags(value): """Strip SGML/XML tags and replace adjacent whitespace by one space. """ if hasattr(value, '__html__'): value = value.__html__() return Markup(unicode(value)).striptags()
Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the following snippet: .. sourcecode:: html+jinja...
def do_groupby(environment, value, attribute): """Group a sequence of objects by a common attribute. If you for example have a list of dicts or objects that represent persons with `gender`, `first_name` and `last_name` attributes and you want to group all users by genders you can do something like the ...
Extracts metdata files from the given package to the given folder, which may be referenced in any way that is permitted in a requirements.txt file or install_requires=[] listing. Current supported metadata files that will be extracted: - pytoml.yml (only if package wasn't obtained as ...
def extract_metainfo_files_from_package( package, output_folder, debug=False ): """ Extracts metdata files from the given package to the given folder, which may be referenced in any way that is permitted in a requirements.txt file or install_requires=[] listing. ...
Returns the path the system-wide python binary. (In case we're running in a virtualenv or venv)
def _get_system_python_executable(): """ Returns the path the system-wide python binary. (In case we're running in a virtualenv or venv) """ # This function is required by get_package_as_folder() to work # inside a virtualenv, since venv creation will fail with # the virtualenv's local pytho...
This function downloads the given package / dependency and extracts the raw contents into a folder. Afterwards, it returns a tuple with the type of distribution obtained, and the temporary folder it extracted to. It is the caller's responsibility to delete the returned temp folder after...
def get_package_as_folder(dependency): """ This function downloads the given package / dependency and extracts the raw contents into a folder. Afterwards, it returns a tuple with the type of distribution obtained, and the temporary folder it extracted to. It is the caller's responsi...
See if a dependency reference refers to a folder path. If it does, return the folder path (which parses and resolves file:// urls in the process). If it doesn't, return None.
def parse_as_folder_reference(dep): """ See if a dependency reference refers to a folder path. If it does, return the folder path (which parses and resolves file:// urls in the process). If it doesn't, return None. """ # Special case: pep508 urls if dep.find("@") > 0 and ( ...
Internal function to extract metainfo from a package. Currently supported info types: - name - dependencies (a list of dependencies)
def _extract_info_from_package(dependency, extract_type=None, debug=False, include_build_requirements=False ): """ Internal function to extract metainfo from a package. Currently suppo...
Obtain the dependencies from a package. Please note this function is possibly SLOW, especially if you enable the recursive mode.
def get_package_dependencies(package, recursive=False, verbose=False, include_build_requirements=False): """ Obtain the dependencies from a package. Please note this function is possibly SLOW, especially if you enable ...
Gets the dependencies from the package in the given folder, then attempts to deduce the actual package name resulting from each dependency line, stripping away everything else.
def get_dep_names_of_package( package, keep_version_pins=False, recursive=False, verbose=False, include_build_requirements=False ): """ Gets the dependencies from the package in the given folder, then attempts to deduce the actual package name resulting ...
This function will take care of all non-recipe things, by: 1. Processing them from --requirements (the modules argument) and installing them 2. Installing the user project/app itself via setup.py if ignore_setup_py=True
def run_pymodules_install(ctx, modules, project_dir, ignore_setup_py=False): """ This function will take care of all non-recipe things, by: 1. Processing them from --requirements (the modules argument) and installing them 2. Installing the user project/app itself via setup.py if ...
Calculates all the storage and build dirs, and makes sure the directories exist where necessary.
def setup_dirs(self, storage_dir): '''Calculates all the storage and build dirs, and makes sure the directories exist where necessary.''' self.storage_dir = expanduser(storage_dir) if ' ' in self.storage_dir: raise ValueError('storage dir path cannot contain spaces, please ' ...
Checks that build dependencies exist and sets internal variables for the Android SDK etc. ..warning:: This *must* be called before trying any build stuff
def prepare_build_environment(self, user_sdk_dir, user_ndk_dir, user_android_api, user_ndk_api): '''Checks that build dependencies exist and sets internal variables for...
Returns the location of site-packages in the python-install build dir.
def get_site_packages_dir(self, arch=None): '''Returns the location of site-packages in the python-install build dir. ''' if self.python_recipe.name == 'python2legacy': return join(self.get_python_install_dir(), 'lib', 'python2.7', 'site-packages') ...
The libs dir for a given arch.
def get_libs_dir(self, arch): '''The libs dir for a given arch.''' ensure_dir(join(self.libs_dir, arch)) return join(self.libs_dir, arch)
make limited length string in form: "the string is very lo...(and 15 more)"
def shorten_string(string, max_width): ''' make limited length string in form: "the string is very lo...(and 15 more)" ''' string_len = len(string) if string_len <= max_width: return string visible = max_width - 16 - int(log10(string_len)) # expected suffix len "...(and XXXXX more)...
Runs the command (which should be an sh.Command instance), while logging the output.
def shprint(command, *args, **kwargs): '''Runs the command (which should be an sh.Command instance), while logging the output.''' kwargs["_iter"] = True kwargs["_out_bufsize"] = 1 kwargs["_err_to_out"] = True kwargs["_bg"] = True is_critical = kwargs.pop('_critical', False) tail_n = kwar...
add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...)
def add_argument(self, *args, **kwargs): """ add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...) """ # if no positional args are supplied or only one is supplied and # it doesn't look like an option string, par...
error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception.
def error(self, message): """error(message: string) Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(_sys....
Given an object, return a boolean indicating whether it is an instance or subclass of :py:class:`Exception`.
def isexception(obj): """Given an object, return a boolean indicating whether it is an instance or subclass of :py:class:`Exception`. """ if isinstance(obj, Exception): return True if isclass(obj) and issubclass(obj, Exception): return True return False
Receives a row, converts datetimes to strings.
def _reduce_datetimes(row): """Receives a row, converts datetimes to strings.""" row = list(row) for i in range(len(row)): if hasattr(row[i], 'isoformat'): row[i] = row[i].isoformat() return tuple(row)
Returns the row as a dictionary, as ordered.
def as_dict(self, ordered=False): """Returns the row as a dictionary, as ordered.""" items = zip(self.keys(), self.values()) return OrderedDict(items) if ordered else dict(items)
A Tablib Dataset containing the row.
def dataset(self): """A Tablib Dataset containing the row.""" data = tablib.Dataset() data.headers = self.keys() row = _reduce_datetimes(self.values()) data.append(row) return data
A Tablib Dataset representation of the RecordCollection.
def dataset(self): """A Tablib Dataset representation of the RecordCollection.""" # Create a new Tablib Dataset. data = tablib.Dataset() # If the RecordCollection is empty, just return the empty set # Check number of rows by typecasting to list if len(list(self)) == 0: ...
Returns a list of all rows for the RecordCollection. If they haven't been fetched yet, consume the iterator and cache the results.
def all(self, as_dict=False, as_ordereddict=False): """Returns a list of all rows for the RecordCollection. If they haven't been fetched yet, consume the iterator and cache the results.""" # By calling list it calls the __iter__ method rows = list(self) if as_dict: ...
Returns a single record for the RecordCollection, or `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.
def first(self, default=None, as_dict=False, as_ordereddict=False): """Returns a single record for the RecordCollection, or `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.""" # Try to get a record, or return/raise default. ...
Returns a single record for the RecordCollection, ensuring that it is the only record, or returns `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.
def one(self, default=None, as_dict=False, as_ordereddict=False): """Returns a single record for the RecordCollection, ensuring that it is the only record, or returns `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.""" # Ensure that...
Get a connection to this Database. Connections are retrieved from a pool.
def get_connection(self): """Get a connection to this Database. Connections are retrieved from a pool. """ if not self.open: raise exc.ResourceClosedError('Database closed.') return Connection(self._engine.connect())
Executes the given SQL query against the Database. Parameters can, optionally, be provided. Returns a RecordCollection, which can be iterated over to get result rows as dictionaries.
def query(self, query, fetchall=False, **params): """Executes the given SQL query against the Database. Parameters can, optionally, be provided. Returns a RecordCollection, which can be iterated over to get result rows as dictionaries. """ with self.get_connection() as conn: ...
Bulk insert or update.
def bulk_query(self, query, *multiparams): """Bulk insert or update.""" with self.get_connection() as conn: conn.bulk_query(query, *multiparams)
Like Database.query, but takes a filename to load a query from.
def query_file(self, path, fetchall=False, **params): """Like Database.query, but takes a filename to load a query from.""" with self.get_connection() as conn: return conn.query_file(path, fetchall, **params)
Like Database.bulk_query, but takes a filename to load a query from.
def bulk_query_file(self, path, *multiparams): """Like Database.bulk_query, but takes a filename to load a query from.""" with self.get_connection() as conn: conn.bulk_query_file(path, *multiparams)
A context manager for executing a transaction on this Database.
def transaction(self): """A context manager for executing a transaction on this Database.""" conn = self.get_connection() tx = conn.transaction() try: yield conn tx.commit() except: tx.rollback() finally: conn.close()
Executes the given SQL query against the connected Database. Parameters can, optionally, be provided. Returns a RecordCollection, which can be iterated over to get result rows as dictionaries.
def query(self, query, fetchall=False, **params): """Executes the given SQL query against the connected Database. Parameters can, optionally, be provided. Returns a RecordCollection, which can be iterated over to get result rows as dictionaries. """ # Execute the given query. ...
Bulk insert or update.
def bulk_query(self, query, *multiparams): """Bulk insert or update.""" self._conn.execute(text(query), *multiparams)
Like Connection.query, but takes a filename to load a query from.
def query_file(self, path, fetchall=False, **params): """Like Connection.query, but takes a filename to load a query from.""" # If path doesn't exists if not os.path.exists(path): raise IOError("File '{}' not found!".format(path)) # If it's a directory if os.path.is...
Like Connection.bulk_query, but takes a filename to load a query from.
def bulk_query_file(self, path, *multiparams): """Like Connection.bulk_query, but takes a filename to load a query from. """ # If path doesn't exists if not os.path.exists(path): raise IOError("File '{}'' not found!".format(path)) # If it's a directory ...
Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a generator of tuples containing the match and its score. If a dictionary is used, also returns the key for each match. Arguments: query: An object representing the thing we w...
def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0): """Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a generator of tuples containing the match and its score. If a dictionary ...
Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a list of tuples containing the match and its score. If a dictionary is used, also returns the key for each match. Arguments: query: An object representing the thing we want t...
def extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5): """Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a list of tuples containing the match and its score. If a dictionary is used, also returns ...
Get a list of the best matches to a collection of choices. Convenience function for getting the choices with best scores. Args: query: A string to match against choices: A list or dictionary of choices, suitable for use with extract(). processor: Optional function for trans...
def extractBests(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0, limit=5): """Get a list of the best matches to a collection of choices. Convenience function for getting the choices with best scores. Args: query: A string to match against choices: A list...
Find the single best match above a score in a list of choices. This is a convenience method which returns the single best choice. See extract() for the full arguments list. Args: query: A string to match against choices: A list or dictionary of choices, suitable for use with ex...
def extractOne(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0): """Find the single best match above a score in a list of choices. This is a convenience method which returns the single best choice. See extract() for the full arguments list. Args: query: A str...
This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify and remove duplicates. Specifically, it uses the process.extract to identify duplicates that score greater than a user defined threshold. Then, it looks for the longest item in the duplicate list sinc...
def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio): """This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify and remove duplicates. Specifically, it uses the process.extract to identify duplicates that score greater than a user defined...
If both objects aren't either both string or unicode instances force them to unicode
def make_type_consistent(s1, s2): """If both objects aren't either both string or unicode instances force them to unicode""" if isinstance(s1, str) and isinstance(s2, str): return s1, s2 elif isinstance(s1, unicode) and isinstance(s2, unicode): return s1, s2 else: return unicod...
Process string by -- removing all but letters and numbers -- trim whitespace -- force to lower case if force_ascii == True, force convert to ascii
def full_process(s, force_ascii=False): """Process string by -- removing all but letters and numbers -- trim whitespace -- force to lower case if force_ascii == True, force convert to ascii""" if force_ascii: s = asciidammit(s) # Keep only Letters and Numbers (see Un...
Return the ratio of the most similar substring as a number between 0 and 100.
def partial_ratio(s1, s2): """"Return the ratio of the most similar substring as a number between 0 and 100.""" s1, s2 = utils.make_type_consistent(s1, s2) if len(s1) <= len(s2): shorter = s1 longer = s2 else: shorter = s2 longer = s1 m = SequenceMatcher(None, s...
Return a cleaned string with token sorted.
def _process_and_sort(s, force_ascii, full_process=True): """Return a cleaned string with token sorted.""" # pull tokens ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s tokens = ts.split() # sort tokens and join sorted_string = u" ".join(sorted(tokens)) return sor...
Return a measure of the sequences' similarity between 0 and 100 but sorting the token before comparing.
def token_sort_ratio(s1, s2, force_ascii=True, full_process=True): """Return a measure of the sequences' similarity between 0 and 100 but sorting the token before comparing. """ return _token_sort(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process)
Return the ratio of the most similar substring as a number between 0 and 100 but sorting the token before comparing.
def partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True): """Return the ratio of the most similar substring as a number between 0 and 100 but sorting the token before comparing. """ return _token_sort(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process)
Find all alphanumeric tokens in each string... - treat them as a set - construct two strings of the form: <sorted_intersection><sorted_remainder> - take ratios of those two strings - controls for unordered partial matches
def _token_set(s1, s2, partial=True, force_ascii=True, full_process=True): """Find all alphanumeric tokens in each string... - treat them as a set - construct two strings of the form: <sorted_intersection><sorted_remainder> - take ratios of those two strings - controls fo...