[Checkins] SVN: zope.publisher/branches/py3-attempt2/src/zope/publisher/ Partial python-3 support (work in progress)

Andrey Lebedev cvs-admin at zope.org
Fri Feb 15 17:26:22 UTC 2013


Log message for revision 129440:
  Partial python-3 support (work in progress)
  
  

Changed:
  U   zope.publisher/branches/py3-attempt2/src/zope/publisher/base.py
  U   zope.publisher/branches/py3-attempt2/src/zope/publisher/browser.py
  U   zope.publisher/branches/py3-attempt2/src/zope/publisher/http.py
  U   zope.publisher/branches/py3-attempt2/src/zope/publisher/interfaces/__init__.py
  U   zope.publisher/branches/py3-attempt2/src/zope/publisher/publish.py
  U   zope.publisher/branches/py3-attempt2/src/zope/publisher/testing.py
  U   zope.publisher/branches/py3-attempt2/src/zope/publisher/tests/test_baserequest.py
  U   zope.publisher/branches/py3-attempt2/src/zope/publisher/tests/test_xmlrpcrequest.py

-=-
Modified: zope.publisher/branches/py3-attempt2/src/zope/publisher/base.py
===================================================================
--- zope.publisher/branches/py3-attempt2/src/zope/publisher/base.py	2013-02-15 17:25:45 UTC (rev 129439)
+++ zope.publisher/branches/py3-attempt2/src/zope/publisher/base.py	2013-02-15 17:26:22 UTC (rev 129440)
@@ -16,7 +16,7 @@
 Specifically, 'BaseRequest', 'BaseResponse', and 'DefaultPublication' are
 specified here.
 """
-from cStringIO import StringIO
+from io import BytesIO, StringIO
 
 from zope.interface import implementer
 from zope.interface.common.mapping import IReadMapping, IEnumerableMapping
@@ -50,7 +50,7 @@
 
     def handleException(self, exc_info):
         'See IPublisherResponse'
-        f = StringIO()
+        f = BytesIO()
         print_exception(
             exc_info[0], exc_info[1], exc_info[2], 100, f)
         self.setResult(f.getvalue())
@@ -398,7 +398,7 @@
 
         environ['PATH_INFO'] = path
         if body_instream is None:
-            body_instream = StringIO('')
+            body_instream = BytesIO('')
 
         super(TestRequest, self).__init__(body_instream, environ)
 

Modified: zope.publisher/branches/py3-attempt2/src/zope/publisher/browser.py
===================================================================
--- zope.publisher/branches/py3-attempt2/src/zope/publisher/browser.py	2013-02-15 17:25:45 UTC (rev 129439)
+++ zope.publisher/branches/py3-attempt2/src/zope/publisher/browser.py	2013-02-15 17:26:22 UTC (rev 129440)
@@ -21,7 +21,6 @@
 __docformat__ = 'restructuredtext'
 
 import re
-from types import ListType, TupleType, StringType
 from cgi import FieldStorage
 import tempfile
 
@@ -53,7 +52,7 @@
 from zope.publisher.skinnable import SkinChangedEvent #BBB import
 
 
-__ArrayTypes = (ListType, TupleType)
+__ArrayTypes = (list, tuple)
 
 start_of_header_search=re.compile('(<head[^>]*>)', re.I).search
 base_re_search=re.compile('(<base.*?>)',re.I).search
@@ -89,7 +88,7 @@
 
 def field2int(v):
     if isinstance(v, __ArrayTypes):
-        return map(field2int, v)
+        return list(map(field2int, v))
     v = field2string(v)
     if not v:
         raise ValueError('Empty entry when <strong>integer</strong> expected')
@@ -100,7 +99,7 @@
 
 def field2float(v):
     if isinstance(v, __ArrayTypes):
-        return map(field2float, v)
+        return list(map(field2float, v))
     v = field2string(v)
     if not v:
         raise ValueError(
@@ -113,7 +112,7 @@
 
 def field2long(v):
     if isinstance(v, __ArrayTypes):
-        return map(field2long, v)
+        return list(map(field2long, v))
     v = field2string(v)
 
     # handle trailing 'L' if present.
@@ -122,7 +121,7 @@
     if not v:
         raise ValueError('Empty entry when <strong>integer</strong> expected')
     try:
-        return long(v)
+        return int(v)
     except ValueError:
         raise ValueError("A long integer was expected in the value '%s'" % v)
 
@@ -165,7 +164,7 @@
     type_converters[field_type] = converter
 
 
-isCGI_NAME = {
+isCGI_NAME = lambda key: key in {
     # These fields are placed in request.environ instead of request.form.
     'SERVER_SOFTWARE' : 1,
     'SERVER_NAME' : 1,
@@ -185,12 +184,12 @@
     'CONTENT_TYPE' : 1,
     'CONTENT_LENGTH' : 1,
     'SERVER_URL': 1,
-    }.has_key
+    }
 
-hide_key={
+hide_key=lambda key: key in {
     'HTTP_AUTHORIZATION':1,
     'HTTP_CGI_AUTHORIZATION': 1,
-    }.has_key
+     }
 
 class Record(object):
 
@@ -206,12 +205,12 @@
         return self.__dict__[key]
 
     def __str__(self):
-        items = self.__dict__.items()
+        items = list(self.__dict__.items())
         items.sort()
         return "{" + ", ".join(["%s: %s" % item for item in items]) + "}"
 
     def __repr__(self):
-        items = self.__dict__.items()
+        items = list(self.__dict__.items())
         items.sort()
         return ("{"
             + ", ".join(["%s: %s" % (key, repr(value))
@@ -393,7 +392,7 @@
         if key is not None:
             key = self._decode(key)
 
-        if type(item) == StringType:
+        if type(item) == str:
             item = self._decode(item)
 
         if flags:
@@ -583,7 +582,7 @@
         d.update(self._environ)
         d.update(self._cookies)
         d.update(self.form)
-        return d.keys()
+        return list(d.keys())
 
 
     def get(self, key, default=None):
@@ -661,8 +660,8 @@
         if kw:
             _testEnv.update(kw)
         if body_instream is None:
-            from StringIO import StringIO
-            body_instream = StringIO('')
+            from io import BytesIO
+            body_instream = BytesIO()
 
         super(TestRequest, self).__init__(body_instream, _testEnv)
         if form:

Modified: zope.publisher/branches/py3-attempt2/src/zope/publisher/http.py
===================================================================
--- zope.publisher/branches/py3-attempt2/src/zope/publisher/http.py	2013-02-15 17:25:45 UTC (rev 129439)
+++ zope.publisher/branches/py3-attempt2/src/zope/publisher/http.py	2013-02-15 17:26:22 UTC (rev 129440)
@@ -13,7 +13,8 @@
 ##############################################################################
 """HTTP Publisher
 """
-from cStringIO import StringIO
+import sys
+from io import BytesIO
 from zope.i18n.interfaces import IUserPreferredCharsets
 from zope.i18n.interfaces import IUserPreferredLanguages
 from zope.i18n.locales import locales, LoadLocaleError
@@ -31,18 +32,23 @@
 from zope.publisher.interfaces.http import IResult
 from zope.publisher.interfaces.logginginfo import ILoggingInfo
 from zope.publisher.skinnable import setDefaultSkin
-import Cookie
 import cgi
 import logging
 import tempfile
 import types
-import urllib
-import urlparse
 import zope.component
 import zope.contenttype.parse
 import zope.event
 import zope.interface
 
+PY2 = sys.version_info[0] == 2
+if PY2:
+    import Cookie as cookies
+    from urllib import splitport, quote
+    from urlparse import urlsplit
+else:
+    import http.cookies as cookies
+    from urllib.parse import splitport, quote, urlsplit
 
 # Default Encoding
 ENCODING = 'UTF-8'
@@ -176,7 +182,7 @@
                 return self.__request.getURL(i)
             else:
                 return self.__request.getApplicationURL(i)
-        except IndexError, v:
+        except IndexError as v:
             if v[0] == i:
                 return default
             raise
@@ -195,7 +201,7 @@
         if not size:
             size = environment.get('HTTP_CONTENT_LENGTH')
         if not size or int(size) < 65536:
-            self.cacheStream = StringIO()
+            self.cacheStream = BytesIO()
         else:
             self.cacheStream = tempfile.TemporaryFile()
         self.size = size and int(size) or -1
@@ -352,7 +358,7 @@
         script = get_env('SCRIPT_NAME', '').strip()
 
         # _script and the other _names are meant for URL construction
-        self._app_names = filter(None, script.split('/'))
+        self._app_names = [f for f in script.split('/') if f]
 
         # get server URL and store it too, since we are already looking it up
         server_url = get_env('SERVER_URL', None)
@@ -381,7 +387,7 @@
 
         if environ.has_key('HTTP_HOST'):
             host = environ['HTTP_HOST'].strip()
-            hostname, port = urllib.splitport(host)
+            hostname, port = splitport(host)
         else:
             hostname = environ.get('SERVER_NAME', '').strip()
             port = environ.get('SERVER_PORT', '')
@@ -401,8 +407,8 @@
 
         # ignore cookies on a CookieError
         try:
-            c = Cookie.SimpleCookie(text)
-        except Cookie.CookieError, e:
+            c = cookies.SimpleCookie(text)
+        except cookies.CookieError as e:
             eventlog.warn(e)
             return result
 
@@ -521,8 +527,7 @@
                 raise IndexError(level)
             names = names[:-level]
         # See: http://www.ietf.org/rfc/rfc2718.txt, Section 2.2.5
-        names = [urllib.quote(name.encode("utf-8"), safe='/+@')
-                 for name in names]
+        names = [quote(name.encode("utf-8"), safe='/+@') for name in names]
 
         if path_only:
             if not names:
@@ -544,8 +549,7 @@
             names = self._app_names
 
         # See: http://www.ietf.org/rfc/rfc2718.txt, Section 2.2.5
-        names = [urllib.quote(name.encode("utf-8"), safe='/+@')
-                 for name in names]
+        names = [quote(name.encode("utf-8"), safe='/+@') for name in names]
 
         if path_only:
             return names and ('/' + '/'.join(names)) or '/'
@@ -900,8 +904,8 @@
 
     def _cookie_list(self):
         try:
-            c = Cookie.SimpleCookie()
-        except Cookie.CookieError, e:
+            c = cookies.SimpleCookie()
+        except cookies.CookieError as e:
             eventlog.warn(e)
             return []
         for name, attrs in self._cookies.items():
@@ -918,7 +922,7 @@
                     k = 'max-age'
                 elif k == 'comment':
                     # Encode rather than throw an exception
-                    v = urllib.quote(v.encode('utf-8'), safe="/?:@&+")
+                    v = quote(v.encode('utf-8'), safe="/?:@&+")
                 c[name][k] = str(v)
         return str(c).splitlines()
 
@@ -938,7 +942,7 @@
 
 
 def extract_host(url):
-    scheme, host, path, query, fragment = urlparse.urlsplit(url)
+    scheme, host, path, query, fragment = urlsplit(url)
     if ':' not in host:
         port = DEFAULT_PORTS.get(scheme)
         if port:

Modified: zope.publisher/branches/py3-attempt2/src/zope/publisher/interfaces/__init__.py
===================================================================
--- zope.publisher/branches/py3-attempt2/src/zope/publisher/interfaces/__init__.py	2013-02-15 17:25:45 UTC (rev 129439)
+++ zope.publisher/branches/py3-attempt2/src/zope/publisher/interfaces/__init__.py	2013-02-15 17:26:22 UTC (rev 129440)
@@ -62,10 +62,10 @@
 
     def __str__(self):
         try:
-            ob = `self.ob`
+            ob = repr(self.ob)
         except:
             ob = 'unprintable object'
-        return 'Object: %s, name: %s' % (ob, `self.name`)
+        return 'Object: %s, name: %s' % (ob, repr(self.name))
 
 class IDebugError(ITraversalException):
     def getObject():

Modified: zope.publisher/branches/py3-attempt2/src/zope/publisher/publish.py
===================================================================
--- zope.publisher/branches/py3-attempt2/src/zope/publisher/publish.py	2013-02-15 17:25:45 UTC (rev 129439)
+++ zope.publisher/branches/py3-attempt2/src/zope/publisher/publish.py	2013-02-15 17:26:22 UTC (rev 129440)
@@ -16,6 +16,8 @@
 Provide an apply-like facility that works with any mapping object
 """
 import sys
