Commits

Robert Brewer  committed b6291ef

trunk: more syntax syncs with python3, including a couple bugfixes that were done in the python3 branch

  • Participants
  • Parent commits 6ad6c19

Comments (0)

Files changed (8)

File cherrypy/__init__.py

         
         newdoc = [cls.__doc__ or ""]
         
-        dctnames = dct.keys()
-        dctnames.sort()
-        
-        for name in dctnames:
+        for name in sorted(dct.keys()):
             if name.endswith("__doc"):
                 # Remove the magic doc attribute.
                 if hasattr(cls, name):
         cls.__doc__ = "\n\n".join(newdoc)
 
 
+from cherrypy.py3util import sorted
 from cherrypy._cperror import HTTPError, HTTPRedirect, InternalRedirect
 from cherrypy._cperror import NotFound, CherryPyException, TimeoutError
 

File cherrypy/_cpchecker.py

     global_config_contained_paths = False
     
     def check_app_config_entries_dont_start_with_script_name(self):
-        for sn, app in cherrypy.tree.apps.iteritems():
+        for sn, app in cherrypy.tree.apps.items():
             if not isinstance(app, cherrypy.Application):
                 continue
             if not app.config:
                 warnings.warn(os.linesep.join(msg))
     
     def check_skipped_app_config(self):
-        for sn, app in cherrypy.tree.apps.iteritems():
+        for sn, app in cherrypy.tree.apps.items():
             if not isinstance(app, cherrypy.Application):
                 continue
             if not app.config:
                 return
     
     def check_app_config_brackets(self):
-        for sn, app in cherrypy.tree.apps.iteritems():
+        for sn, app in cherrypy.tree.apps.items():
             if not isinstance(app, cherrypy.Application):
                 continue
             if not app.config:
     def check_static_paths(self):
         # Use the dummy Request object in the main thread.
         request = cherrypy.request
-        for sn, app in cherrypy.tree.apps.iteritems():
+        for sn, app in cherrypy.tree.apps.items():
             if not isinstance(app, cherrypy.Application):
                 continue
             request.app = app
     
     def _compat(self, config):
         """Process config and warn on each obsolete or deprecated entry."""
-        for section, conf in config.iteritems():
+        for section, conf in config.items():
             if isinstance(conf, dict):
