def _return_response_json_content(self, value, **args): struct = _odict((('type', _webtypes.ClassDefInfo (_metadata.ClassDefInfo .fromclass(_responses.WebReturnResponse)) .prim()), ('retval', value.prim()), )) # XXX: use out-of-band current auth info # FIXME: use in-band auth info via auth info facet auth_info = self.current_auth_info if auth_info: realm = auth_info.realm try: user = auth_info.user except AttributeError: user = None accepted = auth_info.accepted else: realm = None user = None accepted = False struct['auth_info'] = _odict((('realm', realm), ('user', user), ('accepted', accepted))) return _webtypes.json_dumps(struct)
def _exc_response_json_content(self, data): struct = \ _odict((('type', _webtypes.ClassDefInfo (_metadata.ClassDefInfo.fromclass(data.response_type)) .prim()), )) exc_facet = data['exc'] if _debug.DEBUG_EXC_NAME in exc_facet.debug_flags: struct['name'] = exc_facet.name struct['displayname'] = exc_facet.displayname if _debug.DEBUG_EXC_MESSAGE in exc_facet.debug_flags: struct['message'] = exc_facet.message if _debug.DEBUG_EXC_INSTANCE_INFO in exc_facet.debug_flags: struct['class_def_module'] = exc_facet.class_def_module struct['args'] = exc_facet.args if exc_facet.traceback is not None \ and _debug.DEBUG_EXC_TRACEBACK in exc_facet.debug_flags: struct['traceback'] = exc_facet.traceback try: auth_info_facet = data['auth_info'] except KeyError: pass else: struct['auth_info'] = \ _odict((('realm', auth_info_facet.realm), ('user', auth_info_facet.user), ('accepted', auth_info_facet.accepted))) return _webtypes.json_dumps(struct)
def cors_preflight(cls, method, uri, args=None, origin=None, accept_mediaranges=('application/json', '*/*; q=0.01'), auth=None, headers=None, *args_, **kwargs): if origin is None: raise TypeError('missing origin') headers = _odict(headers or ()) preflight_headers = {'Access-Control-Request-Method': method} if headers: preflight_headers['Access-Control-Request-Headers'] = \ ', '.join((name.lower() for name in headers.keys())) try: preflight_headers['Accept'] = headers['Accept'] except KeyError: pass return cls('options', uri, *args_, origin=origin, accept_mediaranges=accept_mediaranges, headers=preflight_headers, **kwargs)
:type: :class:`traceback` """ return self._orig_tb def _debug_flag_argname(flag): return _re.sub('^debug_', '', _bedframe.DebugFlagSet.flag_name(flag).lower()) _DEBUG_FLAGS_BY_ARGVALUE = \ _odict([('secure', _bedframe.DEBUG_SECURE), ('default', _bedframe.DEBUG_DEFAULT), ('full', _bedframe.DEBUG_FULL), ('exc_secure', _bedframe.DEBUG_EXC_SECURE), ('exc_default', _bedframe.DEBUG_EXC_DEFAULT), ('exc_full', _bedframe.DEBUG_EXC_FULL), ]) _DEBUG_FLAGS_BY_ARGVALUE.update([(_debug_flag_argname(flag), flag) for flag in _bedframe.DebugFlagSet.valid_flags()]) _logger = _logging.getLogger() _LOGGING_FORMAT = '%(levelname)s: %(message)s' _LOGLEVELS_BY_ARGVALUE = _odict([('critical', _logging.CRITICAL), ('error', _logging.ERROR), ('warning', _logging.WARNING),
def __init__(self, method, uri, args=None, argtypes=None, args_as=None, accept_mediaranges=('application/json', '*/*; q=0.01'), auth=None, authtype='basic', origin=None, headers=None, **kwargs): method_kwargs = {} headers = _odict(headers or ()) method_kwargs['headers'] = headers if origin is not None: headers['Origin'] = origin headers.setdefault('Accept', ', '.join(accept_mediaranges)) if args: if argtypes: untyped_args = [arg for arg in args if arg not in argtypes] else: untyped_args = args.keys() if untyped_args: raise ValueError('missing type specifications for request' ' arguments {}'.format(untyped_args)) if args_as is None: if _http.method_defines_body_semantics(method.upper()): args_as = 'body' else: args_as = 'query' if args_as == 'query': args_json = {name: argtypes[name](value).json() for name, value in args.items()} method_kwargs['params'] = args_json elif args_as == 'body': args_webobjects = {name: argtypes[name](value) for name, value in args.items()} body = _webtypes.json_dumps(args_webobjects) method_kwargs['data'] = body headers['Content-Type'] = 'application/json' elif args_as == 'body_urlencoded': args_json = {name: argtypes[name](value).json() for name, value in args.items()} body = _urlencode(args_json) method_kwargs['data'] = body headers['Content-Type'] = 'application/x-www-form-urlencoded' else: raise ValueError('invalid argument mechanism {!r}; expected' ' one of {}' .format(args_as, ('query', 'body', 'body_urlencoded'))) if auth is not None: try: auth_class = _requests_auth_classmap[authtype] except KeyError: raise ValueError('invalid authentication type {!r}; expected' ' one of {}' .format(authtype, ('basic', 'digest'))) method_kwargs['auth'] = auth_class(*auth) method_kwargs.update(kwargs) super(WebRequest, self).__init__(method, uri, **method_kwargs)
def _request_pathpart_args_jsons(self): return _odict(self._request_pathpart_args_jsons_items_iter)
def request_pathpart_args_prims(self): return _odict(self.request_pathpart_args_prims_items_iter)
def sync(self): """ Write any unsaved changes to persistent storage and reload any settings that have been changed externally This function is called by :meth:`open` and :meth:`close`. .. warning:: **Bug:** Writing settings in the conf format is not yet implemented, so calling this after calling one of the mutator methods will raise a :exc:`~exceptions.NotImplementedError`. .. note:: **TODO:** conflict detection, resolution, exceptions :raise EnvironmentError: Raised if an error is encountered outside the Python system while reading or writing settings to persistent storage. :raise spruce.settings.MalformedSettingsLocation: Raised if a malformed settings location is encountered. """ format_ = self._formats[self.format] read = format_.read_func write = format_.write_func # determine all applicable locations locations = [] locations.append(self._paths[self.format][self.base_scope][self.component_scope]) for greater_component in self._greater_components(self.component_scope): if self.component_scope_fallback(self.component_scope, greater_component): locations.append(self._paths[self.format][self.base_scope][greater_component]) if self.base_scope == "user" and self.base_scope_fallback: locations.append(self._paths[self.format]["system"][self.component_scope]) for greater_component in self._greater_components(self.component_scope): if self.component_scope_fallback(self.component_scope, greater_component): locations.append(self._paths[self.format]["system"][greater_component]) for index, location in enumerate(locations): location = location.replace("{organization}", self.organization) if self.application is not None: location = location.replace("{application}", self.application) if self.subsystem is not None: location = location.replace("{subsystem}", self.subsystem) location = location.replace("{extension}", format_.extension) locations[index] = location self._locations = locations # actuate :meth:`clear` if "" in self._keystowrite: assert "" in self._cache_ assert self._cache_[""] is None write(self.locations[0], {"": None}) self._keystowrite.remove("") del self._cache_[""] # actuate :meth:`set_value` and :meth:`remove` try: write( self.locations[0], _odict((key, value) for key, value in self._cache_.iteritems() if key in self._keystowrite), ) except _exc.MalformedSettingsLocation as exc: raise _exc.MalformedSettingsLocation(self.locations[0], message=exc.message_) # update :attr:`_cache_` and :attr:`_keys_in_primarylocation` if not self._deleting: self._cache_.clear() self._cache_.update({key: str(value) for key, value in self.defaults.items()}) for index, location in enumerate(reversed(self.locations)): try: location_settings = read(location, [""]) except _exc.MalformedSettingsLocation as exc: raise _exc.MalformedSettingsLocation(location, message=exc.message_) self._cache_.update(location_settings) if index == len(self.locations) - 1: self._keys_in_primarylocation = set(location_settings.keys()) self._cache_creationtime = _datetime.now()