Skip to content

Commit

Permalink
More cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
gforcada committed Feb 15, 2016
1 parent a2cf2f2 commit 9935eec
Show file tree
Hide file tree
Showing 11 changed files with 94 additions and 91 deletions.
8 changes: 2 additions & 6 deletions plone/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,2 @@
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
# -*- coding: utf-8 -*-
__import__('pkg_resources').declare_namespace(__name__)
6 changes: 4 additions & 2 deletions plone/tiles/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-

# Convenience imports
from plone.tiles.tile import Tile, PersistentTile
from plone.tiles.tile import PersistentTile
from plone.tiles.tile import Tile


assert Tile, PersistentTile # silence pyflakes
23 changes: 11 additions & 12 deletions plone/tiles/absoluteurl.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
# -*- coding: utf-8 -*-

import urllib

from plone.tiles.data import encode
from plone.tiles.interfaces import ITileDataManager
from plone.tiles.interfaces import ITileType
from zope.component import getMultiAdapter
from zope.component import queryUtility

from zope.traversing.browser.interfaces import IAbsoluteURL
from zope.traversing.browser.absoluteurl import AbsoluteURL
from zope.traversing.browser.interfaces import IAbsoluteURL

import urllib

from plone.tiles.interfaces import ITileType, ITileDataManager
from plone.tiles.data import encode

_safe = '@+'

Expand All @@ -27,15 +26,15 @@ def __str__(self):
context = tile.__parent__

if name is None or context is None:
raise TypeError("Insufficient context to determine URL")
raise TypeError('Insufficient context to determine URL')

tileFragment = "@@" + urllib.quote(name.encode('utf-8'), _safe)
tileFragment = '@@' + urllib.quote(name.encode('utf-8'), _safe)
if id:
tileFragment += '/' + urllib.quote(id.encode('utf-8'), _safe)

absolute_url = getMultiAdapter((context, request), IAbsoluteURL)
try:
tileFragment = '%s/%s' % (str(absolute_url), tileFragment)
tileFragment = '{0}/{1}'.format(str(absolute_url), tileFragment)
except TypeError: # Not enough context to get URL information
pass

Expand All @@ -49,14 +48,14 @@ def breadcrumbs(self):
name = tile.__name__
context = tile.__parent__

tileFragment = "@@" + urllib.quote(name.encode('utf-8'), _safe)
tileFragment = '@@' + urllib.quote(name.encode('utf-8'), _safe)
if id:
tileFragment += '/' + urllib.quote(id.encode('utf-8'), _safe)

base = tuple(
getMultiAdapter((context, request), IAbsoluteURL).breadcrumbs())
base += ({'name': name,
'url': "%s/%s" % (base[-1]['url'], tileFragment,),
'url': '{0}/{1}'.format(base[-1]['url'], tileFragment,),
},)

return base
Expand Down
66 changes: 37 additions & 29 deletions plone/tiles/data.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
# -*- coding: utf-8 -*-
import logging
import urllib
from zope.interface import implements
from zope.interface import implementer
from zope.interface import Interface
from zope.component import adapts
from persistent.dict import PersistentDict
from plone.tiles.interfaces import IFieldTypeConverter
from plone.tiles.interfaces import IPersistentTile
from plone.tiles.interfaces import ITile
from plone.tiles.interfaces import ITileDataContext
from plone.tiles.interfaces import ITileDataManager
from plone.tiles.interfaces import ITileType
from zope.annotation.interfaces import IAnnotations
from zope.component import adapter
from zope.component import queryUtility
from zope.component import adapts
from zope.component import getMultiAdapter
from zope.component import queryUtility
from zope.component.interfaces import ComponentLookupError
from zope.schema import getFieldsInOrder
from zope.interface import implementer
from zope.interface import implements
from zope.interface import Interface
from zope.schema import getFields
from zope.schema import getFieldsInOrder
from zope.schema.interfaces import ISequence
from zope.annotation.interfaces import IAnnotations
from plone.tiles.interfaces import ITileType
from plone.tiles.interfaces import ITile
from plone.tiles.interfaces import IPersistentTile
from plone.tiles.interfaces import ITileDataManager
from plone.tiles.interfaces import ITileDataContext
from plone.tiles.interfaces import IFieldTypeConverter
from persistent.dict import PersistentDict

import logging
import urllib


try:
import json
Expand Down Expand Up @@ -54,7 +56,7 @@ def __init__(self, tile):
self.tileType = queryUtility(ITileType, name=tile.__name__)
self.annotations = IAnnotations(self.tile.request,
self.tile.request.form)
self.key = "%s.%s" % (ANNOTATIONS_KEY_PREFIX, tile.id,)
self.key = '{0}.{1}'.format(ANNOTATIONS_KEY_PREFIX, tile.id,)

