def _stored(self, key, default=None): value, expires = default, None with ignored(OSError): with open(self.__file_path(key), 'rb') as file: with ignored(Exception): (value, expires) = pickle.load(file) return value, expires
def __delitem__(self, key): if not self.data: self.load() with ignored(KeyError): del self.data[key] if self.autosave: self.save()
def __call__(self, event): item = event.target['item'] instantiated = False raw = None if isinstance(item, FunctionType): raw = item elif not isinstance(item, str): initialized = item instantiated = True else: with ignored(ImportError, AttributeError): raw = load_definition_from_string(item) if not instantiated: if not raw: raise NameError( 'Cannot initialize dependency {0}, the module may not exist.' .format(item)) args, kwargs = [], {} if isinstance(raw, FunctionType): kwargs['container'] = self.container init = event.target.get('init', {}) if isinstance(init, dict): for key, val in init.items(): kwargs[key] = get_param_from_container(val, self.container) elif isinstance(init, list): for arg in init: args.append(get_param_from_container(arg, self.container)) initialized = raw(*args, **kwargs) return initialized
def __call__(self, event): item = event.target['item'] instantiated = False raw = None if isinstance(item, FunctionType): raw = item elif not isinstance(item, str): initialized = item instantiated = True else: with ignored(ImportError, AttributeError): raw = load_definition_from_string(item) if not instantiated: if not raw: raise NameError( 'Cannot initialize dependency {0}, the module may not exist.'.format(item)) args, kwargs = [], {} if isinstance(raw, FunctionType): kwargs['container'] = self.container init = event.target.get('init', {}) if isinstance(init, dict): for key, val in init.items(): kwargs[key] = get_param_from_container(val, self.container) elif isinstance(init, list): for arg in init: args.append(get_param_from_container(arg, self.container)) initialized = raw(*args, **kwargs) return initialized
def _load(self): try: with open(self.__file_path(), 'rb') as file: with ignored(Exception): return pickle.load(file) except: return ()
def _process_field_storage(fields, get=None, post=None, files=None): if not get: get = MultiDict() if not post: post = MultiDict() if not files: files = MultiDict() with ignored(Exception): for name in fields: field = fields[name] if isinstance(name, str) else name if isinstance(field, list): _process_field_storage(field, get, post, files) elif field.filename: # An uploaded file, create a new File tuple to resolve the # not indexable issue. files[field.name] = File(field.file, field.filename, field.name, field.type, field.type_options, field.disposition, field.disposition_options, field.headers) elif field.disposition or field.name not in get: post[field.name] = field.value else: if field.name not in get: get[field.name] = field.value return get, post, files
def _process_field_storage(fields, get=None, post=None, files=None): if not get: get = MultiDict() if not post: post = MultiDict() if not files: files = MultiDict() with ignored(Exception): for name in fields: field = fields[name] if isinstance(name, str) else name if isinstance(field, list): _process_field_storage(field, get, post, files) elif field.filename: # An uploaded file, create a new File tuple to resolve the # not indexable issue. files[field.name] = File( field.file, field.filename, field.name, field.type, field.type_options, field.disposition, field.disposition_options, field.headers) elif field.disposition or field.name not in get: post[field.name] = field.value else: if field.name not in get: get[field.name] = field.value return get, post, files
def build_route(self, **definition): """Converts a route definition into a specific route. """ for strategy in self._build_strategies: with ignored(TypeError): return strategy(**definition) raise Exception( 'No strategy is capable of building route {0}'.format(definition))
def _save(self, expires): with open(self.__file_path(), 'wb') as file: with ignored(Exception): pickle.dump( (self.data, expires), file, pickle.HIGHEST_PROTOCOL)
def clear(self): """Clears the flash messages from the container and session. This is called automatically after the flash messages have been iterated over. """ with ignored(KeyError): del self.session[self.session_key] self.messages = collections.OrderedDict()
def get_form_vars(environ, dict_type): """Convert environ vars into GET/POST/FILES objects. Process all get and post vars from a <form> and return MultiDict of each. """ if environ['REQUEST_METHOD'] == 'PUT' and not environ.get('CONTENT_TYPE'): environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded' field_storage = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=True) post_dict, files_dict = dict_type(), dict_type() with ignored(Exception): post_dict._mutable = True files_dict._mutable = True post, files = _process_field_storage(field_storage, post_dict, files_dict) with ignored(Exception): post.make_immutable() files.make_immutable() return post, files
def invalidate(self): """Invalidate the data that has been bound on the form. This is called automatically when data is bound to the form and sets the forms validity to invalid. """ attrs = ('_data', '_raw_data', '_errors') for attr in attrs: with ignored(AttributeError): delattr(self, attr) self._validated = self._valid = False
def invalidate(self): """Invalidate the data that has been bound on the form. This is called automatically when data is bound to the form and sets the forms validity to invalid. """ attrs = ('_data', '_raw_data', '_errors', '_form_errors') for attr in attrs: with ignored(AttributeError): delattr(self, attr) self._validated = self._valid = False
def find_commands_in_module(module): """Retrieves a list of all commands within a module. Returns: A list of commands from the module. """ commands = [] for key in dir(module): item = getattr(module, key) with ignored(Exception): if issubclass(item, Base) and item != Base: commands.append(item) return commands
def reloader(main_func, args, kwargs, script_dir=None): if os.environ.get('RUN_MAIN') == 'true': thread.start_new_thread(main_func, args, kwargs) with ignored(KeyboardInterrupt): reloader_thread() else: try: exit_code = restart_with_reloader(script_dir) if exit_code < 0: os.kill(os.getpid(), -exit_code) else: sys.exit(exit_code) except KeyboardInterrupt: print('\nTerminated.')
def _process_field_storage(fields, get=None, post=None, files=None): if not get: get = MultiDict() if not post: post = MultiDict() if not files: files = MultiDict() with ignored(Exception): for name in fields: field = fields[name] if isinstance(name, str) else name if isinstance(field, list): _process_field_storage(field, get, post, files) elif field.filename: files[field.name] = field elif field.disposition or field.name not in get: post[field.name] = field.value else: if field.name not in get: get[field.name] = field.value return get, post, files
def _process_field_storage(fs, post, files): with ignored(Exception): for name in fs: field = fs[name] if isinstance(name, str) else name if isinstance(field, list): _process_field_storage(field, post, files) elif field.filename: # An uploaded file, create a new File tuple to resolve the # not indexable issue. files[field.name] = File( field.file, field.filename, field.name, field.type, field.type_options, field.disposition, field.disposition_options, field.headers) else: post[field.name] = field.value return post, files
def execute(self): try: from __main__ import APP_MODULE test_runner = None cli_args = '' sys.argv = [sys.argv.pop(0)] try: import pytest test_runner = 'pytest' cli_args = '--cov {0}'.format(APP_MODULE) except: with ignored(ImportError): import nose test_runner = 'nose' cli_args = '--cover-package={0}'.format(APP_MODULE) if test_runner: sys.modules[test_runner].main(cli_args.split(' ')) else: raise ConsoleError("You must install either 'nose' or 'py.test' to run the unit tests.") except: _no_application_error()
def execute(self): try: app_module = os.environ['APP_MODULE'] test_runner = None cli_args = '' sys.argv = [sys.argv.pop(0)] try: import pytest test_runner = 'pytest' cli_args = '--cov {0}'.format(app_module) except: with ignored(ImportError): import nose test_runner = 'nose' cli_args = '--cover-package={0}'.format(app_module) if test_runner: sys.modules[test_runner].main(cli_args.split(' ')) else: raise ConsoleError( "You must install either 'nose' or 'py.test' to run the unit tests." ) except: _no_application_error()
def _destroy(self): with ignored(OSError): os.unlink(self.__file_path())
def _save(self, expires): with open(self.__file_path(), 'wb') as file: with ignored(Exception): pickle.dump((self.data, expires), file, pickle.HIGHEST_PROTOCOL)
def __setitem__(self, key, value, timeout=0): expires = datetime.now() + timedelta( seconds=int(timeout)) if timeout else None with open(self.__file_path(key), 'wb') as file: with ignored(Exception): pickle.dump((value, expires), file, pickle.HIGHEST_PROTOCOL)
def __call__(self, view_model): with contextmanagers.ignored(KeyError): del view_model.data['context'] return JSONEncoder().encode(view_model.data)
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages import watson from watson.common.contextmanagers import ignored with open('LICENSE') as f: license = f.read() reqs = '' with ignored(IOError, OSError): reqs = open(os.path.join(os.path.dirname(__file__), 'requirements.txt')).read().split("\n")[0:-1] setup( name='watson-framework', version=watson.__version__, description='An easy to use Python 3 framework for creating web applications.', long_description='''Watson, a Python 3 web framework "It's elementary my dear Watson" Watson is an easy to use framework designed to get out of your way and let you code your application rather than wrangle with the framework. The latest documentation can be found at http://simoncoulton.github.com/watson ''', author='Simon Coulton', author_email='*****@*****.**', url='http://simoncoulton.github.com/watson', license=license, packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), classifiers=[
def test_ignored_exception(): with ignored(Exception): raise Exception assert True
def __delitem__(self, key): with ignored(OSError): os.unlink(self.__file_path(key))
# -*- coding: utf-8 -*- import collections from datetime import datetime, timedelta import os import pickle from tempfile import gettempdir from watson.common.imports import get_qualified_name from watson.common.contextmanagers import ignored with ignored(ImportError): import memcache class BaseStorage(object): """Base class for all cache storage classes. Cache storage classes are designed to act similar to a dict, however get and set methods can be used when a timeout is required on a set, or when a default value is to be specified on a get. Attributes: dict config: The relevant configuration settings for the storage. """ config = None def __init__(self, config=None): self.config = config or {} def __setitem__(self, key, value, timeout=0): """See set() """ raise NotImplementedError('__setitem__ must be implemented')
def execute(self, **kwargs): actual_kwargs = kwargs.copy() with ignored(Exception): del actual_kwargs['action'] method = self.get_execute_method(**kwargs) return method(**actual_kwargs) or {}
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages import watson from watson.common.contextmanagers import ignored with open('LICENSE') as f: license = f.read() reqs = '' with ignored(IOError, OSError): reqs = open(os.path.join(os.path.dirname(__file__), 'requirements.txt')).read() setup(name='watson-framework', version=watson.__version__, description= 'An easy to use Python 3 framework for creating web applications.', long_description='''Watson, a Python 3 web framework "It's elementary my dear Watson" Watson is an easy to use framework designed to get out of your way and let you code your application rather than wrangle with the framework. The latest documentation can be found at http://simoncoulton.github.com/watson ''', author='Simon Coulton', author_email='*****@*****.**', url='http://simoncoulton.github.com/watson', license=license, packages=find_packages( exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
# -*- coding: utf-8 -*- import collections from datetime import datetime, timedelta import os import pickle from tempfile import gettempdir from watson.common.imports import get_qualified_name from watson.common.contextmanagers import ignored with ignored(ImportError): import memcache class BaseStorage(object): """Base class for all cache storage classes. Cache storage classes are designed to act similar to a dict, however get and set methods can be used when a timeout is required on a set, or when a default value is to be specified on a get. Attributes: config (dict): The relevant configuration settings for the storage. """ config = None def __init__(self, config=None): self.config = config or {} def __setitem__(self, key, value, timeout=0): """See set() """