+
+import six
 from zope import component
 from zope.interface import implementer
 from zope.publisher.interfaces import Retry, IReRaiseException
@@ -64,8 +66,8 @@
 
     unwrapped, wrapperCount = unwrapMethod(unwrapped)
 
-    code = unwrapped.func_code
-    defaults = unwrapped.func_defaults
+    code = unwrapped.__code__
+    defaults = unwrapped.__defaults__
     names = code.co_varnames[wrapperCount:code.co_argcount]
 
     nargs = len(names)
@@ -154,7 +156,7 @@
 
                     break # Successful.
 
-                except Retry, retryException:
+                except Retry as retryException:
                     if request.supportsRetry():
                         # Create a copy of the request and use it.
                         newrequest = request.retry()
@@ -187,7 +189,7 @@
 
         response = request.response
         if to_raise is not None:
-            raise to_raise[0], to_raise[1], to_raise[2]
+            six.reraise(to_raise[0], to_raise[1], to_raise[2])
 
     finally:
         to_raise = None  # Avoid circ. ref.

Modified: zope.publisher/branches/py3-attempt2/src/zope/publisher/testing.py
===================================================================
--- zope.publisher/branches/py3-attempt2/src/zope/publisher/testing.py	2013-02-15 17:25:45 UTC (rev 129439)
+++ zope.publisher/branches/py3-attempt2/src/zope/publisher/testing.py	2013-02-15 17:26:22 UTC (rev 129440)
@@ -12,12 +12,20 @@
 #
 ##############################################################################
 
