code stringlengths 1 18.2k |
|---|
def verify_sig(signed_request, secret, issuer=None, algorithms=None, expected_aud=None): """ Verify the JWT signature. Given a raw JWT, this verifies it was signed with *secret*, decodes it, and returns the JSON dict. """ if not issuer: issuer = _get_issuer(signed_request=signed_request) signed_request = _to_bytes(sign... |
def _re_raise_as(NewExc, *args, **kw): """Raise a new exception using the preserved traceback of the last one.""" etype, val, tb = sys.exc_info() raise NewExc(*args, **kw), None, tb |
def generators(): """ List all the available generators. """ from populous import generators base = generators.Generator for name in dir(generators): generator = getattr(generators, name) if isinstance(generator, type) and issubclass(generator, base): name = generator.__name__ doc = (generator.__doc__ or '').strip() if... |
def snake_case(string): ''' Takes a string that represents for example a class name and returns the snake case version of it. It is used for model-to-key conversion ''' s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() |
def limit(limit, every=1): """This decorator factory creates a decorator that can be applied to functions in order to limit the rate the function can be invoked. The rate is `limit` over `every`, where limit is the number of invocation allowed every `every` seconds. limit(4, 60) creates a decorator that limit the funct... |
def value_or_default(self, value): ''' Returns the given value or the specified default value for this field ''' if value is None: if callable(self.default): return self.default() else: return self.default return value |
def validate_required(self, value): ''' Validates the given value agains this field's 'required' property ''' if self.required and (value is None or value==''): raise MissingFieldError(self.name) |
def recover(self, data, redis=None): ''' Retrieve this field's value from the database ''' value = data.get(self.name) if value is None or value == 'None': return None return str(value) |
def save(self, value, redis, *, commit=True): ''' Sets this fields value in the databse ''' value = self.prepare(value) if value is not None: redis.hset(self.obj.key(), self.name, value) else: redis.hdel(self.obj.key(), self.name) if self.index: key = self.key() if self.name in self.obj._old: redis.hdel(key, self.obj._... |
def delete(self, redis): ''' Deletes this field's value from the databse. Should be implemented in special cases ''' if self.index: redis.hdel(self.key(), getattr(self.obj, self.name)) |
def validate(self, value, redis): ''' Validates data obtained from a request and returns it in the apropiate format ''' # cleanup if type(value) == str: value = value.strip() value = self.value_or_default(value) # validation self.validate_required(value) if self.regex and not re.match(self.regex, value, flags=re.ASCII)... |
def delete(self, redis): ''' Deletes this field's value from the databse. Should be implemented in special cases ''' value = getattr(self.obj, self.name) redis.srem(self.key() + ':' + value, self.obj.id) |
def init(self, value): ''' hash passwords given in the constructor ''' value = self.value_or_default(value) if value is None: return None if is_hashed(value): return value return make_password(value) |
def validate(self, value, redis): ''' hash passwords given via http ''' value = super().validate(value, redis) if is_hashed(value): return value return make_password(value) |
def validate(self, value, redis): ''' Validates data obtained from a request in ISO 8061 and returns it in Datetime data type ''' value = self.value_or_default(value) self.validate_required(value) if value is None: return None if type(value) == str: try: value = datetime.datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ') e... |
def fill(self, **kwargs): ''' Loads the relationships into this model. They are not loaded by default ''' setattr(self.obj, self.name, self.get(**kwargs)) |
def get(self, **kwargs): ''' Returns this relation ''' redis = type(self.obj).get_redis() related = list(map( lambda id : self.model().get(debyte_string(id)), self.get_related_ids(redis, **kwargs) )) return related |
def get_acronyms(fulltext): """Find acronyms and expansions from the fulltext. If needed, acronyms can already contain a dictionary of previously found acronyms that will be merged with the current results. """ acronyms = {} for m in ACRONYM_BRACKETS_REGEX.finditer(fulltext): acronym = DOTS_REGEX.sub("", m.group(1)) po... |
if re.search(pattern, match.group(1), re.I) is not None: _add_expansion_to_acronym_dict(acronym, match.group(1), 0, acronyms) continue pattern = "\W(" for char in acronym[:-1]: pattern += "%s\w+\W+" % char pattern += "%s\w+)$" % acronym[-1] # LEVEL 1: expansion with uppercase initials match = re.search(pattern, potenti... |
= _words(potential_expansion_stripped) reversed_words.reverse() reversed_acronym = list(acronym.lower()) reversed_acronym.reverse() index0 = 0 index1 = 0 word = "" try: while index0 < len(reversed_acronym) and index1 < len( reversed_words): word = reversed_words[index1] if index0 + 1 < len(reversed_words): next_word = ... |
= potential_expansion.lower().rfind(word) _add_expansion_to_acronym_dict(acronym, potential_expansion[start:], 4, acronyms) continue # LEVEL 5: expansion with fuzzy initials reversed_words = _words(potential_expansion.lower()) reversed_words.reverse() reversed_acronym = list(acronym.lower()) reversed_acronym.reverse() ... |
except IndexError: word = "" if not word.startswith(char): word = "" if word: start = potential_expansion.lower().rfind(word) _add_expansion_to_acronym_dict(acronym, potential_expansion[start:], 5, acronyms) continue return acronyms |
def _add_expansion_to_acronym_dict(acronym, expansion, level, dictionary): """Add an acronym to the dictionary. Takes care of avoiding duplicates and keeping the expansion marked with the best score. """ if len(acronym) >= len(expansion) or acronym in expansion: return for punctuation in re.findall("\W", expansion): # ... |
def _equivalent_expansions(expansion1, expansion2): """Compare two expansions.""" words1 = _words(expansion1) words2 = _words(expansion2) simplified_versions = [] if words1 == words2: return True for words in (words1, words2): store = [] for word in words: store.append(word[:5]) simplified_versions.append("".join(store... |
def get(self, url, parameters=None): """ Convenience method for requesting to google with proper cookies/params. """ getString = self.getParameters(parameters) headers = {'Authorization':'GoogleLogin auth=%s' % self.auth_token} req = requests.get(url + "?" + getString, headers=headers) return req.text |
def post(self, url, postParameters=None, urlParameters=None): """ Convenience method for requesting to google with proper cookies/params. """ if urlParameters: url = url + "?" + self.getParameters(urlParameters) headers = {'Authorization':'GoogleLogin auth=%s' % self.auth_token, 'Content-Type': 'application/x-www-form-... |
def _getAuth(self): """ Main step in authorizing with Reader. Sends request to Google ClientAuthMethod URL which returns an Auth token. Returns Auth token or raises IOError on error. """ parameters = { 'service' : 'reader', 'Email' : self.username, 'Passwd' : self.password, 'accountType' : 'GOOGLE'} req = requests.post... |
def _getToken(self): """ Second step in authorizing with Reader. Sends authorized request to Reader token URL and returns a token value. Returns token or raises IOError on error. """ headers = {'Authorization':'GoogleLogin auth=%s' % self.auth_token} req = requests.get(ReaderUrl.API_URL + 'token', headers=headers) if r... |
def post(self, url, postParameters=None, urlParameters=None): """ Convenience method for requesting to google with proper cookies/params. """ if self.authorized_client: if urlParameters: getString = self.getParameters(urlParameters) req = urllib2.Request(url + "?" + getString) else: req = urllib2.Request(url) postStrin... |
def get(self, url, parameters=None): """ Convenience method for requesting to google with proper cookies/params. """ if not self.access_token: raise IOError("No authorized client available.") if parameters is None: parameters = {} parameters.update({'access_token': self.access_token, 'alt': 'json'}) request = requests.... |
def post(self, url, postParameters=None, urlParameters=None): """ Convenience method for requesting to google with proper cookies/params. """ if not self.access_token: raise IOError("No authorized client available.") if not self.action_token: raise IOError("Need to generate action token.") if urlParameters is None: url... |
def _setupHttp(self): """ Setup an HTTP session authorized by OAuth2. """ if self._http == None: http = httplib2.Http() self._http = self._credentials.authorize(http) |
def get(self, url, parameters=None): """ Implement libgreader's interface for authenticated GET request """ if self._http == None: self._setupHttp() uri = url + "?" + self.getParameters(parameters) response, content = self._http.request(uri, "GET") return content |
def post(self, url, postParameters=None, urlParameters=None): """ Implement libgreader's interface for authenticated POST request """ if self._action_token == None: self._action_token = self.get(ReaderUrl.ACTION_TOKEN_URL) if self._http == None: self._setupHttp() uri = url + "?" + self.getParameters(urlParameters) post... |
def parse_Element(self, node): """Parse an `ELEMENT_NODE`. This calls specific `do_<tagName>` handers for different elements. If no handler is available the `generic_parse` method is called. All tagNames specified in `self.ignores` are simply ignored. """ name = node.tagName ignores = self.ignores if name in ignores: r... |
def generic_parse(self, node, pad=0): """A Generic parser for arbitrary tags in a node. Parameters: - node: A node in the DOM. - pad: `int` (default: 0) If 0 the node data is not padded with newlines. If 1 it appends a newline after parsing the childNodes. If 2 it pads before and after the nodes are processed. Defaults... |
def clean_pieces(self, pieces): """Cleans the list of strings given as `pieces`. It replaces multiple newlines by a maximum of 2 and returns a new list. It also wraps the paragraphs nicely. """ ret = [] count = 0 for i in pieces: if i == '\n': count = count + 1 else: if i == '";': if count: ret.append('\n') elif count ... |
def _format_json(self, ans, q): """ Generate a json response string. """ params = {} try: params['indent'] = int(q.get('indent')[0]) except: pass return json.dumps(ans, **params)+'\n' |
def _format(self, ans, q): """ Returns the response tuple according to the selected format. A format is available if the method "_format_xxx" is callable. The default format is json. """ if 'fmt' in q: fmt = q['fmt'][0] else: fmt = 'json' fmt = fmt.lower() if fmt in self._formatters: return (200, self._formatters[fmt](... |
def version(self, path, postmap=None, **params): """ Return the taskforce version. Supports standard options. """ q = httpd.merge_query(path, postmap) ans = { 'taskforce': taskforce_version, 'python': '.'.join(str(x) for x in sys.version_info[:3]), } ans['platform'] = { 'system': platform.system(), } # Add in some extr... |
def config(self, path, postmap=None, **params): """ Return the running configuration which almost always matches the configuration in the config file. During a reconfiguration, it may be transitioning to the new state, in which case it will be different to the pending config. Neither the running or pending configuratio... |
def tasks(self, path, postmap=None, **params): """ Return the task status. This delves into the operating structures and picks out information about tasks that is useful for status monitoring. For each task, the response includes: control - The active task control value, whoich may have been changed via the management ... |
stamp when the process started. started_t - The Unix time_t of when the process started. status - The exit code for the last time this process exited. exit - The status translated for human consumption. Not that the status and exit values are not cleared if the process has successfully restarted. Supports standard opti... |
= utils.time2iso(p.started) if p.exited is not None: proc['exited_t'] = p.exited proc['exited'] = utils.time2iso(p.exited) if p.pending_sig is not None: # pragma: no cover proc['exit_pending'] = True info['processes'].append(proc) ans[name] = info return self._format(ans, q) |
def list_attributes(self): """ Returns the Node attributes names. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.list_attributes() ['attributeB', 'attributeA'] :return: Attributes names. :rtype: list """ return [attribute for attribute, value in self.iteritems() ... |
def get_attributes(self): """ Returns the Node attributes. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(value="A"), attributeB=Attribute(value="B")) >>> node_a.get_attributes() [<Attribute object at 0x7fa471d3b5e0>, <Attribute object at 0x101e6c4a0>] :return: Attributes. :rtype: list """ return [at... |
def attribute_exists(self, name): """ Returns if given attribute exists in the node. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.attribute_exists("attributeA") True >>> node_a.attribute_exists("attributeC") False :param name: Attribute name. :type name: unicod... |
def add_attribute(self, name, value): """ Adds given attribute to the node. Usage:: >>> node_a = AbstractNode() >>> node_a.add_attribute("attributeA", Attribute()) True >>> node_a.list_attributes() [u'attributeA'] :param name: Attribute name. :type name: unicode :param value: Attribute value. :type value: Attribute :re... |
def remove_attribute(self, name): """ Removes given attribute from the node. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.remove_attribute("attributeA") True >>> node_a.list_attributes() ['attributeB'] :param name: Attribute name. :type name: unicode :return: M... |
def parent(self, value): """ Setter for **self.__parent** attribute. :param value: Attribute value. :type value: AbstractNode or AbstractCompositeNode """ if value is not None: assert issubclass(value.__class__, AbstractNode), "'{0}' attribute: '{1}' is not a '{2}' subclass!".format( "parent", value, AbstractNode.__cla... |
def children(self, value): """ Setter for **self.__children** attribute. :param value: Attribute value. :type value: list """ if value is not None: assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format("children", value) for element in value: assert issubclass(element.__class__, AbstractNode),... |
def child(self, index): """ Returns the child associated with given index. Usage:: >>> node_b = AbstractCompositeNode("MyNodeB") >>> node_c = AbstractCompositeNode("MyNodeC") >>> node_a = AbstractCompositeNode("MyNodeA", children=[node_b, node_c]) >>> node_a.child(0) <AbstractCompositeNode object at 0x10107b6f0> >>> no... |
def index_of(self, child): """ Returns the given child index. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_a.index_of(node_b) 0 >>> node_a.index_of(node_c) 1 :param child: Child node. :type chil... |
def add_child(self, child): """ Adds given child to the node. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB") >>> node_a.add_child(node_b) True >>> node_a.children [<AbstractCompositeNode object at 0x10107afe0>] :param child: Child node. :type child: AbstractNode or A... |
def remove_child(self, index): """ Removes child at given index from the Node children. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_a.remove_child(1) True >>> [child.name for child in node_a.ch... |
def insert_child(self, child, index): """ Inserts given child at given index. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_d = AbstractCompositeNode("MyNodeD") >>> node_a.insert_child(node_d, 1)... |
def sort_children(self, attribute=None, reverse_order=False): """ Sorts the children using either the given attribute or the Node name. :param attribute: Attribute name used for sorting. :type attribute: unicode :param reverse_order: Sort in reverse order. :type reverse_order: bool :return: Method success. :rtype: bool... |
def find_children(self, pattern=r".*", flags=0, candidates=None): """ Finds the children matching the given patten. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> node_a.find_children("c", re.IGNORECAS... |
def find_family(self, pattern=r".*", flags=0, node=None): """ Returns the Nodes from given family. :param pattern: Matching pattern. :type pattern: unicode :param flags: Matching regex flags. :type flags: int :param node: Node to start walking from. :type node: AbstractNode or AbstractCompositeNode or Object :return: F... |
def list_node(self, tab_level=-1): """ Lists the current Node and its children. Usage:: >>> node_a = AbstractCompositeNode("MyNodeA") >>> node_b = AbstractCompositeNode("MyNodeB", node_a) >>> node_c = AbstractCompositeNode("MyNodeC", node_a) >>> print node_a.list_node() |----'MyNodeA' |----'MyNodeB' |----'MyNodeC' :par... |
def add_repositories(): """ Adds additional sources as defined in LINUX_PACKAGE_REPOSITORIES. """ if not env.overwrite and env.LINUX_PACKAGE_REPOSITORIES == server_state('linux_package_repositories'): return if env.verbosity: print env.host, "UNCOMMENTING SOURCES in /etc/apt/sources.list and adding PPAs" if contains(fi... |
def add_user(username='',password='',group='', site_user=False): """ Adds the username """ if group: group = '-g %s'% group if not site_user: run('echo %s:%s > /tmp/users.txt'% (username,password)) if not site_user: sudo('useradd -m -s /bin/bash %s %s'% (group,username)) sudo('chpasswd < /tmp/users.txt') sudo('rm -rf /... |
def change_ssh_port(): """ For security woven changes the default ssh port. """ host = normalize(env.host_string)[1] after = env.port before = str(env.DEFAULT_SSH_PORT) host_string=join_host_strings(env.user,host,before) with settings(host_string=host_string, user=env.user): if env.verbosity: print env.host, "CHANGING ... |
def disable_root(): """ Disables root and creates a new sudo user as specified by HOST_USER in your settings or your host_string The normal pattern for hosting is to get a root account which is then disabled. returns True on success """ def enter_password(): password1 = getpass.getpass(prompt='Enter the password for %s... |
new or existing account you wish to use to setup and deploy to your node?", default=sudo_user) else: root_user = env.ROOT_USER sudo_user = env.user original_password = env.get('HOST_PASSWORD','') host_string=join_host_strings(root_user,host,str(env.DEFAULT_SSH_PORT)) with settings(host_string=host_string, key_filename=... |
-rf /tmp/sudoers.tmp') if env.key_filename: sudo('mkdir -p /home/%s/.ssh'% sudo_user) sudo('cp -f ~/.ssh/authorized_keys /home/%s/.ssh/authorized_keys'% sudo_user) sudo('chown -R %s:sudo /home/%s/.ssh'% (sudo_user,sudo_user)) env.password = original_password #finally disable root host_string=join_host_strings(sudo_user... |
def install_packages(): """ Install a set of baseline packages and configure where necessary """ if env.verbosity: print env.host, "INSTALLING & CONFIGURING NODE PACKAGES:" #Get a list of installed packages p = run("dpkg -l | awk '/ii/ {print $2}'").split('\n') #Remove apparmor - TODO we may enable this later if env.ov... |
env.installed_packages[env.host] = packages if env.overwrite and 'apache2' in env.installed_packages[env.host]: #some sensible defaults -might move to putting this config in a template sudo("rm -f /etc/apache2/sites-enabled/000-default") sed('/etc/apache2/apache2.conf',before='KeepAlive On',after='KeepAlive Off',use_su... |
build") |
def lsb_release(): """ Get the linux distribution information and return in an attribute dict The following attributes should be available: base, distributor_id, description, release, codename For example Ubuntu Lucid would return base = debian distributor_id = Ubuntu description = Ubuntu 10.04.x LTS release = 10.04 co... |
def port_is_open(): """ Determine if the default port and user is open for business. """ with settings(hide('aborts'), warn_only=True ): try: if env.verbosity: print "Testing node for previous installation on port %s:"% env.port distribution = lsb_release() except KeyboardInterrupt: if env.verbosity: print >> sys.stder... |
def restrict_ssh(rollback=False): """ Set some sensible restrictions in Ubuntu /etc/ssh/sshd_config and restart sshd UseDNS no #prevents dns spoofing sshd defaults to yes X11Forwarding no # defaults to no AuthorizedKeysFile %h/.ssh/authorized_keys uncomments PasswordAuthentication no and restarts sshd """ if not rollba... |
point ssh %s@%s -p%s"% (env.user, env.host, env.port) c_text = 'Would you like to disable password login and use only ssh key authentication' proceed = confirm(c_text,default=False) if not env.INTERACTIVE or proceed or env.DISABLE_SSH_PASSWORD: #uncomments PasswordAuthentication no and restarts uncomment(sshd_config,'#... |
def set_timezone(rollback=False): """ Set the time zone on the server using Django settings.TIME_ZONE """ if not rollback: if contains(filename='/etc/timezone', text=env.TIME_ZONE, use_sudo=True): return False if env.verbosity: print env.host, "CHANGING TIMEZONE /etc/timezone to "+env.TIME_ZONE _backup_file('/etc/timez... |
def setup_ufw(): """ Setup basic ufw rules just for ssh login """ if not env.ENABLE_UFW: return ufw_state = server_state('ufw_installed') if ufw_state and not env.overwrite or ufw_state == str(env.HOST_SSH_PORT): return #check for actual package ufw = run("dpkg -l | grep 'ufw' | awk '{print $2}'").strip() if not ufw: i... |
def setup_ufw_rules(): """ Setup ufw app rules from application templates and settings UFW_RULES """ #current rules current_rules = server_state('ufw_rules') if current_rules: current_rules = set(current_rules) else: current_rules = set([]) role = env.role_lookup[env.host_string] firewall_rules = set(env.firewall_rules... |
def uninstall_packages(): """ Uninstall unwanted packages """ p = server_state('packages_installed') if p: installed = set(p) else: return env.uninstalled_packages[env.host] = [] #first uninstall any that have been taken off the list packages = set(get_packages()) uninstall = installed - packages if uninstall and env.v... |
def upgrade_packages(): """ apt-get update and apt-get upgrade """ if env.verbosity: print env.host, "apt-get UPDATING and UPGRADING SERVER PACKAGES" print " * running apt-get update " sudo('apt-get -qqy update') if env.verbosity: print " * running apt-get upgrade" print " NOTE: apt-get upgrade has been known in rare c... |
def upload_etc(): """ Upload and render all templates in the woven/etc directory to the respective directories on the nodes Only configuration for installed packages will be uploaded where that package creates it's own subdirectory in /etc/ ie /etc/apache2. For configuration that falls in some other non package directo... |
len_dir = len(dir) if len_dir < length: length = len_dir env.project_template_dir = dir template_dir = os.path.join(os.path.split(os.path.realpath(__file__))[0],'templates','') default_templates = _get_template_files(template_dir) if env.project_template_dir: user_templates = _get_template_files(os.path.join(env.projec... |
def upload_ssh_key(rollback=False): """ Upload your ssh key for passwordless logins """ auth_keys = '/home/%s/.ssh/authorized_keys'% env.user if not rollback: local_user = getpass.getuser() host = socket.gethostname() u = '@'.join([local_user,host]) u = 'ssh-key-uploaded-%s'% u if not env.overwrite and server_state(u):... |
sudo('rm -rf /home/%s/.ssh') return |
def cable_to_text(cable, include_header): """\ Returns the header/content of the cable as text. """ if include_header: return u'\n\n'.join(cable.header, cable.content) return cable.content |
def generate_text_files(in_dir, out_dir, include_header=False): """\ Walks through the `in_dir` and generates text versions of the cables in the `out_dir`. """ for cable in cables_from_source(in_dir): out = codecs.open(out_dir + '/' + cable.reference_id + '.txt', 'wb', encoding='utf-8') out.write(cable_to_text(cable, i... |
def extract_stack(frame, context=10, exceptionsFrameSymbol=EXCEPTIONS_FRAME_SYMBOL): """ Extracts the stack from given frame while excluded any symbolized frame. :param frame: Frame. :type frame: Frame :param context: Context to extract. :type context: int :param exceptionsFrameSymbol: Stack trace frame tag. :type exce... |
def extract_arguments(frame): """ Extracts the arguments from given frame. :param frame: Frame. :type frame: object :return: Arguments. :rtype: tuple """ arguments = ([], None, None) try: source = textwrap.dedent("".join(inspect.getsourcelines(frame)[0]).replace("\\\n", "")) except (IOError, TypeError) as error: return... |
def extract_locals(trcback): """ Extracts the frames locals of given traceback. :param trcback: Traceback. :type trcback: Traceback :return: Frames locals. :rtype: list """ output = [] stack = extract_stack(get_inner_most_frame(trcback)) for frame, file_name, line_number, name, context, index in stack: args_names, name... |
def extract_exception(*args): """ Extracts the exception from given arguments or from :func:`sys.exc_info`. :param \*args: Arguments. :type \*args: \* :return: Extracted exception. :rtype: tuple """ cls, instance, trcback = sys.exc_info() exceptions = filter(lambda x: issubclass(type(x), BaseException), args) trcbacks ... |
def format_exception(cls, instance, trcback, context=1): """ | Formats given exception. | The code produce a similar output to :func:`traceback.format_exception` except that it allows frames to be excluded from the stack if the given stack trace frame tag is found in the frame locals and set **True**. :param cls: Excep... |
def format_report(cls, instance, trcback, context=1): """ Formats a report using given exception. :param cls: Exception class. :type cls: object :param instance: Exception instance. :type instance: object :param trcback: Traceback. :type trcback: Traceback :param context: Context being included. :type context: int :ret... |
frames.append("{0:>40}".format("Locals:")) for key, value in sorted(locals.iteritems()): frames.append("{0:>40} = {1}".format(key, value)) frames.append("") trcback = format_exception(cls, instance, trcback) return header, frames, trcback |
def base_exception_handler(*args): """ Provides the base exception handler. :param \*args: Arguments. :type \*args: \* :return: Definition success. :rtype: bool """ header, frames, trcback = format_report(*extract_exception(*args)) LOGGER.error("!> {0}".format(Constants.logging_separators)) map(lambda x: LOGGER.error("... |
def handle_exceptions(*args): """ | Handles exceptions. | It's possible to specify an user defined exception handler, if not, :func:`base_exception_handler` handler will be used. | The decorator uses given exceptions objects or the default Python `Exception <http://docs.python.org/library/exceptions.html#exceptions.Exc... |
except exceptions as error: for handler in handlers: handler(error) return handle_exceptions_wrapper return handle_exceptions_decorator |
def line(self, value): """ Setter for **self.__line** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("line", value) assert value > 0, "'{0}' attribute: '{1}' need to be exactly positive!".format("line", v... |
def update_parameters(url, parameters, encoding='utf8'): """ Updates a URL's existing GET parameters. :param url: a base URL to which to add additional parameters. :param parameters: a dictionary of parameters, any mix of unicode and string objects as the parameters and the values. :parameter encoding: the byte encodin... |
encoding. byte_parameters = [] for key, value in (existing_query_parameters + parameters.items()): if isinstance(key, unicode): key = key.encode(encoding) if isinstance(value, unicode): value = value.encode(encoding) byte_parameters.append((key, value)) # Generate the final URL with all of the updated parameters. Read ... |
def set_directory(path): """ | Creates a directory with given path. | The directory creation is delegated to Python :func:`os.makedirs` definition so that directories hierarchy is recursively created. :param path: Directory path. :type path: unicode :return: Definition success. :rtype: bool """ try: if not foundations.... |
def copy(source, destination): """ Copies given file or directory to destination. :param source: Source to copy from. :type source: unicode :param destination: Destination to copy to. :type destination: unicode :return: Method success. :rtype: bool """ try: if os.path.isfile(source): LOGGER.debug("> Copying '{0}' file ... |
def remove(path): """ Removes given path. :param path: Path to remove. :type path: unicode :return: Method success. :rtype: bool """ try: if os.path.isfile(path): LOGGER.debug("> Removing '{0}' file.".format(path)) os.remove(path) elif os.path.isdir(path): LOGGER.debug("> Removing '{0}' directory.".format(path)) shutil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.