-                for k, v in conf.iteritems():
+                for k, v in conf.items():
                     if k in self.obsolete:
                         warnings.warn("%r is obsolete. Use %r instead.\n"
                                       "section: [%s]" %
     def check_compatibility(self):
         """Process config and warn on each obsolete or deprecated entry."""
         self._compat(cherrypy.config)
-        for sn, app in cherrypy.tree.apps.iteritems():
+        for sn, app in cherrypy.tree.apps.items():
             if not isinstance(app, cherrypy.Application):
                 continue
             self._compat(app.config)
         ns.extend(cherrypy.config.namespaces.keys())
         ns += self.extra_config_namespaces
         
-        for section, conf in app.config.iteritems():
+        for section, conf in app.config.items():
             is_path_section = section.startswith("/")
             if is_path_section and isinstance(conf, dict):
-                for k, v in conf.iteritems():
+                for k, v in conf.items():
                     atoms = k.split(".")
                     if len(atoms) > 1:
                         if atoms[0] not in ns:
     
     def check_config_namespaces(self):
         """Process config and warn on each unknown config namespace."""
-        for sn, app in cherrypy.tree.apps.iteritems():
+        for sn, app in cherrypy.tree.apps.items():
             if not isinstance(app, cherrypy.Application):
                 continue
             self._known_ns(app)
     known_config_types = {}
     
     def _populate_known_types(self):
-        import __builtin__
-        builtins = [x for x in vars(__builtin__).values()
-                    if type(x) is type(str)]
+        import __builtin__ as builtins
+        b = [x for x in vars(builtins).values()
+             if type(x) is type(str)]
         
         def traverse(obj, namespace):
             for name in dir(obj):
                 if name == 'body_params':
                     continue
                 vtype = type(getattr(obj, name, None))
-                if vtype in builtins:
+                if vtype in b:
                     self.known_config_types[namespace + "." + name] = vtype
         
         traverse(cherrypy.request, "request")
         msg = ("The config entry %r in section %r is of type %r, "
                "which does not match the expected type %r.")
         
-        for section, conf in config.iteritems():
+        for section, conf in config.items():
             if isinstance(conf, dict):
-                for k, v in conf.iteritems():
+                for k, v in conf.items():
                     if v is not None:
                         expected_type = self.known_config_types.get(k, None)
                         vtype = type(v)
     def check_config_types(self):
         """Assert that config values are of the same type as default values."""
         self._known_types(cherrypy.config)
-        for sn, app in cherrypy.tree.apps.iteritems():
+        for sn, app in cherrypy.tree.apps.items():
             if not isinstance(app, cherrypy.Application):
                 continue
             self._known_types(app.config)
     
     def check_localhost(self):
         """Warn if any socket_host is 'localhost'. See #711."""
-        for k, v in cherrypy.config.iteritems():
+        for k, v in cherrypy.config.items():
             if k == 'server.socket_host' and v == 'localhost':
                 warnings.warn("The use of 'localhost' as a socket host can "
                     "cause problems on newer systems, since 'localhost' can "

File cherrypy/_cpconfig.py

         cherrypy.engine.autoreload.files.add(other)
     
     # Load other into base
-    for section, value_map in reprconf.as_dict(other).iteritems():
+    for section, value_map in reprconf.as_dict(other).items():
         if not isinstance(value_map, dict):
             raise ValueError(
                 "Application config must include section headers, but the "

File cherrypy/_cpdispatch.py

 
     missing_args = []
     multiple_args = []
-    for key, usage in arg_usage.iteritems():
+    for key, usage in arg_usage.items():
         if usage == 0:
             missing_args.append(key)
         elif usage > 1:
         
         # Try successive objects (reverse order)
         num_candidates = len(object_trail) - 1
-        for i in xrange(num_candidates, -1, -1):
+        for i in range(num_candidates, -1, -1):
             
             name, candidate, nodeconf, curpath = object_trail[i]
             if candidate is None:

File cherrypy/_cperror.py

     Any request.params must be supplied in a query string.
     """
     
-    def __init__(self, path):
+    def __init__(self, path, query_string=""):
         import cherrypy
         request = cherrypy.request
         
-        self.query_string = ""
+        self.query_string = query_string
         if "?" in path:
             # Separate any params included in the path
             path, self.query_string = path.split("?", 1)
         response.status = status = self.status
         
         if status in (300, 301, 302, 303, 307):
-            response.headers['Content-Type'] = "text/html"
+            response.headers['Content-Type'] = "text/html;charset=utf-8"
             # "The ... URI SHOULD be given by the Location field
             # in the response."
             response.headers['Location'] = self.urls[0]
         try:
             self.code, self.reason, defaultmsg = _httputil.valid_status(status)
         except ValueError, x:
-            raise cherrypy.__class__(500, x.args[0])
+            raise self.__class__(500, x.args[0])
         
         if self.code < 400 or self.code > 599:
             raise ValueError("status must be between 400 and 599.")
         tb = None
         if cherrypy.request.show_tracebacks:
             tb = format_exc()
-        response.headers['Content-Type'] = "text/html"
+        response.headers['Content-Type'] = "text/html;charset=utf-8"
         
         content = self.get_error_page(self.status, traceback=tb,
                                       message=self._message)
             if callable(error_page):
                 return error_page(**kwargs)
             else:
-                return file(error_page, 'rb').read() % kwargs
+                return open(error_page, 'rb').read() % kwargs
         except:
             e = _format_exception(*_exc_info())[-1]
             m = kwargs['message']

File cherrypy/_cpreqbody.py

         self.read_lines_to_boundary(fp=fp)
         return fp
 
-
-class Infinity(object):
-    def __cmp__(self, other):
-        return 1
-    def __sub__(self, other):
-        return self
-inf = Infinity()
-
-
+
+class Infinity(object):
+    def __cmp__(self, other):
+        return 1
+    def __sub__(self, other):
+        return self
+inf = Infinity()
+
+
 class SizedReader:
     
     def __init__(self, fp, length, maxbytes, bufsize=8192):
                 request_params[key].append(value)
             else:
                 request_params[key] = value
-

File cherrypy/_cprequest.py

                 % (cls.__module__, cls.__name__, self.callback,
                    self.failsafe, self.priority,
                    ", ".join(['%s=%r' % (k, v)
-                              for k, v in self.kwargs.iteritems()])))
+                              for k, v in self.kwargs.items()])))
 
 
 class HookMap(dict):
         newmap = self.__class__()
         # We can't just use 'update' because we want copies of the
         # mutable values (each is a list) as well.
-        for k, v in self.iteritems():
+        for k, v in self.items():
             newmap[k] = v[:]
         return newmap
     copy = __copy__
         
         return cherrypy.response
     
+    # Uncomment for stage debugging
+    # stage = property(lambda self: self._stage, lambda self, v: print(v))
+    
     def respond(self, path_info):
         """Generate a response for the resource at self.path_info. (Core)"""
         try:

File cherrypy/test/webtest.py

     
     # Trying 10 times is simply in case of socket errors.
     # Normal case--it should run once.
-    for trial in xrange(10):
+    for trial in range(10):
         try:
             # Allow http_conn to be a class or an instance
             if hasattr(http_conn, "host"):