+import sys
 import contextlib
 import zope.publisher.browser
 import zope.security.management
 import zope.security.testing
 
+PY2 = sys.version_info[0] == 2
 
+if PY2:
+    _u = unicode
+else:
+    _u = str
+
+
 # These are enhanced versions of the ones in zope.security.testing,
 # they use a TestRequest instead of a TestParticipation.
 

Modified: zope.publisher/branches/py3-attempt2/src/zope/publisher/tests/test_baserequest.py
===================================================================
--- zope.publisher/branches/py3-attempt2/src/zope/publisher/tests/test_baserequest.py	2013-02-15 17:25:45 UTC (rev 129439)
+++ zope.publisher/branches/py3-attempt2/src/zope/publisher/tests/test_baserequest.py	2013-02-15 17:26:22 UTC (rev 129440)
@@ -24,7 +24,7 @@
 from zope.publisher.tests.basetestiapplicationrequest \
      import BaseTestIApplicationRequest
 
-from StringIO import StringIO
+from io import BytesIO
 from zope.interface import Interface, providedBy, alsoProvides
 from zope.component import provideAdapter
 
@@ -35,7 +35,7 @@
 
     def _Test__new(self, **kw):
         from zope.publisher.base import BaseRequest
-        return BaseRequest(StringIO(''), kw)
+        return BaseRequest(BytesIO(), kw)
 
     def _Test__expectedViewType(self):
         return None # we don't expect
