Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

Changeset 2461

Show
Ignore:
Timestamp:
06/24/09 00:10:34
Author:
fumanchu
Message:

python3: port of [2460] (All internals now use cherrypy.serving.request/response instead of request/response for a speed boost)

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • branches/python3/cherrypy/_cpdispatch.py

    r2373 r2461  
    5353    parameters are part of the request; if they are invalid a 400 Bad Request. 
    5454    """ 
    55     show_mismatched_params = getattr(cherrypy.request, 'show_mismatched_params', False) 
     55    show_mismatched_params = getattr( 
     56        cherrypy.serving.request, 'show_mismatched_params', False) 
    5657    try: 
    5758        (args, varargs, varkw, defaults) = inspect.getargspec(callable) 
     
    120121        raise cherrypy.HTTPError(404) 
    121122 
    122     body_params = cherrypy.request.body.params or {} 
     123    body_params = cherrypy.serving.request.body.params or {} 
    123124    body_params = set(body_params.keys()) 
    124125    qs_params = set(callable_kwargs.keys()) - body_params 
     
    177178     
    178179    def _get_kwargs(self): 
    179         kwargs = cherrypy.request.params.copy() 
     180        kwargs = cherrypy.serving.request.params.copy() 
    180181        if self._kwargs: 
    181182            kwargs.update(self._kwargs) 
     
    245246        positional arguments. 
    246247        """ 
    247         request = cherrypy.request 
     248        request = cherrypy.serving.request 
    248249        app = request.app 
    249250        root = app.root 
     
    356357    def __call__(self, path_info): 
    357358        """Set handler and config for the current request.""" 
    358         request = cherrypy.request 
     359        request = cherrypy.serving.request 
    359360        resource, vpath = self.find_handler(path_info) 
    360361         
     
    365366                avail.append("HEAD") 
    366367            avail.sort() 
    367             cherrypy.response.headers['Allow'] = ", ".join(avail) 
     368            cherrypy.serving.response.headers['Allow'] = ", ".join(avail) 
    368369             
    369370            # Find the subhandler 
     
    414415        func = self.find_handler(path_info) 
    415416        if func: 
    416             cherrypy.request.handler = LateParamPageHandler(func) 
     417            cherrypy.serving.request.handler = LateParamPageHandler(func) 
    417418        else: 
    418             cherrypy.request.handler = cherrypy.NotFound() 
     419            cherrypy.serving.request.handler = cherrypy.NotFound() 
    419420     
    420421    def find_handler(self, path_info): 
     
    422423        import routes 
    423424         
    424         request = cherrypy.request 
     425        request = cherrypy.serving.request 
    425426         
    426427        config = routes.request_config() 
    427428        config.mapper = self.mapper 
    428         if hasattr(cherrypy.request, 'wsgi_environ'): 
    429             config.environ = cherrypy.request.wsgi_environ 
     429        if hasattr(request, 'wsgi_environ'): 
     430            config.environ = request.wsgi_environ 
    430431        config.host = request.headers.get('Host', None) 
    431432        config.protocol = request.scheme 
     
    541542    from cherrypy.lib import httputil 
    542543    def vhost_dispatch(path_info): 
    543         header = cherrypy.request.headers.get 
     544        request = cherrypy.serving.request 
     545        header = request.headers.get 
    544546         
    545547        domain = header('Host', '') 
     
    554556         
    555557        # Touch up staticdir config. See http://www.cherrypy.org/ticket/614. 
    556         section = cherrypy.request.config.get('tools.staticdir.section') 
     558        section = request.config.get('tools.staticdir.section') 
    557559        if section: 
    558560            section = section[len(prefix):] 
    559             cherrypy.request.config['tools.staticdir.section'] = section 
     561            request.config['tools.staticdir.section'] = section 
    560562         
    561563        return result 
  • branches/python3/cherrypy/_cperror.py

    r2450 r2461  
    55from traceback import format_exception as _format_exception 
    66from urllib.parse import urljoin as _urljoin 
    7 from cherrypy.lib import httputil 
     7from cherrypy.lib import httputil as _httputil 
    88 
    99 
     
    3030    def __init__(self, path, query_string=""): 
    3131        import cherrypy 
    32         request = cherrypy.request 
     32        request = cherrypy.serving.request 
    3333         
    3434        self.query_string = query_string 
     
    6161    def __init__(self, urls, status=None): 
    6262        import cherrypy 
    63         request = cherrypy.request 
     63        request = cherrypy.serving.request 
    6464         
    6565        if isinstance(urls, str): 
     
    100100        """ 
    101101        import cherrypy 
    102         response = cherrypy.response 
     102        response = cherrypy.serving.response 
    103103        response.status = status = self.status 
    104104         
     
    160160    import cherrypy 
    161161     
    162     response = cherrypy.response 
     162    response = cherrypy.serving.response 
    163163     
    164164    # Remove headers which applied to the original content, 
     
    193193        self.status = status 
    194194        try: 
    195             self.code, self.reason, defaultmsg = httputil.valid_status(status) 
     195            self.code, self.reason, defaultmsg = _httputil.valid_status(status) 
    196196        except ValueError as x: 
    197197            raise self.__class__(500, x.args[0]) 
     
    213213        import cherrypy 
    214214         
    215         response = cherrypy.response 
     215        response = cherrypy.serving.response 
    216216         
    217217        clean_headers(self.code) 
     
    221221        response.status = self.status 
    222222        tb = None 
    223         if cherrypy.request.show_tracebacks: 
     223        if cherrypy.serving.request.show_tracebacks: 
    224224            tb = format_exc() 
    225225        response.headers['Content-Type'] = "text/html;charset=utf-8" 
     
    246246        if path is None: 
    247247            import cherrypy 
    248             path = cherrypy.request.script_name + cherrypy.request.path_info 
     248            request = cherrypy.serving.request 
     249            path = request.script_name + request.path_info 
    249250        self.args = (path,) 
    250251        HTTPError.__init__(self, 404, "The path %r was not found." % path) 
     
    289290     
    290291    try: 
    291         code, reason, message = httputil.valid_status(status) 
     292        code, reason, message = _httputil.valid_status(status) 
    292293    except ValueError as x: 
    293294        raise cherrypy.HTTPError(500, x.args[0]) 
     
    311312     
    312313    # Use a custom template or callable for the error page? 
    313     pages = cherrypy.request.error_page 
     314    pages = cherrypy.serving.request.error_page 
    314315    error_page = pages.get(code) or pages.get('default') 
    315316    if error_page: 
     
    339340def _be_ie_unfriendly(status): 
    340341    import cherrypy 
    341     response = cherrypy.response 
     342    response = cherrypy.serving.response 
    342343     
    343344    # For some statuses, Internet Explorer 5+ shows "friendly error 
  • branches/python3/cherrypy/_cplogging.py

    r2435 r2461  
    77logfmt = logging.Formatter("%(message)s") 
    88import os 
    9 import email.utils 
    109import sys 
    1110 
     
    7372        which are written in their C-style notation (\\n, \\t, etc). 
    7473        """ 
    75         request = cherrypy.request 
     74        request = cherrypy.serving.request 
    7675        remote = request.remote 
    77         response = cherrypy.response 
     76        response = cherrypy.serving.response 
    7877        outheaders = response.headers 
    7978        inheaders = request.headers 
     
    8988                 'r': request.request_line, 
    9089                 's': status, 
    91                  'b': outheaders.get('Content-Length', '') or "-", 
    92                  'f': inheaders.get('Referer', ''), 
    93                  'a': inheaders.get('User-Agent', ''), 
     90                 'b': dict.get(outheaders, 'Content-Length', '') or "-", 
     91                 'f': dict.get(inheaders, 'Referer', ''), 
     92                 'a': dict.get(inheaders, 'User-Agent', ''), 
    9493                 } 
    9594        for k, v in atoms.items(): 
     
    117116        """Return now() in Apache Common Log Format (no timezone).""" 
    118117        now = datetime.datetime.now() 
    119         monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 
    120                'aug', 'sep', 'oct', 'nov', 'dec', 
    121                'january', 'february', 'march', 'april', 'may', 'june', 'july', 
    122                'august', 'september', 'october', 'november', 'december'] 
     118        monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 
     119                      'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] 
    123120        month = monthnames[now.month - 1].capitalize() 
    124121        return ('[%02d/%s/%04d:%02d:%02d:%02d]' % 
     
    230227        """Flushes the stream.""" 
    231228        try: 
    232             stream = cherrypy.request.wsgi_environ.get('wsgi.errors') 
     229            stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') 
    233230        except (AttributeError, KeyError): 
    234231            pass 
     
    239236        """Emit a record.""" 
    240237        try: 
    241             stream = cherrypy.request.wsgi_environ.get('wsgi.errors') 
     238            stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') 
    242239        except (AttributeError, KeyError): 
    243240            pass 
  • branches/python3/cherrypy/_cpmodpy.py

    r2438 r2461  
    264264import os 
    265265import re 
     266import subprocess 
    266267 
    267268 
    268269def read_process(cmd, args=""): 
    269     pipein, pipeout = os.popen4("%s %s" % (cmd, args)) 
     270    fullcmd = "%s %s" % (cmd, args) 
     271    p = subprocess.Popen(fullcmd, shell=True, 
     272                         stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 
     273                         close_fds=True) 
    270274    try: 
    271         firstline = pipeout.readline() 
    272         if (re.search(r"(not recognized|No such file|not found)", firstline, 
     275        firstline = p.stdout.readline() 
     276        if (re.search(b"(not recognized|No such file|not found)", firstline, 
    273277                      re.IGNORECASE)): 
    274278            raise IOError('%s must be on your system path.' % cmd) 
    275         output = firstline + pipeout.read() 
     279        output = firstline + p.stdout.read() 
    276280    finally: 
    277         pipeout.close() 
     281        p.stdout.close() 
    278282    return output 
    279283 
  • branches/python3/cherrypy/_cpreqbody.py

    r2415 r2461  
    593593        # however, app developers are responsible in that case to set 
    594594        # cherrypy.request.process_body to False so this method isn't called. 
    595         h = cherrypy.request.headers 
     595        h = cherrypy.serving.request.headers 
    596596        if 'Content-Length' not in h and 'Transfer-Encoding' not in h: 
    597597            raise cherrypy.HTTPError(411) 
  • branches/python3/cherrypy/_cprequest.py

    r2451 r2461  
    133133    if not isinstance(v, Hook): 
    134134        v = Hook(v) 
    135     cherrypy.request.hooks[hookpoint].append(v) 
     135    cherrypy.serving.request.hooks[hookpoint].append(v) 
    136136 
    137137def request_namespace(k, v): 
    138138    """Attach request attributes declared in config.""" 
    139     setattr(cherrypy.request, k, v) 
     139    setattr(cherrypy.serving.request, k, v) 
    140140 
    141141def response_namespace(k, v): 
     
    144144    # http://cherrypy.org/ticket/889 
    145145    if k[:8] == 'headers.': 
    146         cherrypy.response.headers[k.split('.', 1)[1]] = v 
     146        cherrypy.serving.response.headers[k.split('.', 1)[1]] = v 
    147147    else: 
    148         setattr(cherrypy.response, k, v) 
     148        setattr(cherrypy.serving.response, k, v) 
    149149 
    150150def error_page_namespace(k, v): 
     
    152152    if k != 'default': 
    153153        k = int(k) 
    154     cherrypy.request.error_page[k] = v 
     154    cherrypy.serving.request.error_page[k] = v 
    155155 
    156156 
     
    521521         
    522522        """ 
     523        response = cherrypy.serving.response 
    523524        self.stage = 'run' 
    524525        try: 
     
    545546            sp = int(self.server_protocol[5]), int(self.server_protocol[7]) 
    546547            self.protocol = min(rp, sp) 
    547             cherrypy.response.headers.protocol = self.protocol 
     548            response.headers.protocol = self.protocol 
    548549             
    549550            # Rebuild first line of the request (e.g. "GET /path HTTP/1.0"). 
     
    584585                    body = "" 
    585586                r = bare_error(body) 
    586                 response = cherrypy.response 
    587587                response.output_status, response.header_list, response.body = r 
    588588         
    589589        if self.method == "HEAD": 
    590590            # HEAD requests MUST NOT return a message-body in the response. 
    591             cherrypy.response.body = [] 
     591            response.body = [] 
    592592         
    593593        try: 
     
    596596            cherrypy.log.error(traceback=True) 
    597597         
    598         if cherrypy.response.timed_out: 
     598        if response.timed_out: 
    599599            raise cherrypy.TimeoutError() 
    600600         
    601         return cherrypy.response 
     601        return response 
    602602     
    603603    # Uncomment for stage debugging 
     
    606606    def respond(self, path_info): 
    607607        """Generate a response for the resource at self.path_info. (Core)""" 
     608        response = cherrypy.serving.response 
    608609        try: 
    609610            try: 
     
    646647                    if self.handler: 
    647648                        self.stage = 'handler' 
    648                         cherrypy.response.body = self.handler() 
     649                        response.body = self.handler() 
    649650                     
    650651                    # Finalize 
    651652                    self.stage = 'before_finalize' 
    652653                    self.hooks.run('before_finalize') 
    653                     cherrypy.response.finalize() 
     654                    response.finalize() 
    654655                except (cherrypy.HTTPRedirect, cherrypy.HTTPError) as inst: 
    655656                    inst.set_response() 
    656657                    self.stage = 'before_finalize (HTTPError)' 
    657658                    self.hooks.run('before_finalize') 
    658                     cherrypy.response.finalize() 
     659                    response.finalize() 
    659660            finally: 
    660661                self.stage = 'on_end_resource' 
     
    719720     
    720721    def get_resource(self, path): 
    721  
    722722        """Call a dispatcher (which sets self.handler and .config). (Core)""" 
    723723        dispatch = self.dispatch 
     
    752752                self.error_response() 
    753753            self.hooks.run("after_error_response") 
    754             cherrypy.response.finalize() 
     754            cherrypy.serving.response.finalize() 
    755755        except cherrypy.HTTPRedirect as inst: 
    756756            inst.set_response() 
    757             cherrypy.response.finalize() 
     757            cherrypy.serving.response.finalize() 
    758758     
    759759    # ------------------------- Properties ------------------------- # 
  • branches/python3/cherrypy/_cptools.py

    r2396 r2461  
    8787            conf = {} 
    8888         
    89         tm = cherrypy.request.toolmaps[self.namespace] 
     89        tm = cherrypy.serving.request.toolmaps[self.namespace] 
    9090        if self._name in tm: 
    9191            conf.update(tm[self._name]) 
     
    130130        if p is None: 
    131131            p = getattr(self.callable, "priority", self._priority) 
    132         cherrypy.request.hooks.attach(self._point, self.callable, 
    133                                       priority=p, **conf) 
     132        cherrypy.serving.request.hooks.attach(self._point, self.callable, 
     133                                              priority=p, **conf) 
    134134 
    135135 
     
    160160            if not handled: 
    161161                raise cherrypy.NotFound() 
    162             return cherrypy.response.body 
     162            return cherrypy.serving.response.body 
    163163        handle_func.exposed = True 
    164164        return handle_func 
     
    166166    def _wrapper(self, **kwargs): 
    167167        if self.callable(**kwargs): 
    168             cherrypy.request.handler = None 
     168            cherrypy.serving.request.handler = None 
    169169     
    170170    def _setup(self): 
     
    178178        if p is None: 
    179179            p = getattr(self.callable, "priority", self._priority) 
    180         cherrypy.request.hooks.attach(self._point, self._wrapper, 
    181                                       priority=p, **conf) 
     180        cherrypy.serving.request.hooks.attach(self._point, self._wrapper, 
     181                                              priority=p, **conf) 
    182182 
    183183 
     
    207207     
    208208    def callable(self): 
    209         innerfunc = cherrypy.request.handler 
     209        innerfunc = cherrypy.serving.request.handler 
    210210        def wrap(*args, **kwargs): 
    211211            return self.newhandler(innerfunc, *args, **kwargs) 
    212         cherrypy.request.handler = wrap 
     212        cherrypy.serving.request.handler = wrap 
    213213 
    214214 
     
    228228        method when the tool is "turned on" in config. 
    229229        """ 
    230         cherrypy.request.error_response = self._wrapper 
     230        cherrypy.serving.request.error_response = self._wrapper 
    231231 
    232232 
     
    267267        method when the tool is "turned on" in config. 
    268268        """ 
    269         hooks = cherrypy.request.hooks 
     269        hooks = cherrypy.serving.request.hooks 
    270270         
    271271        conf = self._merged_args() 
     
    359359            raise Exception('method "%s" is not supported' % attr) 
    360360         
    361         conf = cherrypy.request.toolmaps['tools'].get("xmlrpc", {}) 
     361        conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {}) 
    362362        _xmlrpc.respond(body, 
    363363                        conf.get('encoding', 'utf-8'), 
    364364                        conf.get('allow_none', 0)) 
    365         return cherrypy.response.body 
     365        return cherrypy.serving.response.body 
    366366    default.exposed = True 
    367367 
     
    379379     
    380380    def _wrapper(self, invalid_methods=("POST", "PUT", "DELETE"), **kwargs): 
    381         request = cherrypy.request 
     381        request = cherrypy.serving.request 
    382382         
    383383        if not hasattr(cherrypy, "_cache"): 
     
    403403         
    404404        p = conf.pop("priority", None) 
    405         cherrypy.request.hooks.attach('before_handler', self._wrapper, 
    406                                       priority=p, **conf) 
     405        cherrypy.serving.request.hooks.attach('before_handler', self._wrapper, 
     406                                              priority=p, **conf) 
    407407 
    408408 
     
    428428    def __enter__(self): 
    429429        """Populate request.toolmaps from tools specified in config.""" 
    430         cherrypy.request.toolmaps[self.namespace] = map = {} 
     430        cherrypy.serving.request.toolmaps[self.namespace] = map = {} 
    431431        def populate(k, v): 
    432432            toolname, arg = k.split(".", 1) 
     
    437437    def __exit__(self, exc_type, exc_val, exc_tb): 
    438438        """Run tool._setup() for each tool in our toolmap.""" 
    439         map = cherrypy.request.toolmaps.get(self.namespace) 
     439        map = cherrypy.serving.request.toolmaps.get(self.namespace) 
    440440        if map: 
    441441            for name, settings in map.items(): 
  • branches/python3/cherrypy/_cptree.py

    r2335 r2461  
    8181        if self._script_name is None: 
    8282            # None signals that the script name should be pulled from WSGI environ. 
    83             return cherrypy.request.wsgi_environ['SCRIPT_NAME'].rstrip("/") 
     83            return cherrypy.serving.request.wsgi_environ['SCRIPT_NAME'].rstrip("/") 
    8484        return self._script_name 
    8585    def _set_script_name(self, value): 
     
    210210        if path is None: 
    211211            try: 
    212                 path = httputil.urljoin(cherrypy.request.script_name, 
    213                                         cherrypy.request.path_info) 
     212                request = cherrypy.serving.request 
     213                path = httputil.urljoin(request.script_name, 
     214                                        request.path_info) 
    214215            except AttributeError: 
    215216                return None 
  • branches/python3/cherrypy/lib/auth.py

    r2156 r2461  
    55def check_auth(users, encrypt=None, realm=None): 
    66    """If an authorization header contains credentials, return True, else False.""" 
    7     if 'authorization' in cherrypy.request.headers: 
     7    request = cherrypy.serving.request 
     8    if 'authorization' in request.headers: 
    89        # make sure the provided credentials are correctly set 
    9         ah = httpauth.parseAuthorization(cherrypy.request.headers['authorization']) 
     10        ah = httpauth.parseAuthorization(request.headers['authorization']) 
    1011        if ah is None: 
    1112            raise cherrypy.HTTPError(400, 'Bad Request') 
     
    1819                # backward compatibility 
    1920                users = users() # expect it to return a dictionary 
    20  
     21                 
    2122                if not isinstance(users, dict): 
    2223                    raise ValueError("Authentication users must be a dictionary") 
     
    3637        # validate the authorization by re-computing it here 
    3738        # and compare it with what the user-agent provided 
    38         if httpauth.checkResponse(ah, password, method=cherrypy.request.method, 
     39        if httpauth.checkResponse(ah, password, method=request.method, 
    3940                                  encrypt=encrypt, realm=realm): 
    40             cherrypy.request.login = ah["username"] 
     41            request.login = ah["username"] 
    4142            return True 
    42      
    43         cherrypy.request.login = False 
     43         
     44        request.login = False 
    4445    return False 
    4546 
     
    5657     
    5758    # inform the user-agent this path is protected 
    58     cherrypy.response.headers['www-authenticate'] = httpauth.basicAuth(realm) 
     59    cherrypy.serving.response.headers['www-authenticate'] = httpauth.basicAuth(realm) 
    5960     
    6061    raise cherrypy.HTTPError(401, "You are not authorized to access that resource")  
     
    7071     
    7172    # inform the user-agent this path is protected 
    72     cherrypy.response.headers['www-authenticate'] = httpauth.digestAuth(realm) 
     73    cherrypy.serving.response.headers['www-authenticate'] = httpauth.digestAuth(realm) 
    7374     
    7475    raise cherrypy.HTTPError(401, "You are not authorized to access that resource")  
  • branches/python3/cherrypy/lib/auth_basic.py

    r2353 r2461  
    6060        returns True, else it returns False. 
    6161    """ 
    62  
     62     
    6363    if '"' in realm: 
    6464        raise ValueError('Realm cannot contain the " (quote) character.') 
    65  
    66     auth_header = cherrypy.request.headers.get('authorization') 
     65    request = cherrypy.serving.request 
     66     
     67    auth_header = request.headers.get('authorization') 
    6768    if auth_header is not None: 
    6869        try: 
     
    7475                username, password = username_password.decode("ISO-8859-1").split(':', 1) 
    7576                if checkpassword(realm, username, password): 
    76                     cherrypy.request.login = username 
     77                    request.login = username 
    7778                    return # successful authentication 
    7879        except (ValueError, binascii.Error): # split() error, base64.decodestring() error 
    7980            raise cherrypy.HTTPError(400, 'Bad Request') 
    80  
     81     
    8182    # Respond with 401 status and a WWW-Authenticate header 
    82     cherrypy.response.headers['www-authenticate'] = 'Basic realm="%s"' % realm 
     83    cherrypy.serving.response.headers['www-authenticate'] = 'Basic realm="%s"' % realm 
    8384    raise cherrypy.HTTPError(401, "You are not authorized to access that resource") 
    8485 
  • branches/python3/cherrypy/lib/auth_digest.py

    r2420 r2461  
    308308    Arguments: 
    309309    realm: a string containing the authentication realm. 
    310  
     310     
    311311    get_ha1: a callable which looks up a username in a credentials store 
    312312        and returns the HA1 string, which is defined in the RFC to be 
     
    316316        If username is not found in the credentials store, get_ha1() returns 
    317317        None. 
    318  
     318     
    319319    key: a secret string known only to the server, used in the synthesis of nonces. 
    320320    """ 
    321  
    322     auth_header = cherrypy.request.headers.get('authorization') 
     321    request = cherrypy.serving.request 
     322     
     323    auth_header = request.headers.get('authorization') 
    323324    nonce_is_stale = False 
    324325    if auth_header is not None: 
    325326        try: 
    326             auth = HttpDigestAuthorization(auth_header, cherrypy.request.method, debug=debug) 
     327            auth = HttpDigestAuthorization(auth_header, request.method, debug=debug) 
    327328        except ValueError as e: 
    328329            raise cherrypy.HTTPError(400, 'Bad Request: %s' % e) 
    329  
     330         
    330331        if debug: 
    331332            TRACE(str(auth)) 
    332  
     333         
    333334        if auth.validate_nonce(realm, key): 
    334335            ha1 = get_ha1(realm, auth.username) 
     
    336337                # note that for request.body to be available we need to hook in at 
    337338                # before_handler, not on_start_resource like 3.1.x digest_auth does. 
    338                 digest = auth.request_digest(ha1, entity_body=cherrypy.request.body) 
     339                digest = auth.request_digest(ha1, entity_body=request.body) 
    339340                if digest == auth.response: # authenticated 
    340341                    if debug: 
     
    344345                    nonce_is_stale = auth.is_nonce_stale(max_age_seconds=600) 
    345346                    if not nonce_is_stale: 
    346                         cherrypy.request.login = auth.username 
     347                        request.login = auth.username 
    347348                        if debug: 
    348349                            TRACE("authentication of %s successful" % auth.username) 
    349350                        return 
    350  
     351     
    351352    # Respond with 401 status and a WWW-Authenticate header 
    352353    header = www_authenticate(realm, key, stale=nonce_is_stale) 
    353354    if debug: 
    354355        TRACE(header) 
    355     cherrypy.response.headers['WWW-Authenticate'] = header 
     356    cherrypy.serving.response.headers['WWW-Authenticate'] = header 
    356357    raise cherrypy.HTTPError(401, "You are not authorized to access that resource") 
    357358 
  • branches/python3/cherrypy/lib/caching.py

    r2455 r2461  
    124124     
    125125    def key(self): 
    126         request = cherrypy.request 
     126        request = cherrypy.serving.request 
    127127        try: 
    128             response = cherrypy.response 
     128            response = cherrypy.serving.response 
    129129        except AttributeError: 
    130130            response = None 
     
    172172            if (obj_size < self.maxobj_size and total_size < self.maxsize): 
    173173                # add to the expirations list and cache 
    174                 expiration_time = cherrypy.response.time + self.delay 
     174                expiration_time = cherrypy.serving.response.time + self.delay 
    175175                obj_key = self.key() 
    176176                bucket = self.expirations.setdefault(expiration_time, []) 
     
    207207        * returns False 
    208208    """ 
    209     request = cherrypy.request 
     209    request = cherrypy.serving.request 
     210    response = cherrypy.serving.response 
    210211     
    211212    # POST, PUT, DELETE should invalidate (delete) the cached copy. 
     
    221222    request.cacheable = not c 
    222223    if c: 
    223         response = cherrypy.response 
    224224        s, h, b, create_time, original_req_headers = cache_data 
    225225         
     
    260260            # save the cache data 
    261261            body = b''.join(output) 
    262             vary = [he.value for he in 
    263                     cherrypy.response.headers.elements('Vary')] 
     262            vary = [he.value for he in response.headers.elements('Vary')] 
    264263            sel_headers = dict([(k, v) for k, v 
    265                                 in cherrypy.request.headers.items() 
     264                                in cherrypy.serving.request.headers.items() 
    266265                                if k in vary]) 
    267266            cherrypy._cache.put((response.status, response.headers or {}, 
    268267                                 body, response.time, sel_headers)) 
    269268     
    270     response = cherrypy.response 
     269    response = cherrypy.serving.response 
    271270    response.body = tee(response.body) 
    272271 
     
    289288    """ 
    290289     
    291     response = cherrypy.response 
     290    response = cherrypy.serving.response 
    292291    headers = response.headers 
    293292     
     
    307306            if force or "Pragma" not in headers: 
    308307                headers["Pragma"] = "no-cache" 
    309             if cherrypy.request.protocol >= (1, 1): 
     308            if cherrypy.serving.request.protocol >= (1, 1): 
    310309                if force or "Cache-Control" not in headers: 
    311310                    headers["Cache-Control"] = "no-cache, must-revalidate" 
  • branches/python3/cherrypy/lib/cptools.py

    r2412 r2461  
    3131    See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 
    3232    """ 
    33     response = cherrypy.response 
     33    response = cherrypy.serving.response 
    3434     
    3535    # Guard against being run twice. 
     
    5454    # MUST be ignored." 
    5555    if status >= 200 and status <= 299: 
    56         request = cherrypy.request 
     56        request = cherrypy.serving.request 
    5757         
    5858        conditions = request.headers.elements('If-Match') or [] 
     
    7777    will be performed. 
    7878    """ 
    79     response = cherrypy.response 
     79    response = cherrypy.serving.response 
    8080    lastmod = response.headers.get('Last-Modified') 
    8181    if lastmod: 
    8282        status, reason, msg = _httputil.valid_status(response.status) 
    8383         
    84         request = cherrypy.request 
     84        request = cherrypy.serving.request 
    8585         
    8686        since = request.headers.get('If-Unmodified-Since') 
     
    118118    """ 
    119119     
    120     request = cherrypy.request 
     120    request = cherrypy.serving.request 
    121121     
    122122    if scheme: 
     
    134134        base = request.headers.get(local, base) 
    135135    if not base: 
    136         port = cherrypy.request.local.port 
     136        port = request.local.port 
    137137        if port == 80: 
    138138            base = '127.0.0.1' 
     
    162162    headers, and will doubly-truncate the response. 
    163163    """ 
    164     request = cherrypy.request 
     164    request = cherrypy.serving.request 
    165165    for name in headers: 
    166166        if name in request.headers: 
     
    171171    """Set headers on the response.""" 
    172172    for name, value in (headers or []): 
    173         cherrypy.response.headers[name] = value 
     173        cherrypy.serving.response.headers[name] = value 
    174174response_headers.failsafe = True 
    175175 
     
    187187    """ 
    188188    try: 
    189         match = bool(re.match(pattern, cherrypy.request.headers['Referer'])) 
     189        match = bool(re.match(pattern, cherrypy.serving.request.headers['Referer'])) 
    190190        if accept == match: 
    191191            return 
     
    232232    def do_login(self, username, password, from_page='..', **kwargs): 
    233233        """Login. May raise redirect, or return True if request handled.""" 
     234        response = cherrypy.serving.response 
    234235        error_msg = self.check_username_and_password(username, password) 
    235236        if error_msg: 
    236237            body = self.login_screen(from_page, username, error_msg) 
    237             cherrypy.response.body = body 
    238             if "Content-Length" in cherrypy.response.headers: 
     238            response.body = body 
     239            if "Content-Length" in response.headers: 
    239240                # Delete Content-Length header so finalize() recalcs it. 
    240                 del cherrypy.response.headers["Content-Length"] 
     241                del response.headers["Content-Length"] 
    241242            return True 
    242243        else: 
    243             cherrypy.session[self.session_key] = cherrypy.request.login = username 
     244            cherrypy.serving.request.login = username 
     245            cherrypy.session[self.session_key] = username 
    244246            self.on_login(username) 
    245247            raise cherrypy.HTTPRedirect(from_page or "/") 
     
    251253        sess[self.session_key] = None 
    252254        if username: 
    253             cherrypy.request.login = None 
     255            cherrypy.serving.request.login = None 
    254256            self.on_logout(username) 
    255257        raise cherrypy.HTTPRedirect(from_page) 
     
    258260        """Assert username. May raise redirect, or return True if request handled.""" 
    259261        sess = cherrypy.session 
    260         request = cherrypy.request 
     262        request = cherrypy.serving.request 
     263        response = cherrypy.serving.response 
    261264         
    262265        username = sess.get(self.session_key) 
     
    264267            sess[self.session_key] = username = self.anonymous() 
    265268        if not username: 
    266             cherrypy.response.body = self.login_screen(cherrypy.url(qs=request.query_string)) 
    267             if "Content-Length" in cherrypy.response.headers: 
     269            response.body = self.login_screen(cherrypy.url(qs=request.query_string)) 
     270            if "Content-Length" in response.headers: 
    268271                # Delete Content-Length header so finalize() recalcs it. 
    269                 del cherrypy.response.headers["Content-Length"] 
     272                del response.headers["Content-Length"] 
    270273            return True 
    271         cherrypy.request.login = username 
     274        request.login = username 
    272275        self.on_check(username) 
    273276     
    274277    def run(self): 
    275         request = cherrypy.request 
     278        request = cherrypy.serving.request 
     279        response = cherrypy.serving.response 
     280         
    276281        path = request.path_info 
    277282        if path.endswith('login_screen'): 
     
    279284        elif path.endswith('do_login'): 
    280285            if request.method != 'POST': 
    281                 cherrypy.response.headers['Allow'] = "POST" 
     286                response.headers['Allow'] = "POST" 
    282287                raise cherrypy.HTTPError(405) 
    283288            return self.do_login(**request.params) 
    284289        elif path.endswith('do_logout'): 
    285290            if request.method != 'POST': 
    286                 cherrypy.response.headers['Allow'] = "POST" 
     291                response.headers['Allow'] = "POST" 
    287292                raise cherrypy.HTTPError(405) 
    288293            return self.do_logout(**request.params) 
     
    311316def log_request_headers(): 
    312317    """Write request headers to the cherrypy error log.""" 
    313     h = ["  %s: %s" % (k, v) for k, v in cherrypy.request.header_list] 
     318    h = ["  %s: %s" % (k, v) for k, v in cherrypy.serving.request.header_list] 
    314319    cherrypy.log('\nRequest Headers:\n' + '\n'.join(h), "HTTP") 
    315320 
    316321def log_hooks(): 
    317322    """Write request.hooks to the cherrypy error log.""" 
     323    request = cherrypy.serving.request 
     324     
    318325    msg = [] 
    319326    # Sort by the standard points if possible. 
    320327    from cherrypy import _cprequest 
    321328    points = _cprequest.hookpoints 
    322     for k in cherrypy.request.hooks.keys(): 
     329    for k in request.hooks.keys(): 
    323330        if k not in points: 
    324331            points.append(k) 
     
    326333    for k in points: 
    327334        msg.append("    %s:" % k) 
    328         v = cherrypy.request.hooks.get(k, []) 
     335        v = request.hooks.get(k, []) 
    329336        v.sort() 
    330337        for h in v: 
     
    342349def trailing_slash(missing=True, extra=False, status=None): 
    343350    """Redirect if path_info has (missing|extra) trailing slash.""" 
    344     request = cherrypy.request 
     351    request = cherrypy.serving.request 
    345352    pi = request.path_info 
    346353     
     
    371378                for y in flattener(x): 
    372379                    yield y  
    373     response = cherrypy.response 
     380    response = cherrypy.serving.response 
    374381    response.body = flattener(response.body) 
    375382 
     
    403410    if isinstance(media, str): 
    404411        media = [media] 
     412    request = cherrypy.serving.request 
    405413     
    406414    # Parse the Accept request header, and try to match one 
    407415    # of the requested media-ranges (in order of preference). 
    408     ranges = cherrypy.request.headers.elements('Accept') 
     416    ranges = request.headers.elements('Accept') 
    409417    if not ranges: 
    410418        # Any media type is acceptable. 
     
    429437     
    430438    # No suitable media-range found. 
    431     ah = cherrypy.request.headers.get('Accept') 
     439    ah = request.headers.get('Accept') 
    432440    if ah is None: 
    433441        msg = "Your client did not send an Accept header." 
     
    459467def autovary(ignore=None): 
    460468    """Auto-populate the Vary response header based on request.header access.""" 
    461     req_h = cherrypy.request.headers 
    462     cherrypy.request.headers = MonitoredHeaderMap() 
    463     cherrypy.request.headers.update(req_h) 
     469    request = cherrypy.serving.request 
     470     
     471    req_h = request.headers 
     472    request.headers = MonitoredHeaderMap() 
     473    request.headers.update(req_h) 
    464474    if ignore is None: 
    465475        ignore = set(['Content-Disposition', 'Content-Length', 'Content-Type']) 
    466476     
    467477    def set_response_header(): 
    468         resp_h = cherrypy.response.headers 
     478        resp_h = cherrypy.serving.response.headers 
    469479        v = set([e.value for e in resp_h.elements('Vary')]) 
    470         v = v.union(cherrypy.request.headers.accessed_headers) 
     480        v = v.union(request.headers.accessed_headers) 
    471481        v = v.difference(ignore) 
    472482        v = list(v) 
    473483        v.sort() 
    474484        resp_h['Vary'] = ', '.join(v) 
    475     cherrypy.request.hooks.attach( 
     485    request.hooks.attach( 
    476486        'before_finalize', set_response_header, 95) 
    477487 
    478488 
     489 
  • branches/python3/cherrypy/lib/encoding.py

    r2438 r2461  
    2222         
    2323        self.attempted_charsets = set() 
    24          
    25         if cherrypy.request.handler is not None: 
     24        request = cherrypy.serving.request 
     25        if request.handler is not None: 
    2626            # Replace request.handler with self 
    27             self.oldhandler = cherrypy.request.handler 
    28             cherrypy.request.handler = self 
     27            self.oldhandler = request.handler 
     28            request.handler = self 
    2929     
    3030    def encode_stream(self, encoding): 
     
    6565     
    6666    def find_acceptable_charset(self): 
    67         response = cherrypy.response 
    68          
    69         if cherrypy.response.stream: 
     67        request = cherrypy.serving.request 
     68        response = cherrypy.serving.response 
     69         
     70        if response.stream: 
    7071            encoder = self.encode_stream 
    7172        else: 
     
    8687        # Parse the Accept-Charset request header, and try to provide one 
    8788        # of the requested charsets (in order of user preference). 
    88         encs = cherrypy.request.headers.elements('Accept-Charset') 
     89        encs = request.headers.elements('Accept-Charset') 
    8990        charsets = [enc.value.lower() for enc in encs] 
    9091         
     
    125126         
    126127        # No suitable encoding found. 
    127         ac = cherrypy.request.headers.get('Accept-Charset') 
     128        ac = request.headers.get('Accept-Charset') 
    128129        if ac is None: 
    129130            msg = "Your client did not send an Accept-Charset header." 
     
    134135     
    135136    def __call__(self, *args, **kwargs): 
     137        response = cherrypy.serving.response 
    136138        self.body = self.oldhandler(*args, **kwargs) 
    137139         
     
    150152            self.body = [] 
    151153         
    152         ct = cherrypy.response.headers.elements("Content-Type") 
     154        ct = response.headers.elements("Content-Type") 
    153155        if ct: 
    154156            ct = ct[0] 
     
    157159                ct.params['charset'] = self.find_acceptable_charset() 
    158160                if self.add_charset: 
    159                     cherrypy.response.headers["Content-Type"] = str(ct) 
     161                    response.headers["Content-Type"] = str(ct) 
    160162         
    161163        return self.body 
     
    216218        * The 'identity' value is given with a qvalue > 0. 
    217219    """ 
    218     response = cherrypy.response 
     220    request = cherrypy.serving.request 
     221    response = cherrypy.serving.response 
    219222     
    220223    set_vary_header(response, "Accept-Encoding") 
     
    226229    # If returning cached content (which should already have been gzipped), 
    227230    # don't re-zip. 
    228     if getattr(cherrypy.request, "cached", False): 
     231    if getattr(request, "cached", False): 
    229232        return 
    230233     
    231     acceptable = cherrypy.request.headers.elements('Accept-Encoding') 
     234    acceptable = request.headers.elements('Accept-Encoding') 
    232235    if not acceptable: 
    233236        # If no Accept-Encoding field is present in a request, 
  • branches/python3/cherrypy/lib/jsontools.py

    r2388 r2461  
    88 
    99def json_in(*args, **kwargs): 
    10     request = cherrypy.request 
     10    request = cherrypy.serving.request 
    1111    _h = request.headers 
    1212    if ('Content-Type' not in _h 
     
    2525 
    2626def json_out(*args, **kwargs): 
    27     request = cherrypy.request 
    28     response = cherrypy.response 
     27    request = cherrypy.serving.request 
     28    response = cherrypy.serving.response 
    2929 
    3030    real_handler = request.handler 
  • branches/python3/cherrypy/lib/sessions.py

    r2441 r2461  
    562562    if not hasattr(cherrypy.serving, "session"): 
    563563        return 
     564    request = cherrypy.serving.request 
     565    response = cherrypy.serving.response 
    564566     
    565567    # Guard against running twice 
    566     if hasattr(cherrypy.request, "_sessionsaved"): 
     568    if hasattr(request, "_sessionsaved"): 
    567569        return 
    568     cherrypy.request._sessionsaved = True 
    569      
    570     if cherrypy.response.stream: 
     570    request._sessionsaved = True 
     571     
     572    if response.stream: 
    571573        # If the body is being streamed, we have to save the data 
    572574        #   *after* the response has been written out 
    573         cherrypy.request.hooks.attach('on_end_request', cherrypy.session.save) 
     575        request.hooks.attach('on_end_request', cherrypy.session.save) 
    574576    else: 
    575577        # If the body is not being streamed, we save the data now 
    576578        # (so we can release the lock). 
    577         if isinstance(cherrypy.response.body, types.GeneratorType): 
    578             cherrypy.response.collapse_body() 
     579        if isinstance(response.body, types.GeneratorType): 
     580            response.collapse_body() 
    579581        cherrypy.session.save() 
    580582save.failsafe = True 
     
    619621    """ 
    620622     
    621     request = cherrypy.request 
     623    request = cherrypy.serving.request 
    622624     
    623625    # Guard against running twice 
     
    646648    def update_cookie(id): 
    647649        """Update the cookie every time the session id changes.""" 
    648         cherrypy.response.cookie[name] = id 
     650        cherrypy.serving.response.cookie[name] = id 
    649651    sess.id_observers.append(update_cookie) 
    650652     
     
    679681    """ 
    680682    # Set response cookie 
    681     cookie = cherrypy.response.cookie 
     683    cookie = cherrypy.serving.response.cookie 
    682684    cookie[name] = cherrypy.serving.session.id 
    683     cookie[name]['path'] = (path or cherrypy.request.headers.get(path_header) 
     685    cookie[name]['path'] = (path or cherrypy.serving.request.headers.get(path_header) 
    684686                            or '/') 
    685687     
     
    700702def expire(): 
    701703    """Expire the current session cookie.""" 
    702     name = cherrypy.request.config.get('tools.sessions.name', 'session_id') 
     704    name = cherrypy.serving.request.config.get('tools.sessions.name', 'session_id') 
    703705    one_year = 60 * 60 * 24 * 365 
    704706    e = time.time() - one_year 
    705     cherrypy.response.cookie[name]['expires'] = httputil.HTTPDate(e) 
    706  
    707  
     707    cherrypy.serving.response.cookie[name]['expires'] = httputil.HTTPDate(e) 
     708 
     709 
  • branches/python3/cherrypy/lib/static.py

    r2420 r2461  
    3131    """ 
    3232     
    33     response = cherrypy.response 
     33    response = cherrypy.serving.response 
    3434     
    3535    # If path is relative, users should fix it by making path absolute. 
     
    8787    not be set. If disposition is None, no Content-Disposition header will 
    8888    be written. 
    89     """ 
    90      
    91     response = cherrypy.response 
     89 
     90    CAUTION: If the request contains a 'Range' header, one or more seek()s will 
     91    be performed on the file object.  This may cause undesired behavior if 
     92    the file object is not seekable.  It could also produce undesired results 
     93    if the caller set the read position of the file object prior to calling 
     94    serve_fileobj(), expecting that the data would be served starting from that 
     95    position. 
     96    """ 
     97     
     98    response = cherrypy.serving.response 
    9299     
    93100    try: 
     
    116123def _serve_fileobj(fileobj, content_type, content_length): 
    117124    """Internal. Set response.body to the given file object, perhaps ranged.""" 
    118     response = cherrypy.response 
     125    response = cherrypy.serving.response 
    119126     
    120127    # HTTP/1.0 didn't have Range/Accept-Ranges headers, or the 206 code 
    121     if cherrypy.request.protocol >= (1, 1): 
     128    request = cherrypy.serving.request 
     129    if request.protocol >= (1, 1): 
    122130        response.headers["Accept-Ranges"] = "bytes" 
    123         r = httputil.get_ranges(cherrypy.request.headers.get('Range'), 
    124                                 content_length) 
     131        r = httputil.get_ranges(request.headers.get('Range'), content_length) 
    125132        if r == []: 
    126133            response.headers['Content-Range'] = "bytes */%s" % content_length 
     
    216223    'index.html', the file '/home/me/myapp/index.html' will be sought. 
    217224    """ 
    218     if cherrypy.request.method not in ('GET', 'HEAD'): 
    219         return False 
    220      
    221     if match and not re.search(match, cherrypy.request.path_info): 
     225    request = cherrypy.serving.request 
     226    if request.method not in ('GET', 'HEAD'): 
     227        return False 
     228     
     229    if match and not re.search(match, request.path_info): 
    222230        return False 
    223231     
     
    237245        section = "/" 
    238246    section = section.rstrip(r"\/") 
    239     branch = cherrypy.request.path_info[len(section) + 1:] 
     247    branch = request.path_info[len(section) + 1:] 
    240248    branch = unquote(branch.lstrip(r"\/")) 
    241249     
     
    243251    filename = os.path.join(dir, branch) 
    244252    cherrypy.log('Checking file %r to fulfill %r' % 
    245                  (filename, cherrypy.request.path_info), 
     253                 (filename, request.path_info), 
    246254                 context='tools.staticdir', severity=logging.DEBUG) 
    247255     
     
    258266            handled = _attempt(os.path.join(filename, index), content_types) 
    259267            if handled: 
    260                 cherrypy.request.is_index = filename[-1] in (r"\/") 
     268                request.is_index = filename[-1] in (r"\/") 
    261269    return handled 
    262270 
     
    272280    out in the Content-Type response header (e.g. "image/gif"). 
    273281    """ 
    274     if cherrypy.request.method not in ('GET', 'HEAD'): 
    275         return False 
    276      
    277     if match and not re.search(match, cherrypy.request.path_info): 
     282    request = cherrypy.serving.request 
     283    if request.method not in ('GET', 'HEAD'): 
     284        return False 
     285     
     286    if match and not re.search(match, request.path_info): 
    278287        return False 
    279288     
  • branches/python3/cherrypy/process/wspbus.py

    r2401 r2461  
    218218            self.log("Shutting down due to error in start listener:", 
    219219                     level=40, traceback=True) 
    220             e_info = sys.exc_info() 
    221220            try: 
    222221                self.exit() 
  • branches/python3/cherrypy/test/benchmark.py

    r2438 r2461  
    188188     
    189189    parse_patterns = [('complete_requests', 'Completed', 
    190                        r'^Complete requests:\s*(\d+)'), 
     190                       br'^Complete requests:\s*(\d+)'), 
    191191                      ('failed_requests', 'Failed', 
    192                        r'^Failed requests:\s*(\d+)'), 
     192                       br'^Failed requests:\s*(\d+)'), 
    193193                      ('requests_per_second', 'req/sec', 
    194                        r'^Requests per second:\s*([0-9.]+)'), 
     194                       br'^Requests per second:\s*([0-9.]+)'), 
    195195                      ('time_per_request_concurrent', 'msec/req', 
    196                        r'^Time per request:\s*([0-9.]+).*concurrent requests\)$'), 
     196                       br'^Time per request:\s*([0-9.]+).*concurrent requests\)$'), 
    197197                      ('transfer_rate', 'KB/sec', 
    198                        r'^Transfer rate:\s*([0-9.]+)'), 
     198                       br'^Transfer rate:\s*([0-9.]+)'), 
    199199                      ] 
    200200     
     
    247247        row = [c] 
    248248        for attr in attrs: 
    249             val = getattr(sess, attr
     249            val = float(getattr(sess, attr)
    250250            avg[attr] += float(val) 
    251251            row.append(val) 
     
    378378                print("\nUsing null Request object") 
    379379            try: 
    380                 run_standard_benchmarks() 
     380                try: 
     381                    run_standard_benchmarks() 
     382                except: 
     383                    print(_cperror.format_exc()) 
     384                    raise 
    381385            finally: 
    382386                cherrypy.engine.exit() 
  • branches/python3/cherrypy/test/test.py

    r2438 r2461  
    153153                warnings.warn("Error importing wsgiconq. pyconquer will not run.") 
    154154            else: 
    155                 app = wsgiconq.WSGILogger(app
     155                app = wsgiconq.WSGILogger(app, c_calls=True
    156156        if self.validate: 
    157157            try: 
  • branches/python3/cherrypy/test/test_dynamicobjectmapping.py

    r2274 r2461  
    44 
    55import cherrypy 
    6  
    76 
    87script_names = ["", "/foo", "/users/fred/blog", "/corp/blog"] 

Hosted by WebFaction

Log in as guest/cpguest to create tickets