Exemplo n.º 1
0
 def _stored(self, key, default=None):
     value, expires = default, None
     with suppress(OSError):
         with open(self.__file_path(key), 'rb') as file:
             with suppress(Exception):
                 (value, expires) = pickle.load(file)
     return value, expires
Exemplo n.º 2
0
 def create(self, path, is_dir=True, parents=True):
     path = pathlib.Path(path)
     if is_dir:
         with suppress(Exception):
             path.mkdir(parents=parents)
     else:
         parent_dir = path.parent
         with suppress(Exception):
             parent_dir.mkdir(parents=parents)
         path.touch()
     return str(path)
Exemplo n.º 3
0
 def instantiate(self, definition):
     item = definition['item']
     if hasattr(item, '__ioc_definition__'):
         definition.update(item.__ioc_definition__)
     args, kwargs = [], {}
     is_lambda = definition.get('call_type', None) == FUNCTION_TYPE
     sig = signature(item)
     if 'container' in sig.parameters:
         kwargs['container'] = self.container
     if 'init' in definition:
         init = definition['init']
         updated_args, updated_kwargs = self.get_args_kwargs(init)
         args.extend(updated_args)
         kwargs.update(updated_kwargs)
         if isfunction(init):
             sig = signature(init)
             if 'container' in sig.parameters:
                 kwargs['container'] = self.container
             init = init(*args, **kwargs)
             definition['init'] = init
         if not is_lambda:
             args, kwargs = self.get_args_kwargs(init)
     item = item(*args, **kwargs)
     if is_lambda and isinstance(item, str):
         # Special case for items that might be retrieved via lambda expressions
         with suppress(Exception):
             definition['item'] = self.container.load_item_from_string(item)
             item, args, kwargs = self.instantiate(definition)
     return item, args, kwargs