@@ -43,8 +43,8 @@
     def test_IApplicationRequest_bodyStream(self):
         from zope.publisher.base import BaseRequest
 
-        request = BaseRequest(StringIO('spam'), {})
-        self.assertEqual(request.bodyStream.read(), 'spam')
+        request = BaseRequest(BytesIO(b'spam'), {})
+        self.assertEqual(request.bodyStream.read(), b'spam')
 
     def test_IPublicationRequest_getPositionalArguments(self):
         self.assertEqual(self._Test__new().getPositionalArguments(), ())

Modified: zope.publisher/branches/py3-attempt2/src/zope/publisher/tests/test_xmlrpcrequest.py
===================================================================
--- zope.publisher/branches/py3-attempt2/src/zope/publisher/tests/test_xmlrpcrequest.py	2013-02-15 17:25:45 UTC (rev 129439)
+++ zope.publisher/branches/py3-attempt2/src/zope/publisher/tests/test_xmlrpcrequest.py	2013-02-15 17:26:22 UTC (rev 129440)
@@ -14,7 +14,7 @@
 """XML-RPC Request Tests
 """
 import unittest
-from StringIO import StringIO
+from io import BytesIO
 
 from zope.publisher.base import DefaultPublication
 from zope.publisher.http import HTTPCharsets
@@ -39,7 +39,7 @@
         XMLRPCRequest.__init__(self, *args, **kw)
 
 
-xmlrpc_call = u'''<?xml version='1.0'?>
+xmlrpc_call = '''<?xml version='1.0'?>
 <methodCall>
   <methodName>action</methodName>
   <params>
@@ -109,7 +109,7 @@
             env['CONTENT_LENGTH'] = str(len(body))
 
         publication = Publication(self.app)
-        instream = StringIO(body)
+        instream = BytesIO(body)
         request = TestXMLRPCRequest(instream, env)
         request.setPublication(publication)
         return request



More information about the checkins mailing list