示例#1
0
    def test_content_type(self):
        r = Response()

        r.content_type = u_('text/html')
        # Verify it's a native string, and not unicode.
        assert type(r.content_type) == str
        assert r.content_type == 'text/html'

        del r.content_type
        assert r.content_type is None
示例#2
0
    def test_signed_cookie(self):
        resp = Response()
        resp.signed_cookie('key_name', 'VALUE', secret='123')
        cookie = resp.headers['Set-Cookie']

        r = Request({}, headers={'Cookie':cookie})
        value = r.signed_cookie('key_name', '123')
        assert value == 'VALUE', value

        r = Request({}, headers={'Cookie':cookie})
        value = r.signed_cookie('non_existing', '123')
        assert not value
示例#3
0
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
                        })
示例#4
0
    def __call__(self, environ, start_response):
        status, headers, app_iter, exc_info = _call_wsgi_application(self.app, environ)
        if status[:3] in self.errors and \
            'tg.status_code_redirect' not in environ and self.error_path:
            # Create a response object
            environ['tg.original_response'] = Response(status=status, headerlist=headers, app_iter=app_iter)
            environ['tg.original_request'] = Request(environ)

            environ['pylons.original_response'] = environ['tg.original_response']
            environ['pylons.original_request'] = environ['tg.original_request']
            
            # Create a new environ to avoid touching the original request data
            new_environ = environ.copy()
            new_environ['PATH_INFO'] = self.error_path

            newstatus, headers, app_iter, exc_info = _call_wsgi_application(self.app, new_environ)
        start_response(status, headers, exc_info)
        return app_iter
示例#5
0
文件: wsgiapp.py 项目: hhy5277/tg2
    def _setup_app_env(self, environ):
        """Setup Request, Response and TurboGears context objects.

        Is also in charge of pushing TurboGears context into the
        paste registry and detect test mode. Returns whenever
        the testmode is enabled or not and the TurboGears context.
        """
        conf = self.config
        testing = False

        # Setup the basic global objects
        req = Request(environ)
        req._fast_setattr('_language', self.lang)
        req._fast_setattr('_response_type', None)

        resp_options = self.resp_options
        response = Response(content_type=resp_options['content_type'],
                            charset=resp_options['charset'],
                            headers=resp_options['headers'])

        # Setup the translator object
        translator = _get_translator(self.lang, tg_config=conf)

        if self.strict_tmpl_context:
            tmpl_context = TemplateContext()
        else:
            tmpl_context = AttribSafeTemplateContext()

        app_globals = self.globals

        locals = RequestLocals()
        locals.response = response
        locals.request = req
        locals.app_globals = app_globals
        locals.config = conf
        locals.tmpl_context = tmpl_context
        locals.translator = translator
        locals.session = environ.get(
            'beaker.session')  # Usually None, unless middleware in place
        locals.cache = environ.get(
            'beaker.cache')  # Usually None, unless middleware in place

        environ['tg.locals'] = locals

        # Register Global objects
        registry = environ['paste.registry']
        registry.register(request_local.config, conf)
        registry.register(request_local.context, locals)

        if 'paste.testing_variables' in environ:
            testing = True
            testenv = environ['paste.testing_variables']
            testenv['req'] = req
            testenv['response'] = response
            testenv['tmpl_context'] = tmpl_context
            testenv['app_globals'] = self.globals
            testenv['config'] = conf
            testenv['session'] = locals.session
            testenv['cache'] = locals.cache

        return testing, locals, registry
示例#6
0
    def setup_app_env(self, environ):
        """Setup Request, Response and TurboGears context objects.

        Is also in charge of pushing TurboGears context into the
        paste registry and detect test mode. Returns whenever
        the testmode is enabled or not and the TurboGears context.
        """
        conf = self.config

        # Setup the basic global objects
        req = Request(environ)
        req._fast_setattr('_language', conf['lang'])
        req._fast_setattr('_response_type', None)

        resp_options = self.resp_options
        response = Response(content_type=resp_options['content_type'],
                            charset=resp_options['charset'],
                            headers=resp_options['headers'])

        # Setup the translator object
        lang = conf['lang']
        translator = _get_translator(lang, tg_config=conf)

        if self.strict_tmpl_context:
            tmpl_context = ContextObj()
        else:
            tmpl_context = AttribSafeContextObj()

        app_globals = self.globals
        session = environ.get('beaker.session')
        cache = environ.get('beaker.cache')

        locals = RequestLocals()
        locals.response = response
        locals.request = req
        locals.app_globals = app_globals
        locals.config = conf
        locals.tmpl_context = tmpl_context
        locals.translator = translator
        locals.session = session
        locals.cache = cache

        if self.enable_routes:  #pragma: no cover
            url = environ.get('routes.url')
            locals.url = url

        environ['tg.locals'] = locals

        #Register Global objects
        registry = environ['paste.registry']
        registry.register(request_local.config, conf)
        registry.register(request_local.context, locals)

        if 'paste.testing_variables' in environ:
            testenv = environ['paste.testing_variables']
            testenv['req'] = req
            testenv['response'] = response
            testenv['tmpl_context'] = tmpl_context
            testenv['app_globals'] = self.globals
            testenv['config'] = conf
            testenv['session'] = locals.session
            testenv['cache'] = locals.cache
            return True, locals

        return False, locals
示例#7
0
 def test_wsgi_response(self):
     r = Response()
     status, headers, body = r.wsgi_response()
     assert '200 OK' == status
示例#8
0
 def test_wsgi_response(self):
     r = Response()
     status, headers, body = r.wsgi_response()
     assert '200 OK' == status