Exemplo n.º 4
0
 def test(self):
     """Runs the unit tests for the project.
     """
     current_directory = os.getcwd()
     os.chdir(os.path.join(current_directory, '..'))
     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 suppress(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()
     os.chdir(current_directory)
Exemplo n.º 5
0
    def register_components(self):
        """Register any components specified with the application.

        Components can include the following modules:
            - dependencies
            - events
            - models
            - routes
            - views

        Registering a component will merge any configuration settings within
        the above modules prior to the application booting.

        An example component might look like:

        /component
            /views
                /index.html
            /routes.py
            /views.py
        """
        types = ('dependencies', 'events', 'routes', 'models', 'views')
        for component in self.config['components']:
            for type_ in types:
                with contextmanagers.suppress(Exception):
                    type_component = imports.load_definition_from_string(
                        '{}.{}.{}'.format(component, type_, type_))
                    if type_ == 'dependencies':
                        self.container.update(type_component)
                    if not isinstance(type_component, ModuleType):
                        self._config[type_] = dict_deep_update(
                            self._config.get(type_, {}), type_component)
            self._config['views'][
                'renderers']['jinja2']['config']['packages'].append(
                (component, 'views'))
Exemplo n.º 6
0
 def _load(self):
     try:
         with open(self.__file_path(), 'rb') as file:
             with suppress(Exception):
                 return pickle.load(file)
     except:
         return ()
Exemplo n.º 7
0
 def __delitem__(self, key):
     if not self.data:
         self.load()
     with suppress(KeyError):
         del self.data[key]
         if self.autosave:
             self.save()
Exemplo n.º 8
0
 def _save(self, expires):
     with open(self.__file_path(), 'wb') as file:
         with suppress(Exception):
             pickle.dump(
                 (self.data,
                  expires),
                 file,
                 pickle.HIGHEST_PROTOCOL)
Exemplo n.º 9
0
 def build_route(self, **definition):
     """Converts a route definition into a specific route.
     """
     for strategy in self._build_strategies:
         with suppress(TypeError):
             return strategy(**definition)
     raise Exception(
         'No strategy is capable of building route {0}'.format(definition))
Exemplo n.º 10
0
    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 suppress(KeyError):
            del self.session[self.session_key]
        self.messages = collections.OrderedDict()
        self.__write_to_session()
Exemplo n.º 11
0
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 suppress(Exception):
        post_dict._mutable = True
        files_dict._mutable = True
    post, files = _process_field_storage(field_storage, post_dict, files_dict)
    with suppress(Exception):
        post.make_immutable()
        files.make_immutable()
    return post, files
Exemplo n.º 12
0
    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 suppress(KeyError):
            del self.session[self.session_key]
        self.messages = collections.OrderedDict()
        self.__write_to_session()
Exemplo n.º 13
0
    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 suppress(AttributeError):
                delattr(self, attr)
        self._validated = self._valid = False
Exemplo n.º 14
0
 def add_func_to_arg_list(self, func, name, prefixed_name):
     index = None
     try:
         index = [arg[0] for arg in func.__args__].index(prefixed_name)
     except:
         with suppress(Exception):
             idx = [arg[0] for arg in func.__args__].index(name)
             del func.__args__[idx]
         func.__args__.append((prefixed_name, self.kwargs))
     if index:
         func.__args__[index] = (self.arg_name, self.kwargs)
Exemplo n.º 15
0
    def execute(self, args):
        """Execute the runner and any commands the user has specified.
        """
        if not args:
            args = sys.argv[:]
        self._name = os.path.basename(args.pop(0))
        execute = True
        help = '-h'
        method = help
        namespace = None
        # Always show help if invalid command
        try:
            namespace, method, *_ = args
        except:
            with suppress(Exception):
                namespace = args[0]
            execute = False
            args.append(method)
        if namespace:
            args = args[1:]
        if namespace == help:
            namespace = None

        # Add the relevant commands
        parser = argparse.ArgumentParser()
        try:
            self.attach_commands(parser, namespace)
        except ConsoleError as exc:
            self._handle_exc(exc)

        # Parse the input
        parsed_args = parser.parse_args(args)
        if execute:
            instance, method, args = parsed_args.command
            try:
                kwargs = {arg_name: getattr(parsed_args, arg_name)
                          for attr, arg_name in args.items()}
                return getattr(instance, method)(**kwargs)
            except ConsoleError as exc:
                self._handle_exc(exc)
Exemplo n.º 16
0
def _process_field_storage(fs, post, files):
    with suppress(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,
                    field)
            else:
                post[field.name] = field.value
    return post, files
Exemplo n.º 17
0
 def _destroy(self):
     with suppress(OSError):
         os.unlink(self.__file_path())
Exemplo n.º 18
0
 def execute(self, **kwargs):
     actual_kwargs = kwargs.copy()
     with suppress(Exception):
         del actual_kwargs['action']
     method = self.get_execute_method(**kwargs)
     return method(**actual_kwargs) or {}
Exemplo n.º 19
0
# -*- coding: utf-8 -*-
import collections
from watson.http.sessions import StorageMixin
from watson.common import imports
from watson.common.contextmanagers import suppress
from watson.http.sessions.serializers import Json
with suppress(ImportError):
    import redis


class Storage(StorageMixin):

    """A redis based storage adapter for session data.
    """
    client = None
    serializer = None
    serializer_class = Json
    encoding = 'utf-8'

    def __init__(self, id=None, timeout=None, autosave=True, config=None):
        super(Storage, self).__init__(id, timeout, autosave)
        settings = {'host': 'localhost', 'port': 6379, 'db': 0}
        if config:
            self._process_config(config)
        self.config = collections.ChainMap(config or {}, settings)
        self.serializer = self.serializer_class()

    def _process_config(self, config):
        if 'serializer_class' in config:
            self.serializer_class = imports.load_definition_from_string(
                config['serializer_class'])
Exemplo n.º 20
0
 def __delitem__(self, key):
     with suppress(OSError):
         os.unlink(self.__file_path(key))
Exemplo n.º 21
0
 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 suppress(Exception):
             pickle.dump((value, expires), file, pickle.HIGHEST_PROTOCOL)
Exemplo n.º 22
0
 def execute(self, **kwargs):
     actual_kwargs = kwargs.copy()
     with suppress(Exception):
         del actual_kwargs['action']
     method = self.get_execute_method(**kwargs)
     return method(**actual_kwargs) or {}
Exemplo n.º 23
0
def test_ignored_exception():
    with suppress(Exception):
        raise Exception
    assert True