Python cherrypy.lib() Examples

The following are 30 code examples of cherrypy.lib(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cherrypy , or try the search function .
Example #1
Source File: _cptools.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def default(self, *vpath, **params):
        rpcparams, rpcmethod = _xmlrpc.process_body()

        subhandler = self
        for attr in str(rpcmethod).split('.'):
            subhandler = getattr(subhandler, attr, None)

        if subhandler and getattr(subhandler, 'exposed', False):
            body = subhandler(*(vpath + rpcparams), **params)

        else:
            # https://github.com/cherrypy/cherrypy/issues/533
            # if a method is not found, an xmlrpclib.Fault should be returned
            # raising an exception here will do that; see
            # cherrypy.lib.xmlrpcutil.on_error
            raise Exception('method "%s" is not supported' % attr)

        conf = cherrypy.serving.request.toolmaps['tools'].get('xmlrpc', {})
        _xmlrpc.respond(body,
                        conf.get('encoding', 'utf-8'),
                        conf.get('allow_none', 0))
        return cherrypy.serving.response.body 
Example #2
Source File: _cptools.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def default(self, *vpath, **params):
        rpcparams, rpcmethod = _xmlrpc.process_body()

        subhandler = self
        for attr in str(rpcmethod).split('.'):
            subhandler = getattr(subhandler, attr, None)

        if subhandler and getattr(subhandler, 'exposed', False):
            body = subhandler(*(vpath + rpcparams), **params)

        else:
            # https://github.com/cherrypy/cherrypy/issues/533
            # if a method is not found, an xmlrpclib.Fault should be returned
            # raising an exception here will do that; see
            # cherrypy.lib.xmlrpcutil.on_error
            raise Exception('method "%s" is not supported' % attr)

        conf = cherrypy.serving.request.toolmaps['tools'].get('xmlrpc', {})
        _xmlrpc.respond(body,
                        conf.get('encoding', 'utf-8'),
                        conf.get('allow_none', 0))
        return cherrypy.serving.response.body 
Example #3
Source File: _cptools.py    From moviegrabber with GNU General Public License v3.0 6 votes vote down vote up
def default(self, *vpath, **params):
        rpcparams, rpcmethod = _xmlrpc.process_body()
        
        subhandler = self
        for attr in str(rpcmethod).split('.'):
            subhandler = getattr(subhandler, attr, None)
         
        if subhandler and getattr(subhandler, "exposed", False):
            body = subhandler(*(vpath + rpcparams), **params)
        
        else:
            # http://www.cherrypy.org/ticket/533
            # if a method is not found, an xmlrpclib.Fault should be returned
            # raising an exception here will do that; see
            # cherrypy.lib.xmlrpcutil.on_error
            raise Exception('method "%s" is not supported' % attr)
        
        conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {})
        _xmlrpc.respond(body,
                        conf.get('encoding', 'utf-8'),
                        conf.get('allow_none', 0))
        return cherrypy.serving.response.body 
Example #4
Source File: _cptools.py    From opsbro with MIT License 6 votes vote down vote up
def default(self, *vpath, **params):
        rpcparams, rpcmethod = _xmlrpc.process_body()

        subhandler = self
        for attr in str(rpcmethod).split('.'):
            subhandler = getattr(subhandler, attr, None)

        if subhandler and getattr(subhandler, "exposed", False):
            body = subhandler(*(vpath + rpcparams), **params)

        else:
            # https://bitbucket.org/cherrypy/cherrypy/issue/533
            # if a method is not found, an xmlrpclib.Fault should be returned
            # raising an exception here will do that; see
            # cherrypy.lib.xmlrpcutil.on_error
            raise Exception('method "%s" is not supported' % attr)

        conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {})
        _xmlrpc.respond(body,
                        conf.get('encoding', 'utf-8'),
                        conf.get('allow_none', 0))
        return cherrypy.serving.response.body 
