def __process_exception(self, exc_info): try: code = exc_info[1].status_code except: code = 500 exc = exc_info[1] message = str(exc) cause_message = None try: exc = exc.__cause__ tb = exc.__traceback__ cause_message = str(exc) type = get_qualified_name(exc) except: tb = exc_info[2] type = get_qualified_name(exc_info[0]) frames = [] while tb is not None: frame = tb.tb_frame line = tb.tb_lineno co = frame.f_code file = co.co_filename function = co.co_name linecache.checkcache(file) sourcecode = linecache.getline(file, line, frame.f_globals) this_frame = { 'line': line, 'file': file, 'function': function, 'code': sourcecode.strip(), 'vars': {} } frame_vars = frame.f_locals.items() for var_name, value in frame_vars: val = None try: val = str(value) except: # pragma: no cover try: val = repr(value) # pragma: no cover except: val = None this_frame['vars'][var_name] = val frames.append(this_frame) tb = tb.tb_next frames.reverse() del tb return code, message, cause_message, frames, type
def generate_fixtures(self, models, output_to_stdout): """Generate fixture data in json format. Args: models (string): A comma separated list of models to output output_to_stdout (boolean): Whether or not to output to the stdout """ if models: models = models.split(',') for name, options in self.config['connections'].items(): metadata = self._load_metadata(options['metadata']) for model in metadata._decl_class_registry.values(): model_name = imports.get_qualified_name(model) if models and model_name not in models: continue records = self._get_models_in_session(name, model) if not records: continue records = json.dumps(records, indent=4) if output_to_stdout: self.write(records) else: model_name, path = fixtures.save( model, records, self.config['fixtures']) self.write( 'Created fixture for {} at {}'.format(model_name, path))
def __repr__(self): return ( '<{0} routers:{1} routes:{2}>'.format( get_qualified_name(self), len(self.routers), len(self)) )
def __repr__(self): return '<{0} name:{1} method:{2} action:{3} fields:{4}>'.format( get_qualified_name(self), self.name, self.method, self.action, len(self))
def __repr__(self): return ( '<{0} template:{1} format:{2}>'.format( imports.get_qualified_name(self), self.template, self.format) )
def __repr__(self): return ( '<{0} name:{1} path:{2}>'.format( get_qualified_name(self), self.name, self.path) )
def __repr__(self): return ( '<{0} name:{1} path:{2} match:{3}>'.format( get_qualified_name(self), self.name, self.path, self.regex.pattern) )
def get_command(self, command_name): # overrides the runners get_command method if command_name not in self.runner.commands: return None command = self.runner.commands[command_name] if not isinstance(command, str): self.container.add(command_name, get_qualified_name(command)) return self.container.get(command_name)
def save(model, items, fixtures_config): model_name = strings.pluralize( strings.snakecase(model.__name__)) path = '{}/{}.json'.format( fixtures_config['path'], model_name) with open(path, 'w') as file: file.write(items) return imports.get_qualified_name(model), path
def wrapper(self, *args, **kwargs): if not hasattr(self, 'container'): cache_instance = DEFAULT_CACHE_TYPE() else: cache_config = self.container.get('application.config')['cache'] cache_instance = self.container.get(cache_config['type']) key_name = key if key else get_qualified_name(func) if key_name not in cache_instance: cache_instance.set(key_name, func(self, *args, **kwargs), timeout) return cache_instance[key_name]
def wrapper(self, *args, **kwargs): if not hasattr(self, 'container'): cache_instance = DEFAULT_CACHE_TYPE() else: cache_config = self.container.get( 'application.config')['cache'] cache_instance = self.container.get(cache_config['type']) key_name = key if key else get_qualified_name(func) if key_name not in cache_instance: cache_instance.set(key_name, func(self, *args, **kwargs), timeout) return cache_instance[key_name]
def add(self, name, obj, type_='singleton'): """Add an instantiated dependency to the container. Args: name (string): The name used to reference the dependency obj (mixed): The dependency to add type_ (string): prototype|singleton depending on if it should be instantiated on each IocContainer.get call. """ self._add_to_instantiated(name, obj) self.add_definition(name, {'type': type_, 'item': imports.get_qualified_name(obj)})
def __setitem__(self, field, value, replace=False, **options): if self.mutable: field = convert_to_http_field(field) value = [str(value)] if options: value.extend(['{0}={1}'.format(key, val) for key, val in options.items()]) value = '; '.join(value) if isinstance(self.environ, MultiDict): self.environ.set(field, value, replace) else: self.environ[field] = value else: raise TypeError('{0} is not mutable.'.format(get_qualified_name(self)))
def __process_exception(self, exc_info): try: code = exc_info[1].status_code except: code = 500 exc = exc_info[1] message = str(exc) cause_message = None try: exc = exc.__cause__ tb = exc.__traceback__ cause_message = str(exc) type = get_qualified_name(exc) except: tb = exc_info[2] type = get_qualified_name(exc_info[0]) frames = [] while tb is not None: frame = tb.tb_frame line = tb.tb_lineno co = frame.f_code file = co.co_filename function = co.co_name linecache.checkcache(file) sourcecode = linecache.getline(file, line, frame.f_globals) frames.append({ 'line': line, 'file': file, 'function': function, 'code': sourcecode.strip(), 'vars': frame.f_locals.items() }) tb = tb.tb_next frames.reverse() del tb return code, message, cause_message, frames, type
def __repr__(self): class_ = get_qualified_name(self) if self.path: return ( '<{0} name:{1} path:{2} match:{3}>'.format( class_, self.name, self.path, self.regex.pattern) ) return ( '<{0} name:{1} match:{2}>'.format( class_, self.name, self.regex.pattern) )
def add(self, callback, priority=1, only_once=False): """Adds a new callback to the collection. Args: callback (callable): the function to be triggered priority (int): how important the callback is in relation to others only_once (bool): the callback should only be fired once and then removed Raises: TypeError if non-callable is added. """ if not hasattr(callback, '__call__'): name = get_qualified_name(callback) raise TypeError('Callback {0} must be callable.'.format(name)) self.append(ListenerDefinition(callback, priority, only_once)) self.require_sort = True return self
def add(self, callback, priority=1, only_once=False): """Adds a new callback to the collection. Args: callable callback: the function to be triggered int priority: how important the callback is in relation to others bool only_once: the callback should only be fired once and then removed Raises: TypeError if non-callable is added. """ if not hasattr(callback, '__call__'): name = get_qualified_name(callback) raise TypeError('Callback {0} must be callable.'.format(name)) self.append( ListenerDefinition(callback, int(priority), bool(only_once))) self.require_sort = True return self
def get_returned_controller_data(self, controller, event): context = event.params['context'] route_match = context['route_match'] try: execute_params = route_match.params model_data = controller.execute(**execute_params) if model_data is None: raise InternalServerError( 'The controller {0} did not return any data.'.format( controller)) if isinstance(model_data, controllers.ACCEPTABLE_RETURN_TYPES): model_data = {'content': model_data} elif isinstance(model_data, Response): # Short circuited, skip any templating controller.response = context['response'] = model_data return model_data, model_data path = controller.get_execute_method_path(**route_match.params) controller_template = os.path.join(*path) view_template = self.templates.get(controller_template, controller_template) format = route_match.params.get('format', 'html') if isinstance(model_data, Model): if not model_data.template: model_data.template = view_template else: overridden_template = path[:-1] + [model_data.template] model_data.template = os.path.join(*overridden_template) if not model_data.format: model_data.format = format view_model = model_data else: view_model = Model(format=format, template=view_template, data=model_data) context['response'] = controller.response return controller.response, view_model except (ApplicationError, NotFoundError, InternalServerError) as exc: raise except Exception as exc: raise InternalServerError( 'An error occurred executing controller: {0}'.format( get_qualified_name(controller))) from exc
def get_returned_controller_data(self, controller, event): context = event.params['context'] route_match = context['route_match'] try: execute_params = route_match.params model_data = controller.execute(**execute_params) if isinstance(model_data, controllers.ACCEPTABLE_RETURN_TYPES): model_data = {'content': model_data} elif isinstance(model_data, Response): # Short circuited, skip any templating controller.response = context['response'] = model_data return model_data, model_data path = controller.get_execute_method_path( **route_match.params) controller_template = os.path.join(*path) view_template = self.templates.get(controller_template, controller_template) format = route_match.params.get('format', 'html') if isinstance(model_data, Model): if not model_data.template: model_data.template = view_template else: overridden_template = path[:-1] + [model_data.template] model_data.template = os.path.join( *overridden_template) if not model_data.format: model_data.format = format view_model = model_data else: view_model = Model( format=format, template=view_template, data=model_data) context['response'] = controller.response return controller.response, view_model except (ApplicationError, NotFoundError, InternalServerError) as exc: raise # pragma: no cover except Exception as exc: raise InternalServerError( 'An error occurred executing controller: {0}'.format( get_qualified_name(controller))) from exc
def _get_models_in_session(self, name, model): results = [] if isinstance(model, _ModuleMarker): return None inst = inspect(model) attr_names = [c_attr.key for c_attr in inst.mapper.column_attrs] for obj in self.sessions[name].query(model): fields = {} new_obj = collections.OrderedDict() new_obj['class'] = imports.get_qualified_name(model) attr_names = [c_attr.key for c_attr in inst.mapper.column_attrs] for column in attr_names: value = getattr(obj, column) if isinstance(value, enum.Enum): value = value.value elif isinstance(value, datetime): value = str(value) elif isinstance(value, bytes): value = value.decode('utf-8') fields[column] = value new_obj['fields'] = collections.OrderedDict( sorted(fields.items(), key=lambda k: k[0])) results.append(new_obj) return results
def test_qualified_name(self): self_name = imports.get_qualified_name(self) func_name = imports.get_qualified_name(some_func) assert 'tests.watson.common.test_imports.TestImports' == self_name assert 'tests.watson.common.support.some_func' == func_name
def __call__(self, event): raise NotImplementedError( 'The processor <{}> must implement __call__'.format( get_qualified_name(self))) # pragma: no cover
def __repr__(self): return ( '<{0}: {1} param(s), {2} definition(s)>').format( imports.get_qualified_name(self), len(self.params), len(self.definitions) )
def get_qualified_name(obj): """Retrieve the qualified class name of an object. """ return imports.get_qualified_name(obj)
def __repr__(self): return '<{0} db:{1}>'.format(get_qualified_name(self), self.config['db'])
def __repr__(self): return ( '<{0} dir:{1}>'.format( get_qualified_name(self), self.config['dir']) )
def __repr__(self): return ('<{0} dir:{1}>'.format(get_qualified_name(self), self.config['dir']))
def __repr__(self): return '<{0} messages:{1}>'.format(get_qualified_name(self), len(self))
def __call__(self, event): raise NotImplementedError( 'The processor <{}> must implement __call__'.format(get_qualified_name(self))) # pragma: no cover
def __repr__(self): return ('<{0}: {1} param(s), ' '{2} definition(s)>').format( get_qualified_name(self), len(self.config['params']), len(self.config['definitions']))
def __repr__(self): return '<{0} routes:{1}>'.format(get_qualified_name(self), len(self.routes))
def __repr__(self): return '<{0} method:{1} url:{2}>'.format(get_qualified_name(self), self.method, self.url)
def __repr__(self): return '<{0} namespaces:{1}>'.format(get_qualified_name(self), len(self))
def __repr__(self): return ( '<{0} events:{1}>'.format( get_qualified_name(self), len(self.events)) )
def __repr__(self): return '<{0} callbacks:{1}>'.format(get_qualified_name(self), len(self))
def __call__(self, event): route_match = event.params['route_match'] try: controller_class = route_match.route.options['controller'] container = event.params['container'] if controller_class not in container.config['definitions']: container.add(controller_class, controller_class, 'prototype') else: controller_definition = container.config[ 'definitions'][controller_class] controller_definition['type'] = 'prototype' if 'item' not in controller_definition: controller_definition['item'] = controller_class controller = event.params['container'].get(controller_class) except Exception as exc: raise InternalServerError( 'Controller not found for route: {0}'.format( route_match.route.name)) from exc event.params['controller_class'] = controller controller.event = event controller.request = event.params['request'] try: execute_params = route_match.params model_data = controller.execute(**execute_params) if model_data is None: raise InternalServerError( 'The controller {0} did not return any data.'.format(controller)) short_circuit = False if isinstance(model_data, str): model_data = {'content': model_data} elif isinstance(model_data, Response): short_circuit = True response = model_data if not short_circuit: context = {'context': {'controller': controller}} path = controller.get_execute_method_path( **route_match.params) controller_template = os.path.join(*path) view_template = self.templates.get(controller_template, controller_template) format = route_match.params.get('format', 'html') if isinstance(model_data, Model): model_data.data.update(context) if not model_data.template: model_data.template = view_template else: overridden_template = path[:-1] + [model_data.template] model_data.template = os.path.join( *overridden_template) if not model_data.format: model_data.format = format response = model_data else: model_data.update(context) response = Model( format=format, template=view_template, data=model_data) except Exception as exc: raise InternalServerError( 'An error occurred executing controller: {0}'.format(get_qualified_name(controller))) from exc controller.request.session_to_cookie() if controller.request.cookies.modified: controller.response.cookies.merge(controller.request.cookies) return response
def __repr__(self): return '<{0} servers:{1}>'.format(get_qualified_name(self), len(self.config['servers']))
def test_qualified_name(self): assert 'tests.watson.common.test_imports.TestImports' == get_qualified_name( self) assert 'tests.watson.common.support.some_func' == get_qualified_name( some_func)
def __repr__(self): return '<{0}>'.format(get_qualified_name(self))
def __repr__(self): return '<{0} type:{1} include null:{2} expand:{3} attributes:{4}>'.format( imports.get_qualified_name(self), imports.get_qualified_name(self.type), self.include_null, self.expand, ','.join(self.attributes))
def __repr__(self): return '<{0} results:{1}>'.format(get_qualified_name(self), len(self))
def __repr__(self): return '<{0} name:{1}>'.format(get_qualified_name(self), self.name)
def __repr__(self): return '<{0} current:{1} locales:{2}>'.format( imports.get_qualified_name(self), self.current_locale, len(self._locales))
def __repr__(self): return ('<{0}: {1} param(s), ' '{2} definition(s)>').format(get_qualified_name(self), len(self.config['params']), len(self.config['definitions']))
def __delitem__(self, field): if self.mutable: field = convert_to_http_field(field) del self.environ[field] else: raise TypeError('{0} is not mutable.'.format(get_qualified_name(self)))
def __call__(self, event): route_match = event.params['route_match'] try: controller_class = route_match.params['controller'] event.params['container'].add(controller_class, controller_class, 'prototype') controller = event.params['container'].get(controller_class) except Exception as exc: raise InternalServerError('Controller not found for route: {0}'.format(route_match.route.name)) from exc event.params['controller_class'] = controller controller.event = event controller.request = event.params['request'] try: model_data = controller.execute(**route_match.params) short_circuit = False if isinstance(model_data, str): model_data = {'content': model_data} elif isinstance(model_data, Response): short_circuit = True response = model_data if not short_circuit: controller_path = controller.get_execute_method_path(**route_match.params) controller_template = os.path.join(*controller_path) response = Model(format=route_match.params.get('format', 'html'), template=self.templates.get(controller_template, controller_template), data=model_data) except Exception as exc: raise InternalServerError('An error occurred executing controller: {0}'.format(get_qualified_name(controller))) from exc controller.request.session_to_cookie() if controller.request.cookies.modified: controller.response.cookies.merge(controller.request.cookies) return response