def validation_errors_response(*args, **kwargs): """Returns a :class:`.Response` object with validation errors. The response will be created with a *412 Precondition Failed* status code and errors are reported in JSON format as response body. Typical usage is as ``error_handler`` for JSON based api:: @expose('json') @validate({'display_name': validators.NotEmpty(), 'group_name': validators.NotEmpty()}, error_handler=validation_errors_response) def post(self, **params): group = Group(**params) return dict(group=group) """ req = request._current_obj() errors = dict( (unicode_text(key), unicode_text(error)) for key, error in req.validation.errors.items() ) values = req.validation.values try: return Response(status=412, json_body={'errors': errors, 'values': values}) except TypeError: # values cannot be encoded to JSON, this might happen after # validation passed and validators converted them to complex objects. # In this case use request params, instead of controller params. return Response(status=412, json_body={'errors': errors, 'values': req.args_params})
def ksweb_error_handler(*args, **kw): # pragma: nocover from tg import flash, redirect from tg._compat import unicode_text from tg.request_local import request from tg.i18n import lazy_ugettext as l_ _request = request._current_obj() errors = dict((unicode_text(key), unicode_text(error)) for key, error in _request.validation.errors.items()) flash(l_('Errors: %s' % errors), 'error') redirect('/start')
def _check_security(self): requirement = getattr(self, 'allow_only', None) if requirement is None: return True if hasattr(requirement, 'predicate'): # It is a full requirement, let it build the response requirement._check_authorization() return True # It is directly a predicate, build the response ourselves predicate = requirement try: predicate.check_authorization(tg.request.environ) except NotAuthorizedError as e: reason = unicode_text(e) if hasattr(self, '_failed_authorization'): # Should shortcircuit the rest, but if not we will still # deny authorization self._failed_authorization(reason) if not_anonymous().is_met(tg.request.environ): # The user is authenticated but not allowed. code = 403 status = 'error' else: # The user has not been not authenticated. code = 401 status = 'warning' tg.response.status = code flash(reason, status=status) abort(code, comment=reason)
def content(self): vars = odict() request = tg.request._current_obj() response = tg.response._current_obj() attr_dict = request.environ.get("webob.adhoc_attrs", {}).copy() attr_dict["response"] = repr(response.__dict__) for entry in list(attr_dict.keys()): if entry.startswith("tgdb_"): del attr_dict[entry] vars["GET"] = [(k, request.GET.getall(k)) for k in request.GET] vars["POST"] = [(k, [saferepr(p) for p in request.POST.getall(k)]) for k in request.POST] vars["Cookies"] = [(k, request.cookies.get(k)) for k in request.cookies] vars["Headers"] = [ (k, saferepr(v)) for k, v in request.environ.items() if k.startswith("HTTP_") or k in request_header_filter ] vars["Request Attributes"] = [(k, saferepr(v)) for k, v in attr_dict.items() if not callable(v)] vars["Environ"] = [(k, saferepr(v)) for k, v in request.environ.items()] return unicode_text( render( dict(vars=vars), tg.config["debugbar.engine"], "tgext.debugbar.sections.templates.request!html" ).split("\n", 1)[-1] )
def _smart_str(s): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. This function was borrowed from Django. """ if not isinstance(s, string_type): try: return bytes_(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return ' '.join([ _smart_str(arg).decode('utf-8') for arg in s.args ]).encode('utf-8', 'strict') return unicode_text(s).encode('utf-8', 'strict') elif isinstance(s, unicode_text): return s.encode('utf-8', 'strict') else: return s
def unmet(self, msg=None, **placeholders): """ Raise an exception because this predicate is not met. :param msg: The error message to be used; overrides the predicate's default one. :type msg: str :raises NotAuthorizedError: If the predicate is not met. ``placeholders`` represent the placeholders for the predicate message. The predicate's attributes will also be taken into account while creating the message with its placeholders. """ if msg: message = msg else: message = self.message # This enforces lazy strings resolution (lazy translation for example) message = unicode_text(message) # Include the predicate attributes in the placeholders: all_placeholders = self.__dict__.copy() all_placeholders.update(placeholders) raise NotAuthorizedError(message % all_placeholders)
def content(self): vars = odict() request = tg.request._current_obj() response = tg.response._current_obj() attr_dict = request.environ.get('webob.adhoc_attrs', {}).copy() attr_dict['response'] = repr(response.__dict__) for entry in list(attr_dict.keys()): if entry.startswith('tgdb_'): del attr_dict[entry] vars['GET'] = [(k, request.GET.getall(k)) for k in request.GET] vars['POST'] = [(k, [saferepr(p) for p in request.POST.getall(k)]) for k in request.POST] vars['Cookies'] = [(k, request.cookies.get(k)) for k in request.cookies] vars['Headers'] = [ (k, saferepr(v)) for k, v in request.environ.items() if k.startswith('HTTP_') or k in request_header_filter ] vars['Request Attributes'] = [(k, saferepr(v)) for k, v in attr_dict.items() if not callable(v)] vars['Environ'] = [(k, saferepr(v)) for k, v in request.environ.items()] return unicode_text( render(dict(vars=vars), tg.config['debugbar.engine'], 'tgext.debugbar.sections.templates.request!html').split( '\n', 1)[-1])
def content(self): records = [] for record in self.get_and_clear(): msg = record.getMessage() if isinstance(msg, bytes): msg = msg.decode('utf-8', 'ignore') records.append({ 'message': msg, 'time': datetime.datetime.fromtimestamp(record.created), 'level': record.levelname, 'file': format_fname(record.pathname), 'file_long': record.pathname, 'line': record.lineno, }) records = reversed(records) return unicode_text( render(dict(records=records), tg.config['debugbar.engine'], 'tgext.debugbar.sections.templates.logging!html').split( '\n', 1)[-1])
def content(self): controllers = odict() map_controllers('', get_root_controller(), controllers) return unicode_text( render(dict(controllers=controllers), tg.config['debugbar.engine'], 'tgext.debugbar.sections.templates.controllers!html').split( '\n', 1)[-1])
def test_custom_failure_message(self): message = u_('This is a custom message whose id is: %(id_number)s') id_number = 23 p = EqualsFour(msg=message) try: p.unmet(message, id_number=id_number) self.fail('An exception must have been raised') except predicates.NotAuthorizedError as e: self.assertEqual(unicode_text(e), message % dict(id_number=id_number))
def content(self): controllers = odict() map_controllers("", get_root_controller(), controllers) return unicode_text( render( dict(controllers=controllers), tg.config["debugbar.engine"], "tgext.debugbar.sections.templates.controllers!html", ).split("\n", 1)[-1] )
def content(self): data = self._gather_queries() if not data: return 'No queries in executed by the controller.' if isinstance(data, str): return data return unicode_text(render(dict(queries=data, tg=tg), config['debugbar.engine'], 'tgext.debugbar.sections.templates.sqla!html').split('\n', 1)[-1])
def content(self): data = self._gather_queries() if not data: return 'No queries in executed by the controller.' if isinstance(data, str): return data return unicode_text( render(dict(queries=data, tg=tg), config['debugbar.engine'], 'tgext.debugbar.sections.templates.sqla!html').split( '\n', 1)[-1])
def test_unauthorized_with_unicode_message(self): # This test is broken on Python 2.4 and 2.5 because the unicode() # function doesn't work when converting an exception into an unicode # string (this is, to extract its message). unicode_msg = u_('请登陆') environ = {'test_number': 3} p = EqualsFour(msg=unicode_msg) try: p.check_authorization(environ) self.fail('Authorization must have been rejected') except predicates.NotAuthorizedError as e: self.assertEqual(unicode_text(e), unicode_msg)
def eval_unmet_predicate(self, p, environ, expected_error): """Evaluate a predicate that should not be met""" credentials = environ.get('repoze.what.credentials') # Testing check_authorization try: p.evaluate(environ, credentials) self.fail('Predicate must not be met; expected error: %s' % expected_error) except predicates.NotAuthorizedError as error: self.assertEqual(unicode_text(error), expected_error) # Testing is_met: self.assertEqual(p.is_met(environ), False)
def validation_errors_response(*args, **kwargs): """Returns a :class:`.Response` object with validation errors. The response will be created with a *412 Precondition Failed* status code and errors are reported in JSON format as response body. Typical usage is as ``error_handler`` for JSON based api:: @expose('json') @validate({'display_name': validators.NotEmpty(), 'group_name': validators.NotEmpty()}, error_handler=validation_errors_response) def post(self, **params): group = Group(**params) return dict(group=group) """ req = request._current_obj() errors = dict((unicode_text(key), unicode_text(error)) for key, error in req.validation.errors.items()) values = req.validation.values try: return Response(status=412, json_body={ 'errors': errors, 'values': values }) except TypeError: # values cannot be encoded to JSON, this might happen after # validation passed and validators converted them to complex objects. # In this case use request params, instead of controller params. return Response(status=412, json_body={ 'errors': errors, 'values': req.args_params })
def _check_authorization(self, *args, **kwargs): req = request._current_obj() try: self.predicate.check_authorization(req.environ) except NotAuthorizedError as e: reason = unicode_text(e) if req.environ.get('repoze.who.identity'): # The user is authenticated. code = 403 else: # The user is not authenticated. code = 401 response.status = code return self.denial_handler(reason)
def __call__(self, message, status=None, **extra_payload): """Registers a flash message for display on current or next request.""" # Force the message to be unicode so lazystrings, etc... are coerced message = unicode_text(message) payload = self._prepare_payload(message=message, status=status or self.default_status, **extra_payload) if request is not None: # Save the payload in environ too in case JavaScript is not being # used and the message is being displayed in the same request. request.environ["webflash.payload"] = payload resp = response._current_obj() resp.set_cookie(self.cookie_name, payload) if len(resp.headers["Set-Cookie"]) > 4096: raise ValueError("Flash value is too long (cookie would be >4k)")
def __call__(self, message, status=None, **extra_payload): # Force the message to be unicode so lazystrings, etc... are coerced message = unicode_text(message) payload = self.prepare_payload(message = message, status = status or self.default_status, **extra_payload) if request is not None: # Save the payload in environ too in case JavaScript is not being # used and the message is being displayed in the same request. request.environ['webflash.payload'] = payload resp = response._current_obj() resp.set_cookie(self.cookie_name, payload) if len(resp.headers['Set-Cookie']) > 4096: raise ValueError('Flash value is too long (cookie would be >4k)')
def evaluate(self, environ, credentials): """ Evaluate all the predicates it contains. :param environ: The WSGI environment. :param credentials: The :mod:`repoze.what` ``credentials``. :raises NotAuthorizedError: If none of the predicates is met. """ errors = [] for p in self.predicates: try: p.evaluate(environ, credentials) return except NotAuthorizedError as exc: errors.append(unicode_text(exc)) failed_predicates = ', '.join(errors) self.unmet(failed_predicates=failed_predicates)
def __call__(self, message, status=None, overwrite=False, **extra_payload): if response is None: raise ValueError("Must provide a response object or " "configure a callable that provides one") payload = [] if not overwrite and request: try: # Get payload, if already set before payload = request.environ['webflash.payload'] payload = json.loads(url_unquote(payload)) log.debug("Got payload from environ %d", id(request.environ)) if isinstance(payload, dict): log.debug('Upgrading old-style payload...') payload = [payload] except: # No previous payload set before pass payload.append( dict( # Force the message to be unicode so lazystrings, etc... are coerced message=unicode_text(message), status=status or self.default_status, **extra_payload )) payload = url_quote(json.dumps(payload)) if request: # Save the payload in environ too in case JavaScript is not being # used and the message is being displayed in the same request. request.environ['webflash.payload'] = payload log.debug("Setting payload in environ %d", id(request.environ)) log.debug("Setting payload in cookie") response.set_cookie(self.cookie_name, payload) if len(response.headers['Set-Cookie']) > 4096: raise ValueError('Flash value is too long (cookie would be >4k)')
def content(self): records = [] for record in self.get_and_clear(): msg = record.getMessage() if isinstance(msg, bytes): msg = msg.decode('utf-8', 'ignore') records.append({ 'message': msg, 'time': datetime.datetime.fromtimestamp(record.created), 'level': record.levelname, 'file': format_fname(record.pathname), 'file_long': record.pathname, 'line': record.lineno, }) records = reversed(records) return unicode_text(render( dict(records=records), tg.config['debugbar.engine'], 'tgext.debugbar.sections.templates.logging!html' ).split('\n', 1)[-1])
def content(self): queries = getattr(request, 'tgdb_ming_cursors', []) if not queries: return 'No queries in executed by the controller.' data = [] for query in queries.values(): params = json.dumps(query['params'], default=json_util.default) data.append({ 'duration': query['duration'], 'command': query['command'], 'collection': query['collection'], 'filter': format_json(params), 'params': params }) delattr(request, 'tgdb_ming_cursors') return unicode_text( render(dict(queries=data, tg=tg), config['debugbar.engine'], 'tgext.debugbar.sections.templates.ming!html').split( '\n', 1)[-1])
def _smart_str(s): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. This function was borrowed from Django. """ if isinstance(s, byte_string): return s elif isinstance(s, unicode_text): return s.encode('utf-8', 'strict') else: try: return bytes_(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return ' '.join([_smart_str(arg).decode('utf-8') for arg in s.args]).encode('utf-8', 'strict') return unicode_text(s).encode('utf-8', 'strict')
def content(self): queries = getattr(request, 'tgdb_ming_cursors', []) if not queries: return 'No queries in executed by the controller.' data = [] for query in queries.values(): params = json.dumps(query['params'], default=json_util.default) data.append({ 'duration': query['duration'], 'command': query['command'], 'collection': query['collection'], 'filter': format_json(params), 'params': params }) delattr(request, 'tgdb_ming_cursors') return unicode_text(render( dict(queries=data, tg=tg), config['debugbar.engine'], 'tgext.debugbar.sections.templates.ming!html' ).split('\n', 1)[-1])
def _smart_str(s): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. This function was borrowed from Django. """ if not isinstance(s, string_type): try: return bytes_(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return " ".join([_smart_str(arg).decode("utf-8") for arg in s.args]).encode("utf-8", "strict") return unicode_text(s).encode("utf-8", "strict") elif isinstance(s, unicode_text): return s.encode("utf-8", "strict") else: return s
def content(self): try: return unicode_text(render(dict( render_info=request.tgdb_render_info, stats=request.tgdb_profiling_stats, function_calls=request.tgdb_profiling_function_calls, render_calls=request.tgdb_render_calls, vars={'Total Time': request.tgdb_total_time, 'Controller Time': request.tgdb_call_time, 'Render Time': request.tgdb_render_time}), config['debugbar.engine'], 'tgext.debugbar.sections.templates.timing!html' ).split('\n', 1)[-1]) finally: delattr(request, 'tgdb_render_info') delattr(request, 'tgdb_call_start_time') delattr(request, 'tgdb_call_time') delattr(request, 'tgdb_render_start_time') delattr(request, 'tgdb_render_call_start_time') delattr(request, 'tgdb_render_calls') delattr(request, 'tgdb_total_time') delattr(request, 'tgdb_render_time') delattr(request, 'tgdb_profiling_stats') delattr(request, 'tgdb_profiling_function_calls')
def hello(self, **kw): return dict(text=unicode_text(i18n.ugettext('Your application is now running')))
def make_compound_message(cls, error_dict): return unicode_text('\n').join( unicode_text("%s: %s") % errorinfo for errorinfo in error_dict.items() )
def __unicode__(self): # pragma: no cover return unicode_text(self.msg)
def lazy_hello(self, **kw): return dict(text=unicode_text( i18n.lazy_ugettext('Your application is now running')))
def __unicode__(self): return unicode_text(self.msg)