text
stringlengths
81
112k
Create a 7z archive. def seven_zip(archive, items, self_extracting=False): """Create a 7z archive.""" if not isinstance(items, (list, tuple)): items = [items] if self_extracting: return er(_get_sz(), "a", "-ssw", "-sfx", archive, *items) else: return er(_get_sz(), "a", "-ssw", a...
Checks every cache backend alias in ``settings.CACHES`` until it becomes available. After ``max_retries`` attempts to reach any backend are failed it returns ``False``. If ``exit_on_failure`` is set it shuts down with ``exit(1)``. It sets the ``django-docker-helpers:available-check`` key for every cache ba...
Checks every database alias in ``settings.DATABASES`` until it becomes available. After ``max_retries`` attempts to reach any backend are failed it returns ``False``. If ``exit_on_failure`` is set it shuts down with ``exit(1)``. For every database alias it tries to ``SELECT 1``. If no errors raised it chec...
Runs Django migrate command. :return: always ``True`` def migrate(*argv) -> bool: """ Runs Django migrate command. :return: always ``True`` """ wf('Applying migrations... ', False) execute_from_command_line(['./manage.py', 'migrate'] + list(argv)) wf('[+]\n') return True
Formats a response from a WSGI app to handle any RDF graphs If a view function returns a single RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling def output(self, output, accepts, set_http_code, set_content_type): """ Formats a response from a...
Wraps a WSGI application to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified def decorate(self, app): """ Wraps a WSGI application to return formatted RDF graphs Uses content negotiation to serialize t...
Detect an handler and return its wanted signal name. def is_handler(cls, name, value): """Detect an handler and return its wanted signal name.""" signal_name = False config = None if callable(value) and hasattr(value, SPEC_CONTAINER_MEMBER_NAME): spec = getattr(value, SP...
For all of the names build a ChainMap containing a map for every base class. def _build_inheritance_chain(cls, bases, *names, merge=False): """For all of the names build a ChainMap containing a map for every base class.""" result = [] for name in names: maps = [] ...
For every unbound handler, get the bound version. def _build_instance_handler_mapping(cls, instance, handle_d): """For every unbound handler, get the bound version.""" res = {} for member_name, sig_name in handle_d.items(): if sig_name in res: sig_handlers = res[sig_...
For every marked handler, see if there is a suitable signal. If not, raise an error. def _check_local_handlers(cls, signals, handlers, namespace, configs): """For every marked handler, see if there is a suitable signal. If not, raise an error.""" for aname, sig_name in handlers.items():...
Add name info to every "local" (present in the body of this class) signal and add it to the mapping. Also complete signal initialization as member of the class by injecting its name. def _find_local_signals(cls, signals, namespace): """Add name info to every "local" (present in the body of th...
Add name info to every "local" (present in the body of this class) handler and add it to the mapping. def _find_local_handlers(cls, handlers, namespace, configs): """Add name info to every "local" (present in the body of this class) handler and add it to the mapping. """ for an...
Returns the handlers registered at class level. def _get_class_handlers(cls, signal_name, instance): """Returns the handlers registered at class level. """ handlers = cls._signal_handlers_sorted[signal_name] return [getattr(instance, hname) for hname in handlers]
Sort class defined handlers to give precedence to those declared at lower level. ``config`` can contain two keys ``begin`` or ``end`` that will further reposition the handler at the two extremes. def _sort_handlers(cls, signals, handlers, configs): """Sort class defined handlers to give precede...
Calculate per-instance signals and handlers. def instance_signals_and_handlers(cls, instance): """Calculate per-instance signals and handlers.""" isignals = cls._signals.copy() ihandlers = cls._build_instance_handler_mapping( instance, cls._signal_handlers ) ...
:param src: file path :return: checksum value def add(self, src): """ :param src: file path :return: checksum value """ checksum = get_checksum(src) filename = self.get_filename(checksum) if not filename: new_name = self._get_new_name() ...
:param checksum: checksum :return: filename no storage base part def get_filename(self, checksum): """ :param checksum: checksum :return: filename no storage base part """ filename = None for _filename, metadata in self._log.items(): if metadata['chec...
Retrieve file location from cache DB def __retrieve(self, key): ''' Retrieve file location from cache DB ''' with self.get_conn() as conn: try: c = conn.cursor() if key is None: c.execute("SELECT value FROM cache_entries WHERE key ...
Insert a new key to database def __insert(self, key, value): ''' Insert a new key to database ''' if key in self: getLogger().warning("Cache entry exists, cannot insert a new entry with key='{key}'".format(key=key)) return False with self.get_conn() as co...
Delete file key from database def __delete(self, key): ''' Delete file key from database ''' with self.get_conn() as conn: try: c = conn.cursor() c.execute("DELETE FROM cache_entries WHERE key = ?", (key,)) conn.commit() ex...
This method will insert blob data to blob table def __insert_internal_blob(self, key, blob, compressed=True): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None c = conn.cursor() try: ...
This method will insert blob data to blob table def __delete_internal_blob(self, key): ''' This method will insert blob data to blob table ''' with self.get_conn() as conn: conn.isolation_level = None try: c = conn.cursor() c.execute("BEGI...
Retrieve file location from cache DB def __retrieve_internal_blob(self, key): ''' Retrieve file location from cache DB ''' logger = getLogger() with self.get_conn() as conn: try: c = conn.cursor() if key is None: c.execute(...
Retrieve blob in binary format (or string format if encoding is provided) def retrieve_blob(self, key, encoding=None): ''' Retrieve blob in binary format (or string format if encoding is provided) ''' blob_key = self.__retrieve(key) if blob_key is None: return None if not bl...
Return summary rows for `rows`. Parameters ---------- rows : list of dicts Normalized rows to summarize. Returns ------- A list of summary rows. Each row is a tuple where the first item is the data and the second is a dict of keyword arguments that ...
Do writer-specific setup. Parameters ---------- style : dict Style, as passed to __init__. streamer : interface.Stream A stream interface that takes __init__'s `stream` and `interactive` arguments into account. processors : field.StyleProcesso...
A list of unique IDs used to identify a row. If not explicitly set, it defaults to the first column name. def ids(self): """A list of unique IDs used to identify a row. If not explicitly set, it defaults to the first column name. """ if self._ids is None: if self._...
Wait for asynchronous calls to return. def wait(self): """Wait for asynchronous calls to return. """ if self._pool is None: return self._pool.close() self._pool.join()
Acquire and release the lock around output calls. This should allow multiple threads or processes to write output reliably. Code that modifies the `_content` attribute should also do so within this context. def _write_lock(self): """Acquire and release the lock around output calls. ...
Start running `callables` asynchronously. def _start_callables(self, row, callables): """Start running `callables` asynchronously. """ id_vals = {c: row[c] for c in self.ids} def callback(tab, cols, result): if isinstance(result, Mapping): pass e...
Get a listing of all non-system schemas (prefixed with 'pg_') that exist in the database. def schemas(self): """ Get a listing of all non-system schemas (prefixed with 'pg_') that exist in the database. """ sql = """SELECT schema_name FROM information_schema.schemata ...
Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on connect, return all tables, with schema prefixes def tables(self): """ Get a listing of all tables - if schema spe...
Check if the table name is obviously invalid. def _valid_table_name(self, table): """Check if the table name is obviously invalid. """ if table is None or not len(table.strip()): raise ValueError("Invalid table name: %r" % table) return table.strip()
Modify table and field name variables in a sql string with a dict. This seems to be discouraged by psycopg2 docs but it makes small adjustments to large sql strings much easier, making prepped queries much more versatile. USAGE sql = 'SELECT $myInputField FROM $myInputTable' ...
Get a listing of all tables in given schema def tables_in_schema(self, schema): """Get a listing of all tables in given schema """ sql = """SELECT table_name FROM information_schema.tables WHERE table_schema = %s""" return [t[0] for t in self.query(sql,...
Parse schema qualified table name def parse_table_name(self, table): """Parse schema qualified table name """ if "." in table: schema, table = table.split(".") else: schema = None return (schema, table)
Loads a table. Returns None if the table does not already exist in db def load_table(self, table): """Loads a table. Returns None if the table does not already exist in db """ table = self._valid_table_name(table) schema, table = self.parse_table_name(table) if not schema: ...
Return the query string with parameters added def mogrify(self, sql, params): """Return the query string with parameters added """ conn = self.engine.raw_connection() cursor = conn.cursor() return cursor.mogrify(sql, params)
Just a pointer to engine.execute def execute(self, sql, params=None): """Just a pointer to engine.execute """ # wrap in a transaction to ensure things are committed # https://github.com/smnorris/pgdata/issues/3 with self.engine.begin() as conn: result = conn.execute(...
Grab just one record def query_one(self, sql, params=None): """Grab just one record """ r = self.engine.execute(sql, params) return r.fetchone()
Create specified schema if it does not already exist def create_schema(self, schema): """Create specified schema if it does not already exist """ if schema not in self.schemas: sql = "CREATE SCHEMA " + schema self.execute(sql)
Drop specified schema def drop_schema(self, schema, cascade=False): """Drop specified schema """ if schema in self.schemas: sql = "DROP SCHEMA " + schema if cascade: sql = sql + " CASCADE" self.execute(sql)
Creates a table def create_table(self, table, columns): """Creates a table """ schema, table = self.parse_table_name(table) table = self._valid_table_name(table) if not schema: schema = self.schema if table in self.tables: return Table(self, schem...
Load a layer to provided pgdata database connection using OGR2OGR -sql option is like an ESRI where_clause or the ogr2ogr -where option, but to increase flexibility, it is in SQLITE dialect: SELECT * FROM <in_layer> WHERE <sql> def ogr2pg( self, in_file, in_layer=None, ...
A wrapper around ogr2ogr, for quickly dumping a postgis query to file. Suppported formats are ["ESRI Shapefile", "GeoJSON", "FileGDB", "GPKG"] - for GeoJSON, transforms to EPSG:4326 - for Shapefile, consider supplying a column_remap dict - for FileGDB, geom_type is required ...
Try to load logging configuration from a file. Set level to INFO if failed. def setup_logging(filename, log_dir=None, force_setup=False): ''' Try to load logging configuration from a file. Set level to INFO if failed. ''' if not force_setup and ChirpCLI.SETUP_COMPLETED: logging.debug("Master loggin...
Override root logger's level def config_logging(args): ''' Override root logger's level ''' if args.quiet: logging.getLogger().setLevel(logging.CRITICAL) elif args.verbose: logging.getLogger().setLevel(logging.DEBUG)
Add a task parser def add_task(self, task, func=None, **kwargs): ''' Add a task parser ''' if not self.__tasks: raise Exception("Tasks subparsers is disabled") if 'help' not in kwargs: if func.__doc__: kwargs['help'] = func.__doc__ task_parser = s...
Add verbose & quiet options def add_vq(self, parser): ''' Add verbose & quiet options ''' group = parser.add_mutually_exclusive_group() group.add_argument("-v", "--verbose", action="store_true") group.add_argument("-q", "--quiet", action="store_true")
Enable --version and -V to show version information def add_version_func(self, show_version): ''' Enable --version and -V to show version information ''' if callable(show_version): self.__show_version_func = show_version else: self.__show_version_func = lambda cli, args:...
Lazy logger def logger(self): ''' Lazy logger ''' if self.__logger is None: self.__logger = logging.getLogger(self.__name) return self.__logger
Run the app def run(self, func=None): ''' Run the app ''' args = self.parser.parse_args() if self.__add_vq is not None and self.__config_logging: self.__config_logging(args) if self.__show_version_func and args.version and callable(self.__show_version_func): self...
Print header block in text mode def header(*msg, level='h1', separator=" ", print_out=print): ''' Print header block in text mode ''' out_string = separator.join(str(x) for x in msg) if level == 'h0': # box_len = 80 if len(msg) < 80 else len(msg) box_len = 80 print_out('+' + '-'...
Fetch the next two values def fetch(self, value_obj=None): ''' Fetch the next two values ''' val = None try: val = next(self.__iterable) except StopIteration: return None if value_obj is None: value_obj = Value(value=val) else: ...
Keys are sorted based on report order (i.e. some keys to be shown first) Related: see sorted_by_count def get_report_order(self): ''' Keys are sorted based on report order (i.e. some keys to be shown first) Related: see sorted_by_count ''' order_list = [] for x i...
Return report content as a string if mode == STRINGIO else an empty string def content(self): ''' Return report content as a string if mode == STRINGIO else an empty string ''' if isinstance(self.__report_file, io.StringIO): return self.__report_file.getvalue() else: ret...
Format table to print out def format(self): ''' Format table to print out ''' self.max_lengths = [] for row in self.rows: if len(self.max_lengths) < len(row): self.max_lengths += [0] * (len(row) - len(self.max_lengths)) for idx, val in enumerate(r...
Get full filename (with extension) def getfullfilename(file_path): ''' Get full filename (with extension) ''' warnings.warn("getfullfilename() is deprecated and will be removed in near future. Use chirptext.io.write_file() instead", DeprecationWarning) if file_path: return o...
Change extension of a file_path to something else (provide None to remove) def replace_ext(file_path, ext): ''' Change extension of a file_path to something else (provide None to remove) ''' if not file_path: raise Exception("File path cannot be empty") dirname = os.path.dirname(fil...
Change the file name in a path but keep the extension def replace_name(file_path, new_name): ''' Change the file name in a path but keep the extension ''' if not file_path: raise Exception("File path cannot be empty") elif not new_name: raise Exception("New name cannot b...
Get all child folders of a folder def get_child_folders(path): ''' Get all child folders of a folder ''' path = FileHelper.abspath(path) return [dirname for dirname in os.listdir(path) if os.path.isdir(os.path.join(path, dirname))]
Get all child files of a folder def get_child_files(path): ''' Get all child files of a folder ''' path = FileHelper.abspath(path) return [filename for filename in os.listdir(path) if os.path.isfile(os.path.join(path, filename))]
Delete a file def remove_file(filepath): ''' Delete a file ''' try: os.remove(os.path.abspath(os.path.expanduser(filepath))) except OSError as e: if e.errno != errno.ENOENT: raise
Pattern to filename def _ptn2fn(self, pattern): ''' Pattern to filename ''' return [pattern.format(wd=self.working_dir, n=self.__name, mode=self.__mode), pattern.format(wd=self.working_dir, n='{}.{}'.format(self.__name, self.__mode), mode=self.__mode)]
Add a potential config file pattern def add_potential(self, *patterns): ''' Add a potential config file pattern ''' for ptn in patterns: self.__potential.extend(self._ptn2fn(ptn))
Locate config file def locate_config(self): ''' Locate config file ''' for f in self.__potential: f = FileHelper.abspath(f) if os.path.isfile(f): return f return None
Read config automatically if required def config(self): ''' Read config automatically if required ''' if self.__config is None: config_path = self.locate_config() if config_path: self.__config = self.read_file(config_path) self.__config_path = con...
Read a configuration file and return configuration data def read_file(self, file_path): ''' Read a configuration file and return configuration data ''' getLogger().info("Loading app config from {} file: {}".format(self.__mode, file_path)) if self.__mode == AppConfig.JSON: return jso...
Load configuration from a specific file def load(self, file_path): ''' Load configuration from a specific file ''' self.clear() self.__config = self.read_file(file_path)
Retrieve a list of processes sorted by name. Args: sort_by_name (bool): Sort the list by name or by process ID's. Returns: list of (int, str) or list of (int, str, str): List of process id, process name and optional cmdline tuples. def get_processes(sort_by_name=True): ...
Find process by name or by argument in command line. Args: name (str): Process name to search for. arg (str): Command line argument for a process to search for. Returns: tea.process.base.IProcess: Process object if found. def find(name, arg=None): """Find process by name o...
Execute a command with arguments and wait for output. Arguments should not be quoted! Keyword arguments: env (dict): Dictionary of additional environment variables. wait (bool): Wait for the process to finish. Example:: >>> code = 'import sys;sys.stdout.write('out');sys...
Execute a command with arguments and wait for output. If execution was successful function will return True, if not, it will log the output using standard logging and return False. def execute_and_report(command, *args, **kwargs): """Execute a command with arguments and wait for output. If exec...
Read public keys from specified user's authorized_keys file. args: username (str): username. returns: list: Authorised keys for the specified user. def read_authorized_keys(username=None): """Read public keys from specified user's authorized_keys file. args: username (str): u...
Write public keys back to authorized_keys file. Create keys directory if it doesn't already exist. args: user (User): Instance of User containing keys. returns: list: Authorised keys for the specified user. def write_authorized_keys(user=None): """Write public keys back to authorized_keys...
Return a base64 encoding of the key. returns: str: base64 encoding of the public key def b64encoded(self): """Return a base64 encoding of the key. returns: str: base64 encoding of the public key """ if self._b64encoded: return text_type(self...
Return raw key. returns: str: raw key def raw(self): """Return raw key. returns: str: raw key """ if self._raw: return text_type(self._raw).strip("\r\n") else: return text_type(base64decode(self._b64encoded)).strip("\r\n"...
Prepares inner config parser for config stored at ``endpoint``. :return: an instance of :class:`~django_docker_helpers.config.backends.base.BaseParser` :raises config.exceptions.KVStorageKeyDoestNotExist: if specified ``endpoint`` does not exists :raises config.exceptions.KVStorageValueIsEmpt...
Reads a value of ``variable_path`` from consul kv storage. :param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type...
Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware graph def add_format(mimetype, format, requires_context=False): """ Regis...
Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware graph def add_format(self, mimetype, format, requires_context=False): ...
Returns the default mimetype def get_default_mimetype(self): """ Returns the default mimetype """ mimetype = self.default_mimetype if mimetype is None: # class inherits from module default mimetype = DEFAULT_MIMETYPE if mimetype is None: # module is set to None? mimetype = 'application/rdf+xml' return ...
Returns the mimetype if the client sends */* def get_wildcard_mimetype(self): """ Returns the mimetype if the client sends */* """ mimetype = self.wildcard_mimetype if mimetype is None: # class inherits from module default mimetype = WILDCARD_MIMETYPE if mimetype is None: # module is set to None? mimetyp...
Returns what mimetype the client wants to receive Parses the given Accept header and returns the best one that we know how to output An empty Accept will default to application/rdf+xml An Accept with */* use rdf+xml unless a better match is found An Accept that doesn't match anything will ...
Get the serialization format for the given mimetype def get_serialize_format(self, mimetype): """ Get the serialization format for the given mimetype """ format = self.formats.get(mimetype, None) if format is None: format = formats.get(mimetype, None) return format
Returns what (mimetype,format) the client wants to receive Parses the given Accept header and picks the best one that we know how to output Returns (mimetype, format) An empty Accept will default to rdf+xml An Accept with */* use rdf+xml unless a better match is found An Accept that ...
Returns whether this client's Accept header indicates that the client wants to receive RDF def wants_rdf(self, accepts): """ Returns whether this client's Accept header indicates that the client wants to receive RDF """ mimetype = mimeparse.best_match(all_mimetypes + self.all_mimetypes + [WILDCARD], ...
Sends a HTTP request and implements a retry logic. Arguments: session (obj): A client aiohttp session object method (str): Method to use url (str): URL for the request retries (int): Number of times to retry in case of failure interval (float): Time to wait before retries ...
Generates the sitemap file and the stylesheet file and puts them into the content dir. :param writer: the writer instance :type writer: pelican.writers.Writer def generate_output(self, writer): """ Generates the sitemap file and the stylesheet file and puts them into the content dir. ...
Returns the URL for the given DIRECT_TEMPLATE name. Favors ${DIRECT_TEMPLATE}_SAVE_AS over the default path. :param name: name of the direct template :return: str def __get_direct_template_url(self, name): """ Returns the URL for the given DIRECT_TEMPLATE name. Favors ${...
Creates the url nodes for pelican.urlwrappers.Category and pelican.urlwrappers.Tag. :param elements: list of wrapper elements :type elements: list :return: the processes urls as HTML :rtype: str def __process_url_wrapper_elements(self, elements): """ Creates the url node...
Creates the required <url> node for the sitemap xml. :param content: the content class to handle :type content: pelican.contents.Content | None :param content_type: the type of the given content to match settings.EXTENDED_SITEMAP_PLUGIN :type content_type; str :param url; if give...
Check I can identify the necessary commands for managing users. def get_missing_commands(_platform): """Check I can identify the necessary commands for managing users.""" missing = list() if _platform in ('Linux', 'OpenBSD'): if not LINUX_CMD_USERADD: missing.append('useradd') i...
Execute a command and return the stdout and stderr. def execute_command(command=None): """Execute a command and return the stdout and stderr.""" process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stdin = process.communicate() process.wait() return (stdout, s...
Return base64 encoded representation of a string. def base64encode(_input=None): """Return base64 encoded representation of a string.""" if PY2: # pragma: no cover return base64.b64encode(_input) elif PY3: # pragma: no cover if isinstance(_input, bytes): return base64.b64encod...
Take a base64 encoded string and return the decoded string. def base64decode(_input=None): """Take a base64 encoded string and return the decoded string.""" missing_padding = 4 - len(_input) % 4 if missing_padding: _input += '=' * missing_padding if PY2: # pragma: no cover return base6...
Read the sudoers entry for the specified user. args: username (str): username. returns:`r str: sudoers entry for the specified user. def read_sudoers(): """ Read the sudoers entry for the specified user. args: username (str): username. returns:`r str: sudoers ent...
Write sudoers entry. args: user (User): Instance of User containing sudoers entry. returns: str: sudoers entry for the specified user. def write_sudoers_entry(username=None, sudoers_entry=None): """Write sudoers entry. args: user (User): Instance of User containing sudoers en...
Find the sudoers entry in the sudoers file for the specified user. args: username (str): username. sudoers_entries (list): list of lines from the sudoers file. returns:`r str: sudoers entry for the specified user. def get_sudoers_entry(username=None, sudoers_entries=None): """ Fin...
r"""Prepend or append a string to the current documentation of the function. This decorator should be robust even if ``func.__doc__`` is None (for example, if -OO was passed to the interpreter). Usage:: @docstring('Appended this line') def func(): "This docstring will have a l...