Example #5
Source File: _cptools.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
def default(self, *vpath, **params):
        rpcparams, rpcmethod = _xmlrpc.process_body()

        subhandler = self
        for attr in str(rpcmethod).split('.'):
            subhandler = getattr(subhandler, attr, None)

        if subhandler and getattr(subhandler, 'exposed', False):
            body = subhandler(*(vpath + rpcparams), **params)

        else:
            # https://github.com/cherrypy/cherrypy/issues/533
            # if a method is not found, an xmlrpclib.Fault should be returned
            # raising an exception here will do that; see
            # cherrypy.lib.xmlrpcutil.on_error
            raise Exception('method "%s" is not supported' % attr)

        conf = cherrypy.serving.request.toolmaps['tools'].get('xmlrpc', {})
        _xmlrpc.respond(body,
                        conf.get('encoding', 'utf-8'),
                        conf.get('allow_none', 0))
        return cherrypy.serving.response.body 
Example #6
Source File: test_session.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def test_1_Ram_Concurrency(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
        self._test_Concurrency() 
Example #7
Source File: test_session.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def test_2_File_Concurrency(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.FileSession')
        self._test_Concurrency() 
Example #8
Source File: _cprequest.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def hooks_namespace(k, v):
    """Attach bare hooks declared in config."""
    # Use split again to allow multiple hooks for a single
    # hookpoint per path (e.g. "hooks.before_handler.1").
    # Little-known fact you only get from reading source ;)
    hookpoint = k.split('.', 1)[0]
    if isinstance(v, six.string_types):
        v = cherrypy.lib.reprconf.attributes(v)
    if not isinstance(v, Hook):
        v = Hook(v)
    cherrypy.serving.request.hooks[hookpoint].append(v) 
Example #9
Source File: _cpdispatch.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def XMLRPCDispatcher(next_dispatcher=Dispatcher()):
    from cherrypy.lib import xmlrpcutil

    def xmlrpc_dispatch(path_info):
        path_info = xmlrpcutil.patched_path(path_info)
        return next_dispatcher(path_info)
    return xmlrpc_dispatch 
Example #10
Source File: test_session.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def test_2_File_Concurrency(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.FileSession')
        self._test_Concurrency() 
Example #11
Source File: test_session.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def test_1_Ram_Concurrency(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
        self._test_Concurrency() 
Example #12
Source File: _cpdispatch.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def XMLRPCDispatcher(next_dispatcher=Dispatcher()):
    from cherrypy.lib import xmlrpcutil
    def xmlrpc_dispatch(path_info):
        path_info = xmlrpcutil.patched_path(path_info)
        return next_dispatcher(path_info)
    return xmlrpc_dispatch 
Example #13
Source File: _cprequest.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def hooks_namespace(k, v):
    """Attach bare hooks declared in config."""
    # Use split again to allow multiple hooks for a single
    # hookpoint per path (e.g. "hooks.before_handler.1").
    # Little-known fact you only get from reading source ;)
    hookpoint = k.split(".", 1)[0]
    if isinstance(v, basestring):
        v = cherrypy.lib.attributes(v)
    if not isinstance(v, Hook):
        v = Hook(v)
    cherrypy.serving.request.hooks[hookpoint].append(v) 
Example #14
Source File: _cprequest.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def hooks_namespace(k, v):
    """Attach bare hooks declared in config."""
    # Use split again to allow multiple hooks for a single
    # hookpoint per path (e.g. "hooks.before_handler.1").
    # Little-known fact you only get from reading source ;)
    hookpoint = k.split('.', 1)[0]
    if isinstance(v, text_or_bytes):
        v = cherrypy.lib.attributes(v)
    if not isinstance(v, Hook):
        v = Hook(v)
    cherrypy.serving.request.hooks[hookpoint].append(v) 
Example #15
Source File: _cpdispatch.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def XMLRPCDispatcher(next_dispatcher=Dispatcher()):
    from cherrypy.lib import xmlrpcutil

    def xmlrpc_dispatch(path_info):
        path_info = xmlrpcutil.patched_path(path_info)
        return next_dispatcher(path_info)
    return xmlrpc_dispatch 
Example #16
Source File: _cprequest.py    From opsbro with MIT License 5 votes vote down vote up
def hooks_namespace(k, v):
    """Attach bare hooks declared in config."""
    # Use split again to allow multiple hooks for a single
    # hookpoint per path (e.g. "hooks.before_handler.1").
    # Little-known fact you only get from reading source ;)
    hookpoint = k.split(".", 1)[0]
    if isinstance(v, basestring):
        v = cherrypy.lib.attributes(v)
    if not isinstance(v, Hook):
        v = Hook(v)
    cherrypy.serving.request.hooks[hookpoint].append(v) 
Example #17
Source File: _cpdispatch.py    From opsbro with MIT License 5 votes vote down vote up
def XMLRPCDispatcher(next_dispatcher=Dispatcher()):
    from cherrypy.lib import xmlrpcutil

    def xmlrpc_dispatch(path_info):
        path_info = xmlrpcutil.patched_path(path_info)
        return next_dispatcher(path_info)
    return xmlrpc_dispatch 
Example #18
Source File: test_session.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_0_Session(self):
        self.getPage(
            '/set_session_cls/cherrypy.lib.sessions.MemcachedSession'
        )

        self.getPage('/testStr')
        assert self.body == b'1'
        self.getPage('/testGen', self.cookies)
        assert self.body == b'2'
        self.getPage('/testStr', self.cookies)
        assert self.body == b'3'
        self.getPage('/length', self.cookies)
        self.assertErrorPage(500)
        assert b'NotImplementedError' in self.body
        self.getPage('/delkey?key=counter', self.cookies)
        assert self.status_code == 200

        # Wait for the session.timeout (1 second)
        time.sleep(1.25)
        self.getPage('/')
        assert self.body == b'1'

        # Test session __contains__
        self.getPage('/keyin?key=counter', self.cookies)
        assert self.body == b'True'

        # Test session delete
        self.getPage('/delete', self.cookies)
        assert self.body == b'done' 
Example #19
Source File: test_session.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_7_session_cookies(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
        self.getPage('/clear')
        self.getPage('/session_cookie')
        # grab the cookie ID
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        assert set(cookie_parts.keys()) == {'temp', 'Path'}
        id1 = cookie_parts['temp']
        assert list(sessions.RamSession.cache) == [id1]

        # Send another request in the same "browser session".
        self.getPage('/session_cookie', self.cookies)
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        assert set(cookie_parts.keys()) == {'temp', 'Path'}
        assert self.body.decode('utf-8') == id1
        assert list(sessions.RamSession.cache) == [id1]

        # Simulate a browser close by just not sending the cookies
        self.getPage('/session_cookie')
        # grab the cookie ID
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        assert set(cookie_parts.keys()) == {'temp', 'Path'}
        # Assert a new id has been generated...
        id2 = cookie_parts['temp']
        assert id1 != id2
        assert set(sessions.RamSession.cache.keys()) == {id1, id2}

        # Wait for the session.timeout on both sessions
        time.sleep(2.5)
        cache = list(sessions.RamSession.cache)
        if cache:
            if cache == [id2]:
                self.fail('The second session did not time out.')
            else:
                self.fail('Unknown session id in cache: %r', cache) 
Example #20
Source File: test_session.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_2_File_Concurrency(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.FileSession')
        self._test_Concurrency() 
Example #21
Source File: test_session.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_1_Ram_Concurrency(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
        self._test_Concurrency() 
Example #22
Source File: _cprequest.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hooks_namespace(k, v):
    """Attach bare hooks declared in config."""
    # Use split again to allow multiple hooks for a single
    # hookpoint per path (e.g. "hooks.before_handler.1").
    # Little-known fact you only get from reading source ;)
    hookpoint = k.split('.', 1)[0]
    if isinstance(v, str):
        v = cherrypy.lib.reprconf.attributes(v)
    if not isinstance(v, Hook):
        v = Hook(v)
    cherrypy.serving.request.hooks[hookpoint].append(v) 
Example #23
Source File: _cpdispatch.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def XMLRPCDispatcher(next_dispatcher=Dispatcher()):
    from cherrypy.lib import xmlrpcutil

    def xmlrpc_dispatch(path_info):
        path_info = xmlrpcutil.patched_path(path_info)
        return next_dispatcher(path_info)
    return xmlrpc_dispatch 
Example #24
Source File: _cprequest.py    From moviegrabber with GNU General Public License v3.0 4 votes vote down vote up
def finalize(self):
        """Transform headers (and cookies) into self.header_list. (Core)"""
        try:
            code, reason, _ = httputil.valid_status(self.status)
        except ValueError:
            raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])
        
        headers = self.headers
        
        self.status = "%s %s" % (code, reason)
        self.output_status = ntob(str(code), 'ascii') + ntob(" ") + headers.encode(reason)
        
        if self.stream:
            # The upshot: wsgiserver will chunk the response if
            # you pop Content-Length (or set it explicitly to None).
            # Note that lib.static sets C-L to the file's st_size.
            if dict.get(headers, 'Content-Length') is None:
                dict.pop(headers, 'Content-Length', None)
        elif code < 200 or code in (204, 205, 304):
            # "All 1xx (informational), 204 (no content),
            # and 304 (not modified) responses MUST NOT
            # include a message-body."
            dict.pop(headers, 'Content-Length', None)
            self.body = ntob("")
        else:
            # Responses which are not streamed should have a Content-Length,
            # but allow user code to set Content-Length if desired.
            if dict.get(headers, 'Content-Length') is None:
                content = self.collapse_body()
                dict.__setitem__(headers, 'Content-Length', len(content))
        
        # Transform our header dict into a list of tuples.
        self.header_list = h = headers.output()
        
        cookie = self.cookie.output()
        if cookie:
            for line in cookie.split("\n"):
                if line.endswith("\r"):
                    # Python 2.4 emits cookies joined by LF but 2.5+ by CRLF.
                    line = line[:-1]
                name, value = line.split(": ", 1)
                if isinstance(name, unicodestr):
                    name = name.encode("ISO-8859-1")
                if isinstance(value, unicodestr):
                    value = headers.encode(value)
                h.append((name, value)) 
Example #25
Source File: test_session.py    From Tautulli with GNU General Public License v3.0 4 votes vote down vote up
def test_7_session_cookies(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
        self.getPage('/clear')
        self.getPage('/session_cookie')
        # grab the cookie ID
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
        id1 = cookie_parts['temp']
        self.assertEqual(list(sessions.RamSession.cache), [id1])

        # Send another request in the same "browser session".
        self.getPage('/session_cookie', self.cookies)
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
        self.assertBody(id1)
        self.assertEqual(list(sessions.RamSession.cache), [id1])

        # Simulate a browser close by just not sending the cookies
        self.getPage('/session_cookie')
        # grab the cookie ID
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
        # Assert a new id has been generated...
        id2 = cookie_parts['temp']
        self.assertNotEqual(id1, id2)
        self.assertEqual(set(sessions.RamSession.cache.keys()),
                         set([id1, id2]))

        # Wait for the session.timeout on both sessions
        time.sleep(2.5)
        cache = list(sessions.RamSession.cache)
        if cache:
            if cache == [id2]:
                self.fail('The second session did not time out.')
            else:
                self.fail('Unknown session id in cache: %r', cache) 
Example #26
Source File: test_caching.py    From moviegrabber with GNU General Public License v3.0 4 votes vote down vote up
def testCaching(self):
        elapsed = 0.0
        for trial in range(10):
            self.getPage("/")
            # The response should be the same every time,
            # except for the Age response header.
            self.assertBody('visit #1')
            if trial != 0:
                age = int(self.assertHeader("Age"))
                self.assert_(age >= elapsed)
                elapsed = age
        
        # POST, PUT, DELETE should not be cached.
        self.getPage("/", method="POST")
        self.assertBody('visit #2')
        # Because gzip is turned on, the Vary header should always Vary for content-encoding
        self.assertHeader('Vary', 'Accept-Encoding')
        # The previous request should have invalidated the cache,
        # so this request will recalc the response.
        self.getPage("/", method="GET")
        self.assertBody('visit #3')
        # ...but this request should get the cached copy.
        self.getPage("/", method="GET")
        self.assertBody('visit #3')
        self.getPage("/", method="DELETE")
        self.assertBody('visit #4')
        
        # The previous request should have invalidated the cache,
        # so this request will recalc the response.
        self.getPage("/", method="GET", headers=[('Accept-Encoding', 'gzip')])
        self.assertHeader('Content-Encoding', 'gzip')
        self.assertHeader('Vary')
        self.assertEqual(cherrypy.lib.encoding.decompress(self.body), ntob("visit #5"))
        
        # Now check that a second request gets the gzip header and gzipped body
        # This also tests a bug in 3.0 to 3.0.2 whereby the cached, gzipped
        # response body was being gzipped a second time.
        self.getPage("/", method="GET", headers=[('Accept-Encoding', 'gzip')])
        self.assertHeader('Content-Encoding', 'gzip')
        self.assertEqual(cherrypy.lib.encoding.decompress(self.body), ntob("visit #5"))
        
        # Now check that a third request that doesn't accept gzip
        # skips the cache (because the 'Vary' header denies it).
        self.getPage("/", method="GET")
        self.assertNoHeader('Content-Encoding')
        self.assertBody('visit #6') 
Example #27
Source File: helper.py    From moviegrabber with GNU General Public License v3.0 4 votes vote down vote up
def _setup_server(cls, supervisor, conf):
        v = sys.version.split()[0]
        log.info("Python version used to run this test script: %s" % v)
        log.info("CherryPy version: %s" % cherrypy.__version__)
        if supervisor.scheme == "https":
            ssl = " (ssl)"
        else:
            ssl = ""
        log.info("HTTP server version: %s%s" % (supervisor.protocol, ssl))
        log.info("PID: %s" % os.getpid())

        cherrypy.server.using_apache = supervisor.using_apache
        cherrypy.server.using_wsgi = supervisor.using_wsgi

        if sys.platform[:4] == 'java':
            cherrypy.config.update({'server.nodelay': False})

        if isinstance(conf, basestring):
            parser = cherrypy.lib.reprconf.Parser()
            conf = parser.dict_from_file(conf).get('global', {})
        else:
            conf = conf or {}
        baseconf = conf.copy()
        baseconf.update({'server.socket_host': supervisor.host,
                         'server.socket_port': supervisor.port,
                         'server.protocol_version': supervisor.protocol,
                         'environment': "test_suite",
                         })
        if supervisor.scheme == "https":
            #baseconf['server.ssl_module'] = 'builtin'
            baseconf['server.ssl_certificate'] = serverpem
            baseconf['server.ssl_private_key'] = serverpem

        # helper must be imported lazily so the coverage tool
        # can run against module-level statements within cherrypy.
        # Also, we have to do "from cherrypy.test import helper",
        # exactly like each test module does, because a relative import
        # would stick a second instance of webtest in sys.modules,
        # and we wouldn't be able to globally override the port anymore.
        if supervisor.scheme == "https":
            webtest.WebCase.HTTP_CONN = HTTPSConnection
        return baseconf 
Example #28
Source File: test_caching.py    From Tautulli with GNU General Public License v3.0 4 votes vote down vote up
def testCaching(self):
        elapsed = 0.0
        for trial in range(10):
            self.getPage('/')
            # The response should be the same every time,
            # except for the Age response header.
            self.assertBody('visit #1')
            if trial != 0:
                age = int(self.assertHeader('Age'))
                self.assert_(age >= elapsed)
                elapsed = age

        # POST, PUT, DELETE should not be cached.
        self.getPage('/', method='POST')
        self.assertBody('visit #2')
        # Because gzip is turned on, the Vary header should always Vary for
        # content-encoding
        self.assertHeader('Vary', 'Accept-Encoding')
        # The previous request should have invalidated the cache,
        # so this request will recalc the response.
        self.getPage('/', method='GET')
        self.assertBody('visit #3')
        # ...but this request should get the cached copy.
        self.getPage('/', method='GET')
        self.assertBody('visit #3')
        self.getPage('/', method='DELETE')
        self.assertBody('visit #4')

        # The previous request should have invalidated the cache,
        # so this request will recalc the response.
        self.getPage('/', method='GET', headers=[('Accept-Encoding', 'gzip')])
        self.assertHeader('Content-Encoding', 'gzip')
        self.assertHeader('Vary')
        self.assertEqual(
            cherrypy.lib.encoding.decompress(self.body), b'visit #5')

        # Now check that a second request gets the gzip header and gzipped body
        # This also tests a bug in 3.0 to 3.0.2 whereby the cached, gzipped
        # response body was being gzipped a second time.
        self.getPage('/', method='GET', headers=[('Accept-Encoding', 'gzip')])
        self.assertHeader('Content-Encoding', 'gzip')
        self.assertEqual(
            cherrypy.lib.encoding.decompress(self.body), b'visit #5')

        # Now check that a third request that doesn't accept gzip
        # skips the cache (because the 'Vary' header denies it).
        self.getPage('/', method='GET')
        self.assertNoHeader('Content-Encoding')
        self.assertBody('visit #6') 
Example #29
Source File: _cprequest.py    From Tautulli with GNU General Public License v3.0 4 votes vote down vote up
def finalize(self):
        """Transform headers (and cookies) into self.header_list. (Core)"""
        try:
            code, reason, _ = httputil.valid_status(self.status)
        except ValueError:
            raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])

        headers = self.headers

        self.status = '%s %s' % (code, reason)
        self.output_status = ntob(str(code), 'ascii') + \
            b' ' + headers.encode(reason)

        if self.stream:
            # The upshot: wsgiserver will chunk the response if
            # you pop Content-Length (or set it explicitly to None).
            # Note that lib.static sets C-L to the file's st_size.
            if dict.get(headers, 'Content-Length') is None:
                dict.pop(headers, 'Content-Length', None)
        elif code < 200 or code in (204, 205, 304):
            # "All 1xx (informational), 204 (no content),
            # and 304 (not modified) responses MUST NOT
            # include a message-body."
            dict.pop(headers, 'Content-Length', None)
            self._flush_body()
            self.body = b''
        else:
            # Responses which are not streamed should have a Content-Length,
            # but allow user code to set Content-Length if desired.
            if dict.get(headers, 'Content-Length') is None:
                content = self.collapse_body()
                dict.__setitem__(headers, 'Content-Length', len(content))

        # Transform our header dict into a list of tuples.
        self.header_list = h = headers.output()

        cookie = self.cookie.output()
        if cookie:
            for line in cookie.split('\r\n'):
                name, value = line.split(': ', 1)
                if isinstance(name, six.text_type):
                    name = name.encode('ISO-8859-1')
                if isinstance(value, six.text_type):
                    value = headers.encode(value)
                h.append((name, value)) 
Example #30
Source File: test_session.py    From bazarr with GNU General Public License v3.0 4 votes vote down vote up
def test_7_session_cookies(self):
        self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
        self.getPage('/clear')
        self.getPage('/session_cookie')
        # grab the cookie ID
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
        id1 = cookie_parts['temp']
        self.assertEqual(copykeys(sessions.RamSession.cache), [id1])

        # Send another request in the same "browser session".
        self.getPage('/session_cookie', self.cookies)
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
        self.assertBody(id1)
        self.assertEqual(copykeys(sessions.RamSession.cache), [id1])

        # Simulate a browser close by just not sending the cookies
        self.getPage('/session_cookie')
        # grab the cookie ID
        cookie_parts = dict([p.strip().split('=')
                            for p in self.cookies[0][1].split(';')])
        # Assert there is no 'expires' param
        self.assertEqual(set(cookie_parts.keys()), set(['temp', 'Path']))
        # Assert a new id has been generated...
        id2 = cookie_parts['temp']
        self.assertNotEqual(id1, id2)
        self.assertEqual(set(sessions.RamSession.cache.keys()),
                         set([id1, id2]))

        # Wait for the session.timeout on both sessions
        time.sleep(2.5)
        cache = copykeys(sessions.RamSession.cache)
        if cache:
            if cache == [id2]:
                self.fail('The second session did not time out.')
            else:
                self.fail('Unknown session id in cache: %r', cache)