code
stringlengths
1
18.2k
def publish(self, page): """ Publish the page in all languages. """ assert page.publisher_is_draft == True, "Page '%s' must be a draft!" % page publish_page(page, languages=self.languages)
def create_page(self, **extra_kwargs): """ Create page (and page title) in default language extra_kwargs will be pass to cms.api.create_page() e.g.: extra_kwargs={ "soft_root": True, "reverse_id": my_reverse_id, } """ with translation.override(self.default_language_code): # for evaluate the language name lazy translati...
# Create page else: log.debug("Use existing page: %s", page) created = False return page, created else: # Not a plugin page queryset = Title.objects.filter( language=self.default_language_code) queryset = queryset.filter(page__parent=parent) try: title = queryset.filter(slug=self.slug).first() except Title.DoesNotExist...
def create_title(self, page): """ Create page title in all other languages with cms.api.create_title() """ for language_code, lang_name in iter_languages(self.languages): try: title = Title.objects.get(page=page, language=language_code) except Title.DoesNotExist: slug = self.get_slug(language_code, lang_name) assert sl...
def get_add_plugin_kwargs(self, page, no, placeholder, language_code, lang_name): """ Return "content" for create the plugin. Called from self.add_plugins() """ return { "plugin_type": 'TextPlugin', # djangocms_text_ckeditor "body": self.get_dummy_text(page, no, placeholder, language_code, lang_name) }
def add_plugins(self, page, placeholder): """ Add a "TextPlugin" in all languages. """ for language_code, lang_name in iter_languages(self.languages): for no in range(1, self.dummy_text_count + 1): add_plugin_kwargs = self.get_add_plugin_kwargs( page, no, placeholder, language_code, lang_name) log.info( 'add plugin to ...
def get_or_create_placeholder(self, page, placeholder_slot): """ Add a placeholder if not exists. """ placeholder, created = get_or_create_placeholder( page, placeholder_slot, delete_existing=self.delete_first) return placeholder, created
def fill_content(self, page, placeholder_slot): """ Add a placeholder to the page. Here we add a "TextPlugin" in all languages. """ if len(placeholder_slot) == 1: raise RuntimeError(placeholder_slot) placeholder, created = self.get_or_create_placeholder( page, placeholder_slot) self.add_plugins(page, placeholder)
def create(self): """ Create the plugin page in all languages and fill dummy content. """ plugin = CMSPlugin.objects.filter(plugin_type=self.apphook) if plugin.exists(): log.debug('Plugin page for "%s" plugin already exist, ok.', self.apphook) raise plugin page, created = super(CmsPluginPageCreator, self).create() if c...
def get_title(self, language_code, lang_name): """ :return: 'title' string for cms.api.create_page() """ title = "%s %i-%i in %s" % (self.title_prefix, self.current_count, self.current_level, language_code) log.info(title) return title
def get_parent_page(self): """ For 'parent' in cms.api.create_page() """ if self.current_level == 1: # 'root' page return None else: return self.page_data[(self.current_level - 1, self.current_count)]
def translate_path(self, pth): """Translate a /-separated PATH to the local filename syntax.""" # initially copied from SimpleHTTPServer words = pth.split('/') words = filter(None, words) pth = self.location for word in words: # Do not allow path separators other than /, # drive names and . .. drive, word = os.path.spl...
def dict(self): """A dict that holds key/values for all of the properties in the object. :return: """ from collections import OrderedDict SKIP_KEYS = () return OrderedDict( (p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in SKIP_KEYS)
def column(self, source_header_or_pos): """ Return a column by name or position :param source_header_or_pos: If a string, a source header name. If an integer, column position :return: """ for c in self.columns: if c.source_header == source_header_or_pos: assert c.st_vid == self.vid return c elif c.position == source_he...
def add_column(self, position, source_header, datatype, **kwargs): """ Add a column to the source table. :param position: Integer position of the column started from 1. :param source_header: Name of the column, as it exists in the source file :param datatype: Python datatype ( str, int, float, None ) for the column :pa...
assert not c_by_pos or c_by_pos.vid == c.vid c.update( position=position, datatype=datatype.__name__ if isinstance(datatype, type) else datatype, **kwargs) elif c_by_pos: # FIXME This feels wrong; there probably should not be any changes to the both # of the table, since then it won't represent the previouls source. Ma...
def update_id(self, sequence_id=None): """Alter the sequence id, and all of the names and ids derived from it. This often needs to be don after an IntegrityError in a multiprocessing run""" from ..identity import GeneralNumber1 if sequence_id: self.sequence_id = sequence_id self.vid = str(GeneralNumber1('T', self.d_vid...
def table_convert_geometry(metadata, table_name): """Get table metadata from the database.""" from sqlalchemy import Table from ..orm import Geometry table = Table(table_name, metadata, autoload=True) for c in table.columns: # HACK! Sqlalchemy sees spatialte GEOMETRY types # as NUMERIC if c.name == 'geometry': c.type =...
def next_sequence_id(session, sequence_ids, parent_vid, table_class, force_query = False): """ Return the next sequence id for a object, identified by the vid of the parent object, and the database prefix for the child object. On the first call, will load the max sequence number from the database, but subsequence calls...
getting a number :return: """ from sqlalchemy import text seq_col = table_class.sequence_id.property.columns[0].name try: parent_col = table_class._parent_col except AttributeError: parent_col = table_class.d_vid.property.columns[0].name assert bool(parent_vid) key = (parent_vid, table_class.__name__) number = sequence...
def incver(o, prop_names): """Increment the version numbers of a set of properties and return a new object""" from ambry.identity import ObjectNumber d = {} for p in o.__mapper__.attrs: v = getattr(o, p.key) if v is None: d[p.key] = None elif p.key in prop_names: d[p.key] = str(ObjectNumber.increment(v)) else: if not h...
def coerce(cls, key, value): """Convert plain list to MutationList.""" if isinstance(value, string_types): value = value.strip() if value[0] == '[': # It's json encoded, probably try: value = json.loads(value) except ValueError: raise ValueError("Failed to parse JSON: '{}' ".format(value)) else: value = value.split(','...
def parse_view(query): """ Parses asql query to view object. Args: query (str): asql query Returns: View instance: parsed view. """ try: idx = query.lower().index('where') query = query[:idx] except ValueError: pass if not query.endswith(';'): query = query.strip() query += ';' result = _view_stmt.parseString(query) re...
def _flat_alias(t): """ Populates token (column or table) fields from parse result. """ t.name = t.parsed_name t.alias = t.parsed_alias[0] if t.parsed_alias else '' return t
def _build_join(t): """ Populates join token fields. """ t.source.name = t.source.parsed_name t.source.alias = t.source.parsed_alias[0] if t.source.parsed_alias else '' return t
def substitute_vids(library, statement): """ Replace all of the references to tables and partitions with their vids. This is a bit of a hack -- it ought to work with the parser, but instead it just looks for common SQL tokens that indicate an identifier. :param statement: an sqlstatement. String. :return: tuple: new_st...
numbers. Assume partition. raise NotObjectNumberError except NotObjectNumberError: # assume partition try: partition = library.partition(ident) partitions.add(partition.vid) new_parts.append(partition.vid) except NotFoundError: # Ok, maybe it is just a normal identifier... new_parts.append(ident) else: new_parts.append...
def find_indexable_materializable(sql, library): """ Parse a statement, then call functions to install, materialize or create indexes for partitions referenced in the statement. :param sql: :param materialize_f: :param install_f: :param index_f: :return: """ derefed, tables, partitions = substitute_vids(library, sql) i...
= source.name for j in parsed.joins: if j.source.alias: d[j.source.alias] = j.source.name return d def indexable_columns(aliases, parsed): indexes = [] for j in parsed.joins: if j and j.join_cols: for col in j.join_cols: if '.' in col: try: alias, col = col.split('.') if alias: indexes.append((aliases[alias], (col,))) ...
def update(self, rec=None, drop=None, tables=None, install=None, materialize=None, indexes=None, joins=0, views=0): """ Updates current record. Args: rec (FIMRecord): """ if not drop: drop = [] if not tables: tables = set() if not install: install = set() if not materialize: materialize = set() if not indexes: indexes ...
def support_level(self, support_level): """ Sets the support_level of this ProductReleaseRest. :param support_level: The support_level of this ProductReleaseRest. :type: str """ allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"] if support_level not in allowed_values: raise ValueErro...
def callLater(self, when, what, *a, **kw): """ Copied from twisted.internet.task.Clock, r20480. Fixes the bug where the wrong DelayedCall would sometimes be returned. """ dc = base.DelayedCall(self.seconds() + when, what, a, kw, self.calls.remove, lambda c: None, self.seconds) self.calls.append(dc) self.calls.sort(lamb...
def clockIsBroken(): """ Returns whether twisted.internet.task.Clock has the bug that returns the wrong DelayedCall or not. """ clock = Clock() dc1 = clock.callLater(10, lambda: None) dc2 = clock.callLater(1, lambda: None) if dc1 is dc2: return True else: return False
def get_scm_status(config, read_modules=False, repo_url=None, mvn_repo_local=None, additional_params=None): """ Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by default, although it can be requested to read the whole available module structure. :param ...
scm_status_cache["%s|False" % config.artifact] = result return result
def shrink_patch(patch_path, target_file): """ Shrinks a patch on patch_path to contain only changes for target_file. :param patch_path: path to the shrinked patch file :param target_file: filename of a file of which changes should be kept :return: True if the is a section containing changes for target_file, Flase othe...
content.endswith("\n"): content = content + "\n" patch_file.write(content) finally: if patch_file: patch_file.close() return True else: return False
def get_scm_info(directory, branch_id=False, read_only=False, filePath=None): """ Reads SCM info from the given directory. It can fill real commit ID into commit_id field or branch name. @param directory: directory name @param branch_id: reads commit ID if False (default) or branch name if True @param read_only: if Tru...
else: args = ["git", "--git-dir", directory + "/.git", "branch", "-v", "--no-abbrev"] command = Popen(args, stdout=PIPE, stderr=STDOUT) stdout = command.communicate()[0] if command.returncode: raise ScmException("Reading Git branch name and commit ID from %s failed. Output: %s" % (directory, stdout)) branch_name = None...
in stdout.split("\n"): if line.startswith("origin" + chr(9)) and line.endswith(" (fetch)"): parts = re.split("[\s]+", line, 3) origin_url = parts[1] break if branch_id: scminfo = ScmInfo("%s#%s" % (origin_url, branch_name)) else: scminfo = ScmInfo("%s#%s" % (origin_url, commit_id)) if read_only: if scminfo.get_scm_url(...
def new_status(self, new_status): """ Sets the new_status of this BuildSetStatusChangedEvent. :param new_status: The new_status of this BuildSetStatusChangedEvent. :type: str """ allowed_values = ["NEW", "DONE", "REJECTED"] if new_status not in allowed_values: raise ValueError( "Invalid value for `new_status` ({0}), mu...
def old_status(self, old_status): """ Sets the old_status of this BuildSetStatusChangedEvent. :param old_status: The old_status of this BuildSetStatusChangedEvent. :type: str """ allowed_values = ["NEW", "DONE", "REJECTED"] if old_status not in allowed_values: raise ValueError( "Invalid value for `old_status` ({0}), mu...
def command_serve(self, host='', port='8000', level='debug'): ''' Run development server with automated reload on code change:: ./manage.py app:serve [host] [port] [level] ''' logging.basicConfig(level=getattr(logging, level.upper()), format=self.format) if self.bootstrap: logger.info('Bootstraping...') self.bootstrap(...
parent process(not the child) to preserve PID of proccess # we use `pragma: no cover` here, because parent process cannot be # measured with coverage since it is ends with `execvp` if pid: # pragma: no cover os.closerange(3, MAXFD) os.waitpid(pid, 0) # reloading the code in parent process os.execvp(sys.executable, [sys...
def command_shell(self): ''' Shell command:: ./manage.py app:shell Executed with `self.shell_namespace` as local variables namespace. ''' from code import interact interact('Namespace {!r}'.format(self.shell_namespace), local=self.shell_namespace)
def declared_mixin(*bases): '''Create mix-in class with all assignments turned into methods decorated with declared_attr. Usage: @declared_mixin def FactoryFunction(): or with base mix-in class[es]: @declared_mixin(BaseMixIn1, BaseMixIn2) def FactoryFunction(): For example: @declared_mixin def WithParent(): parent_id =...
def elfhash(s): """ :param string: bytes >>> import base64 >>> s = base64.b64encode(b'hello world') >>> elfhash(s) 224648685 """ hash = 0 x = 0 for c in s: hash = (hash << 4) + c x = hash & 0xF0000000 if x: hash ^= (x >> 24) hash &= ~x return (hash & 0x7FFFFFFF)
def find_previous(element, l): """ find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2 """ length = len(l) for index, current in enumerate(l): # current is the last element if le...
def patch_match_hostname(): """Fixes https://github.com/boto/boto/issues/2836""" _old_match_hostname = ssl.match_hostname def _new_match_hostname(cert, hostname): if hostname.endswith('.s3.amazonaws.com'): pos = hostname.find('.s3.amazonaws.com') hostname = hostname[:pos].replace('.', '') + hostname[pos:] return _old_m...
def dict(self): """A dict that holds key/values for all of the properties in the object. :return: """ from collections import OrderedDict d = OrderedDict( [(p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in ('data',)]) if 'list' in self.data: d['bundle_count'] = len(self.data['list']) else: d[...
def update(self): """Cache the list into the data section of the record""" from ambry.orm.exc import NotFoundError from requests.exceptions import ConnectionError, HTTPError from boto.exception import S3ResponseError d = {} try: for k, v in self.list(full=True): if not v: continue d[v['vid']] = { 'vid': v['vid'], 'vnam...
def list(self, full=False): """List all of the bundles in the remote""" if self.is_api: return self._list_api(full=full) else: return self._list_fs(full=full)
def _update_fs_list(self): """Cache the full list for http access. This creates a meta file that can be read all at once, rather than requiring a list operation like S3 access does""" from json import dumps full_list = [ e[1] for e in self._list_fs(full=True) ] remote = self._fs_remote(self.url) remote.setcontents(os.p...
def checkin(self, package, no_partitions=False, force=False, cb=None): """ Check in a bundle package to the remote. :param package: A Database, referencing a sqlite database holding the bundle :param cb: a two argument progress callback: cb(message, num_records) :return: """ from ambry.orm.exc import NotFoundError if n...
def _put_metadata(self, fs_remote, ds): """Store metadata on a pyfs remote""" from six import text_type from fs.errors import ResourceNotFoundError identity = ds.identity d = identity.dict d['summary'] = ds.config.metadata.about.summary d['title'] = ds.config.metadata.about.title meta_stack = self._meta_infos(ds) def d...
def checkout(self, ref, cb=None): """Checkout a bundle from the remote. Returns a file-like object""" if self.is_api: return self._checkout_api(ref, cb=cb) else: return self._checkout_fs(ref, cb=cb)
def remove(self, ref, cb=None): """Check in a bundle to the remote""" if self.is_api: return self._remove_api(ref, cb) else: return self._remove_fs(ref, cb)
def s3(self, url, account_acessor=None, access=None, secret=None): """Setup an S3 pyfs, with account credentials, fixing an ssl matching problem""" from ambry.util.ambrys3 import AmbryS3FS from ambry.util import parse_url_to_dict import ssl pd = parse_url_to_dict(url) if account_acessor: account = account_acessor(pd['h...
def withdict(parser, token): """ Take a complete context dict as extra layer. """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("{% withdict %} expects one argument") nodelist = parser.parse(('endwithdict',)) parser.delete_first_token() return WithDictNode( nodelist=nodelist, context_expr=p...
def render(self, context): """ Render the tag, with extra context layer. """ extra_context = self.context_expr.resolve(context) if not isinstance(extra_context, dict): raise TemplateSyntaxError("{% withdict %} expects the argument to be a dictionary.") with context.push(**extra_context): return self.nodelist.render(con...
def filesessionmaker(sessionmaker, file_manager, file_managers=None): u'''Wrapper of session maker adding link to a FileManager instance to session.:: file_manager = FileManager(cfg.TRANSIENT_ROOT, cfg.PERSISTENT_ROOT) filesessionmaker(sessionmaker(...), file_manager) ''' registry = WeakKeyDictionary() if file_managers...
return session_maker
def oscillating_setpoint(_square_wave=False, shift=0): """A basic example of a target that you may want to approximate. If you have a thermostat, this is a temperature setting. This target can't change too often """ import math c = 0 while 1: if _square_wave: yield ((c % 300) < 150) * 30 + 20 c += 1 else: yield 10 * ma...
def bash_echo_metric(): """A very basic example that monitors a number of currently running processes""" import subprocess # import random # more predictable version of the metric cmd = ( 'set -o pipefail ' ' ; pgrep -f "^bash.*sleep .*from bash: started relay launcher"' ' | wc -l ' ) # less predictable version of the ...
def bash_echo_warmer(n): """A very basic example of how to create n additional tasks. This is a warmer function with randomly delayed effects on the bash_echo_metric and random task lengths to make the metric less predictable """ import subprocess import random cmd = ( 'set -o pipefail ' " ; sleep %s " " ; sh -c 'echo ...
def bash_echo_cooler(n): """A very basic example of how to destroy n running tasks This is a cooler function """ import subprocess cmd = ( 'set -o pipefile ' ' ; kill `pgrep -f "from bash: started relay launcher task"' ' | tail -n %s` 2>/dev/null' % n) subprocess.Popen(cmd, shell=True, executable='bash').wait()
def stop_if_mostly_diverging(errdata): """This is an example stop condition that asks Relay to quit if the error difference between consecutive samples is increasing more than half of the time. It's quite sensitive and designed for the demo, so you probably shouldn't use this is a production setting """ n_increases = s...
def has_resolved_dependencies(self): """Return True if all dependencies are in State.DONE""" for dependency in self.dependencies: if dependency.state != Task.State.DONE: return False return True
def dependencies_as_list(self): """Returns a list of dependency names.""" dependencies = [] for dependency in self.dependencies: dependencies.append(dependency.name) return dependencies
def get_task(self, name): """Get task by name or create it if it does not exists.""" if name in self.tasks.keys(): task = self.tasks[name] else: task = Task(name) self.tasks[name] = task return task
def get_next(self): """Return next task from the stack that has all dependencies resolved. Return None if there are no tasks with resolved dependencies or is there are no more tasks on stack. Use `count` to check is there are still some task left on the stack. raise ValueError if total ordering is not possible.""" self...
def count_buildable_tasks(self): """Count tasks that are new and have dependencies in non FAILED state.""" self.update_tasks_status() buildable_tasks_count = 0 for key, task in self.tasks.iteritems(): if task.state is Task.State.NEW: if self.are_dependencies_buildable(task): buildable_tasks_count += 1 logging.debug("Bu...
def filter_tasks(self, task_names, keep_dependencies=False): """If filter is applied only tasks with given name and its dependencies (if keep_keep_dependencies=True) are kept in the list of tasks.""" new_tasks = {} for task_name in task_names: task = self.get_task(task_name) if task not in new_tasks: new_tasks[task.nam...
def tsort(self): """Given a partial ordering, return a totally ordered list. part is a dict of partial orderings. Each value is a set, which the key depends on. The return value is a list of sets, each of which has only dependencies on items in previous entries in the list. raise ValueError if ordering is not possible ...
or missing dependencies)') return result
def build(self, build_execution_configuration, **kwargs): """ Triggers the build execution for a given configuration. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(re...
def build_task_completed(self, task_id, build_result, **kwargs): """ Notifies the completion of externally managed build task process. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def cal...
def cancel_bbuild(self, build_execution_configuration_id, **kwargs): """ Cancel the build execution defined with given executionConfigurationId. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >...
def _load_config(self): """ Load project's config and return dict. TODO: Convert the original dotted representation to hierarchical. """ config = import_module('config') variables = [var for var in dir(config) if not var.startswith('_')] return {var: getattr(config, var) for var in variables}
def get(name, default=None): """ Return variable by name from the project's config. Name can be a dotted path, like: 'rails.db.type'. """ if '.' not in name: raise Exception("Config path should be divided by at least one dot") section_name, var_path = name.split('.', 1) section = Config._data.get(section_name) return s...
def find_le(self, k): 'Return last item with a key <= k. Raise ValueError if not found.' i = bisect_right(self._keys, k) if i: return self._items[i - 1] raise ValueError('No item found with key at or below: %r' % (k,))
def find_le_index(self, k): 'Return last item with a key <= k. Raise ValueError if not found.' i = bisect_right(self._keys, k) if i: return i - 1 raise ValueError('No item found with key at or below: %r' % (k,))
def find_lt(self, k): """Return last item with a key < k. Raise ValueError if not found. """ i = bisect_left(self._keys, k) if i: return self._items[i - 1] raise ValueError('No item found with key below: %r' % (k,))
def find_ge_index(self, k): 'Return first item with a key >= equal to k. Raise ValueError if not found' i = bisect_left(self._keys, k) if i != len(self): return i raise ValueError('No item found with key at or above: %r' % (k,))
def get_dbg_brk_linux64(): ''' Return the current brk value in the debugged process (only x86_64 Linux) ''' # TODO this method is so weird, find a unused address to inject code not # the base address debugger = get_debugger() code = b'\x0f\x05' # syscall rax = debugger.get_reg("rax") rdi = debugger.get_reg("rdi") rip =...
def get_dbg_brk_linux32(): ''' Return the current brk value in the debugged process (only x86 Linux) ''' # TODO this method is so weird, find a unused address to inject code not # the base address debugger = get_debugger() code = b'\xcd\x80' # int 0x80 eax = debugger.get_reg("eax") ebx = debugger.get_reg("ebx") eip = d...
def start( loop: abstract_loop = None, interval: float = 0.5, hook: hook_type = None) -> asyncio.Task: """ Start the reloader. Create the task which is watching loaded modules and manually added files via ``watch()`` and reloading the process in case of modification. Attach this task to the loop. If ``hook`` is provide...
def strftime(dt, fmt): ''' `strftime` implementation working before 1900 ''' if _illegal_s.search(fmt): raise TypeError("This strftime implementation does not handle %s") if dt.year > 1900: return dt.strftime(fmt) fmt = fmt.replace('%c', '%a %b %d %H:%M:%S %Y')\ .replace('%Y', str(dt.year))\ .replace('%y', '{:04}'.form...
def library_pg(args, l, config): """Report on the operation of a Postgres Library database""" import tabulate import terminaltables from textwrap import fill from ambry.util.text import getTerminalSize import sys if args.connect: try: l.database.connection.execute('SELECT * FROM pg_stat_activity;') sys.exit(0) except E...
AS blocked_user, blocking_locks.pid AS blocking_pid, -- blocking_activity.usename AS blocking_user, blocked_activity.query AS blocked_statement, blocking_activity.query AS current_statement_in_blocking_process FROM pg_catalog.pg_locks blocked_locks JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.p...
= fill(row[2],(x-50)/2) row[3] = fill(row[3], (x-50)/2) rows.append(row) if rows: table = terminaltables.UnixTable([headers] + rows) print table.table if args.locks: headers = None rows = [] q = """ SELECT pid, database, mode, locktype, mode, relation::regclass, tuple, virtualxid FROM pg_locks ORDER BY pid ; """ for ro...
def _detect_timezone_windows(): """Detect timezone on the windows platform.""" # pylint: disable=global-statement global win32timezone_to_en # Try and fetch the key_name for the timezone using # Get(Dynamic)TimeZoneInformation tzi = DTZI_c() kernel32 = ctypes.windll.kernel32 getter = kernel32.GetTimeZoneInformation get...
territory = locale.getdefaultlocale()[0].split("_", 1)[1] olson_name = win32tz_map.win32timezones.get((win32tz_key_name, territory), win32tz_map.win32timezones.get(win32tz_key_name, None)) if not olson_name: return None if not isinstance(olson_name, str): olson_name = olson_name.encode("ascii") return pytz.timezone(ols...
def encrypt_password(raw_password, algorithm='sha1', salt=None): """ Returns a string of the hexdigest of the given plaintext password and salt using the given algorithm ('md5', 'sha1' or other supported by hashlib). """ if salt is None: salt = binascii.hexlify(os.urandom(3))[:5] else: salt = salt.encode('utf-8') raw_p...
def check_password(raw_password, enc_password): """ Returns a boolean of whether the raw_password was correct. Handles encryption formats behind the scenes. """ algo, salt, hsh = enc_password.split('$') return enc_password == encrypt_password(raw_password, algorithm=algo, salt=salt)
def login(self, template='login'): ''' This property will return component which will handle login requests. auth.login(template='login.html') ''' def _login(env, data): form = self._login_form(env) next = env.request.GET.get('next', '/') login_failed = False if env.request.method == 'POST': if form.accept(env.request....
def logout(self, redirect_to='/'): ''' This property will return component which will handle logout requests. It only handles POST requests and do not display any rendered content. This handler deletes session id from `storage`. If there is no session id provided or id is incorrect handler silently redirects to login u...
def content(self, content): """ Sets the content of this SupportLevelPage. :param content: The content of this SupportLevelPage. :type: list[str] """ allowed_values = ["UNRELEASED", "EARLYACCESS", "SUPPORTED", "EXTENDED_SUPPORT", "EOL"] if not set(content).issubset(set(allowed_values)): raise ValueError( "Invalid value...
def get_bpm_task_by_id(self, task_id, **kwargs): """ Get single (recently) active BPM task. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(respon...
def get_bpm_tasks(self, **kwargs): """ List of (recently) active BPM tasks. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thre...