Skip to content

Commit

Permalink
Prepare for Python 2 / 3 compatibility (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
pbauer authored Jan 28, 2018
1 parent 7c14253 commit bad83e4
Show file tree
Hide file tree
Showing 10 changed files with 37 additions and 28 deletions.
3 changes: 2 additions & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ New features:

Bug fixes:

- *add item here*
- Prepare for Python 2 / 3 compatibility
[pbauer]


2.5.4 (2017-11-24)
Expand Down
23 changes: 12 additions & 11 deletions plone/dexterity/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
from zope.schema.interfaces import IContextAwareDefaultFactory
from zope.security.interfaces import IPermission

import six


_marker = object()
_zone = DateTime().timezone()
FLOOR_DATE = DateTime(1970, 0) # always effective
Expand Down Expand Up @@ -360,10 +363,10 @@ def __getattr__(self, name):
# that can't be encoded to ASCII will throw a UnicodeEncodeError

def _get__name__(self):
return unicode(self.id)
return six.text_type(self.id)

def _set__name__(self, value):
if isinstance(value, unicode):
if isinstance(value, six.text_type):
value = str(value) # may throw, but that's OK - id must be ASCII
self.id = value

Expand Down Expand Up @@ -410,7 +413,7 @@ def setModificationDate(self, modification_date=None):
@security.protected(permissions.View)
def Title(self):
# this is a CMF accessor, so should return utf8-encoded
if isinstance(self.title, unicode):
if isinstance(self.title, six.text_type):
return self.title.encode('utf-8')
return self.title or ''

Expand All @@ -425,7 +428,7 @@ def Description(self):
value = value.replace('\r\n', ' ').replace('\r', ' ').replace('\n', ' ') # noqa

# this is a CMF accessor, so should return utf8-encoded
if isinstance(value, unicode):
if isinstance(value, six.text_type):
value = value.encode('utf-8')

return value
Expand Down Expand Up @@ -599,21 +602,21 @@ def setDescription(self, description):
@security.protected(permissions.ModifyPortalContent)
def setCreators(self, creators):
# Set Dublin Core Creator elements - resource authors.
if isinstance(creators, basestring):
if isinstance(creators, six.string_types):
creators = [creators]
self.creators = tuple(safe_unicode(c.strip()) for c in creators)

@security.protected(permissions.ModifyPortalContent)
def setSubject(self, subject):
# Set Dublin Core Subject element - resource keywords.
if isinstance(subject, basestring):
if isinstance(subject, six.string_types):
subject = [subject]
self.subject = tuple(safe_unicode(s.strip()) for s in subject)

@security.protected(permissions.ModifyPortalContent)
def setContributors(self, contributors):
# Set Dublin Core Contributor elements - resource collaborators.
if isinstance(contributors, basestring):
if isinstance(contributors, six.string_types):
contributors = contributors.split(';')
self.contributors = tuple(
safe_unicode(c.strip()) for c in contributors)
Expand Down Expand Up @@ -718,7 +721,7 @@ def manage_delObjects(self, ids=None, REQUEST=None):
"""
if ids is None:
ids = []
if isinstance(ids, basestring):
if isinstance(ids, six.string_types):
ids = [ids]
for id in ids:
item = self._getOb(id)
Expand Down Expand Up @@ -756,9 +759,7 @@ def invokeFactory(self, type_name, id, RESPONSE=None, *args, **kw):
if fti is not None and not fti.isConstructionAllowed(self):
raise Unauthorized('Cannot create %s' % fti.getId())

allowed_ids = [
fti.getId() for fti in constrains.allowedContentTypes()
]
allowed_ids = [i.getId() for i in constrains.allowedContentTypes()]
if type_name not in allowed_ids:
raise ValueError(
'Subobject type disallowed by IConstrainTypes adapter: %s'
Expand Down
2 changes: 1 addition & 1 deletion plone/dexterity/exportimport.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
from Products.GenericSetup.interfaces import IFilesystemExporter
from Products.GenericSetup.interfaces import IFilesystemImporter
from Products.GenericSetup.utils import _getDottedName
from StringIO import StringIO
from csv import reader
from csv import writer
from six import StringIO
from zope.component import queryAdapter
from zope.interface import implementer

Expand Down
2 changes: 1 addition & 1 deletion plone/dexterity/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __call__(self, *args, **kw):

try:
obj = klass(*args, **kw)
except TypeError, e:
except TypeError as e:
raise ValueError(
"Error whilst constructing content for %s using class %s: %s"
% (self.portal_type, fti.klass, str(e))
Expand Down
3 changes: 2 additions & 1 deletion plone/dexterity/tests/case.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from mock import Mock
import gc
import six
import unittest
import zope.component
import zope.component.testing
Expand Down Expand Up @@ -94,6 +95,6 @@ def _global_replace(remove, install):
"""Replace object 'remove' with object 'install' on all dictionaries."""
for referrer in gc.get_referrers(remove):
if (type(referrer) is dict):
for key, value in list(referrer.iteritems()):
for key, value in list(six.iteritems(referrer)):
if value is remove:
referrer[key] = install
3 changes: 2 additions & 1 deletion plone/dexterity/tests/test_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from zope.interface import alsoProvides
from .case import MockTestCase

import six
import zope.schema


Expand Down Expand Up @@ -588,7 +589,7 @@ def test_name_unicode_id_str(self):
self.assertEqual("o", i.id)
self.assertEqual("o", i.getId())

self.assertTrue(isinstance(i.__name__, unicode))
self.assertTrue(isinstance(i.__name__, six.text_type))
self.assertTrue(isinstance(i.id, str))
self.assertTrue(isinstance(i.getId(), str))

Expand Down
6 changes: 4 additions & 2 deletions plone/dexterity/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
from .case import MockTestCase
from zope import schema

import six


class TestRequest(TestRequestBase):
"""Zope 3's TestRequest doesn't support item assignment, but Zope 2's
Expand Down Expand Up @@ -251,7 +253,7 @@ def test_label(self):
addform.portal_type = u"testtype"

label = addform.label
self.assertEqual(u"Add ${name}", unicode(label))
self.assertEqual(u"Add ${name}", six.text_type(label))
self.assertEqual(u"Test title", label.mapping['name'])

def test_schema_lookup_add(self):
Expand Down Expand Up @@ -484,7 +486,7 @@ def test_label(self):
editview.portal_type = u"testtype"

label = editview.label
self.assertEqual(u"Edit ${name}", unicode(label))
self.assertEqual(u"Edit ${name}", six.text_type(label))
self.assertEqual(u"Test title", label.mapping['name'])

def test_schema_lookup_edit(self):
Expand Down
18 changes: 9 additions & 9 deletions plone/dexterity/tests/test_webdav.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
# -*- coding: utf-8 -*-
from OFS.Folder import Folder
from OFS.SimpleItem import SimpleItem
from StringIO import StringIO
from ZPublisher.HTTPResponse import HTTPResponse
from ZPublisher.Iterators import IStreamIterator
from .case import Dummy
from .case import MockTestCase
from email.Message import Message
from mock import Mock
from OFS.Folder import Folder
from OFS.SimpleItem import SimpleItem
from plone.autoform.interfaces import IFormFieldProvider
from plone.behavior.interfaces import IBehaviorAssignable
from plone.dexterity.browser.traversal import DexterityPublishTraverse
Expand All @@ -21,6 +20,7 @@
from plone.dexterity.interfaces import IDexterityFTI
from plone.dexterity.schema import SCHEMA_CACHE
from plone.rfc822.interfaces import IPrimaryField
from six import StringIO
from webdav.NullResource import NullResource
from zExceptions import Forbidden
from zExceptions import MethodNotAllowed
Expand All @@ -31,14 +31,14 @@
from zope.filerepresentation.interfaces import IFileFactory
from zope.filerepresentation.interfaces import IRawReadFile
from zope.filerepresentation.interfaces import IRawWriteFile
from zope.interface import Interface
from zope.interface import alsoProvides
from zope.interface import implementer
from zope.interface import Interface
from zope.lifecycleevent.interfaces import IObjectModifiedEvent
from zope.publisher.browser import TestRequest
from zope.size.interfaces import ISized
from .case import Dummy
from .case import MockTestCase
from ZPublisher.HTTPResponse import HTTPResponse
from ZPublisher.Iterators import IStreamIterator

import re

Expand Down Expand Up @@ -1121,7 +1121,7 @@ class ITest(Interface):
# next

self.assertEqual(body, readfile.read())
self.assertEqual(69L, readfile.size())
self.assertEqual(69, readfile.size())
self.assertEqual('utf-8', readfile.encoding)
self.assertEqual(None, readfile.name)
self.assertEqual('text/plain', readfile.mimeType)
Expand Down
4 changes: 3 additions & 1 deletion plone/dexterity/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@

import datetime
import logging
import six


deprecation.deprecated(
'SchemaNameEncoder',
Expand Down Expand Up @@ -198,7 +200,7 @@ def createContentInContainer(container, portal_type, checkConstraints=True,


def safe_utf8(st):
if isinstance(st, unicode):
if isinstance(st, six.text_type):
st = st.encode('utf8')
return st

Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
'Products.CMFDynamicViewFTI',
'Products.statusmessages',
'setuptools',
'six',
'ZODB3',
'zope.annotation',
'zope.browser',
Expand Down

0 comments on commit bad83e4

Please sign in to comment.