def get(self):
# use explicitly set data (saved as annotation on the request)
Expand All @@ -81,7 +83,7 @@ def get(self):
data = decode(self.tile.request.form,
self.tileType.schema, missing=True)
except (ValueError, UnicodeDecodeError,):
LOGGER.exception(u"Could not convert form data to schema")
LOGGER.exception(u'Could not convert form data to schema')
return self.data.copy()

return data
Expand Down Expand Up @@ -110,7 +112,7 @@ def __init__(self, tile):
(tile.context, tile.request, tile), ITileDataContext)
self.annotations = IAnnotations(self.context)

self.key = "%s.%s" % (ANNOTATIONS_KEY_PREFIX, tile.id,)
self.key = '{0}.{1}'.format(ANNOTATIONS_KEY_PREFIX, tile.id,)

def _get_default_request_data(self):
# If we don't have a schema, just take the request
Expand All @@ -122,7 +124,7 @@ def _get_default_request_data(self):
data = decode(self.tile.request.form,
self.tileType.schema, missing=True)
except (ValueError, UnicodeDecodeError,):
LOGGER.exception(u"Could not convert form data to schema")
LOGGER.exception(u'Could not convert form data to schema')
return self.data.copy()
return data

Expand Down Expand Up @@ -179,14 +181,14 @@ def guess_type(v):
marshall_type = guess_type(item_subvalue)
if isinstance(item_subvalue, bool):
item_subvalue = item_subvalue and '1' or ''
encoded_name = "%s.%s%s:list:%s" % (
encoded_name = '{0}.{1}{2}:list:{3}'.format(
prefix, item_name, marshall_type, postfix)
yield encoded_name, item_subvalue
else:
marshall_type = guess_type(item_value)
if isinstance(item_value, bool):
item_value = item_value and '1' or ''
encoded_name = "%s.%s%s:%s" % (
encoded_name = '{0}.{1}{2}:{3}'.format(
prefix, item_name, marshall_type, postfix)
yield encoded_name, item_value

Expand All @@ -210,12 +212,12 @@ def encode(data, schema, ignore=()):

converter = IFieldTypeConverter(field, None)
if converter is None:
raise ComponentLookupError(u"Cannot URL encode %s of type %s" % (
name, field.__class__,))
msg = u'Cannot URL encode {0} of type {1}'
raise ComponentLookupError(msg.format(name, field.__class__,))

encoded_name = name
if converter.token:
encoded_name = "%s:%s" % (name, converter.token,)
encoded_name = '{0}:{1}'.format(name, converter.token,)

value = data[name]
if value is None:
Expand All @@ -226,12 +228,17 @@ def encode(data, schema, ignore=()):
if ISequence.providedBy(field):
value_type_converter = IFieldTypeConverter(field.value_type, None)
if value_type_converter is None:
msg = u'Cannot URL encode value type for {0} of type {1} : {2}'
raise ComponentLookupError(
u"Cannot URL encode value type for %s of type %s : %s" % (
name, field.__class__, field.value_type.__class__,))
msg.format(
name,
field.__class__,
field.value_type.__class__,
)
)

if value_type_converter.token:
encoded_name = "%s:%s:%s" % (
encoded_name = '{0}:{1}:{2}'.format(
name, value_type_converter.token, converter.token,)

for item in value:
Expand Down Expand Up @@ -299,7 +306,8 @@ def decode(data, schema, missing=True):
for item in value:
if isinstance(item, str):
value = unicode(item, 'utf-8')
if field.value_type._type and not isinstance(item, field.value_type._type):
if field.value_type._type and \
not isinstance(item, field.value_type._type):
item = value_type_field_type(item)
converted.append(item)

Expand Down
18 changes: 10 additions & 8 deletions plone/tiles/esi.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# -*- coding: utf-8 -*-
from plone.tiles.interfaces import ESI_HEADER
from plone.tiles.interfaces import ESI_HEADER_KEY
from plone.tiles.interfaces import IESIRendered
from plone.tiles.tile import PersistentTile
from plone.tiles.tile import Tile
from zope.interface import implements

import re

from zope.interface import implements

from plone.tiles.interfaces import IESIRendered, ESI_HEADER, ESI_HEADER_KEY
from plone.tiles.tile import Tile, PersistentTile

HEAD_CHILDREN = re.compile(r'<head[^>]*>(.*)</head>', re.I | re.S)
BODY_CHILDREN = re.compile(r'<body[^>]*>(.*)</body>', re.I | re.S)
Expand All @@ -17,7 +19,7 @@
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<a class="_esi_placeholder" rel="esi" """ + \
u"""href="%(url)s/@@%(esiMode)s?%(queryString)s"></a>
u"""href="{url}/@@{esiMode}?{queryString}"></a>
</body>
</html>
"""
Expand All @@ -31,7 +33,7 @@ def substituteESILinks(rendered):
"""

rendered = re.sub(r'<html',
'<html xmlns:esi="%s"' % ESI_NAMESPACE_MAP['esi'],
'<html xmlns:esi="{0}"'.format(ESI_NAMESPACE_MAP['esi']),
rendered, 1)
return re.sub(r'<a class="_esi_placeholder" rel="esi" href="([^"]+)"></a>',
r'<esi:include src="\1" />', rendered)
Expand All @@ -50,11 +52,11 @@ def __call__(self, *args, **kwargs):
mode = 'esi-body'
if self.head:
mode = 'esi-head'
return ESI_TEMPLATE % {
return ESI_TEMPLATE.format({
'url': self.request.getURL(),
'queryString': self.request.get('QUERY_STRING', ''),
'esiMode': mode,
}
})
if hasattr(self, 'index'):
return self.index(*args, **kwargs)

Expand Down
3 changes: 1 addition & 2 deletions plone/tiles/fieldtypeconverters.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-

from zope.interface import implements
from plone.tiles.interfaces import IFieldTypeConverter
from zope.interface import implements


class NoConverter(object):
Expand Down
6 changes: 3 additions & 3 deletions plone/tiles/interfaces.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-

from zope.interface import Interface
import zope.schema

from zope.interface.interfaces import IInterface
from zope.publisher.interfaces.browser import IBrowserView

import zope.schema


ESI_HEADER = 'X-ESI-Enabled'
ESI_HEADER_KEY = 'HTTP_' + ESI_HEADER.replace('-', '_').upper()

Expand Down
23 changes: 10 additions & 13 deletions plone/tiles/meta.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
# -*- coding: utf-8 -*-

from zope.interface import Interface

from plone.tiles.interfaces import ITileType
from plone.tiles.tile import Tile
from plone.tiles.type import TileType
from zope import schema
from zope.configuration.fields import (
GlobalObject, GlobalInterface, MessageID, Path)
from zope.security.zcml import Permission

from zope.component.zcml import utility
from zope.configuration.exceptions import ConfigurationError

from zope.configuration.fields import GlobalInterface
from zope.configuration.fields import GlobalObject
from zope.configuration.fields import MessageID
from zope.configuration.fields import Path
from zope.interface import Interface
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.security.zcml import Permission

from plone.tiles.interfaces import ITileType
from plone.tiles.type import TileType
from plone.tiles.tile import Tile

from zope.component.zcml import utility

try:
from Products.Five.browser.metaconfigure import page
Expand Down
25 changes: 13 additions & 12 deletions plone/tiles/tests.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
# -*- coding: utf-8 -*-
from plone.testing import Layer
from plone.testing import layered
from plone.testing import z2
from plone.testing import zca
from plone.tiles import PersistentTile
from plone.tiles import Tile
from zope import schema
from zope.configuration import xmlconfig
from zope.interface import Interface

import unittest2 as unittest
import doctest
from plone.testing import Layer, layered
from plone.testing import zca, z2
import unittest2 as unittest

from zope.configuration import xmlconfig

# For directive tests

from zope.interface import Interface
from zope import schema

from plone.tiles import Tile, PersistentTile


class IDummySchema(Interface):
foo = schema.TextLine(title=u"Foo")
foo = schema.TextLine(title=u'Foo')


class IDummyContext(Interface):
Expand All @@ -29,7 +30,7 @@ class IDummyLayer(Interface):

class DummyTile(Tile):
def __call__(self):
return u"dummy"
return u'dummy'


class DummyTileWithTemplate(PersistentTile):
Expand All @@ -51,7 +52,7 @@ def tearDown(self):
PLONE_TILES_FIXTURE = PloneTiles()

PLONE_TILES_INTEGRATION_TESTING = z2.IntegrationTesting(
bases=(PLONE_TILES_FIXTURE,), name="PloneTiles:Functional")
bases=(PLONE_TILES_FIXTURE,), name='PloneTiles:Functional')


def test_suite():
Expand Down
2 changes: 1 addition & 1 deletion plone/tiles/tile.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __getitem__(self, name):
# __getitem__.

if self.__doc__ is None:
self.__doc__ = "For Zope 2, to keep the ZPublisher happy"
self.__doc__ = 'For Zope 2, to keep the ZPublisher happy'

self.request.response.setHeader(
'X-Tile-Url', self.url)
Expand Down
Loading

1 comment on commit 9935eec

@jenkins-plone-org
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gforcada Jenkins CI reporting about code analysis
See the full report here: http://jenkins.plone.org/job/package-plone.tiles/3//violations

plone/tiles/data.py:156:1: C901 'map_to_pairs' is too complex (12)
plone/tiles/data.py:196:1: C901 'encode' is too complex (15)
plone/tiles/data.py:270:1: C901 'decode' is too complex (14)
plone/tiles/esi.py:60:12: P002 found "hasattr", consider replacing it
plone/tiles/tile.py:79:16: P002 found "hasattr", consider replacing it

Follow these instructions to reproduce it locally.

Please sign in to comment.