Skip to content

Commit

Permalink
Update code to follow Plone styleguide
Browse files Browse the repository at this point in the history
  • Loading branch information
gforcada committed Oct 31, 2016
1 parent 2d4c860 commit eb804c1
Show file tree
Hide file tree
Showing 18 changed files with 244 additions and 167 deletions.
4 changes: 2 additions & 2 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ New features:

Bug fixes:

- *add item here*

- Update code to follow Plone styleguide.
[gforcada]

1.2.13 (2016-10-05)
-------------------
Expand Down
51 changes: 28 additions & 23 deletions plone/app/caching/browser/controlpanel.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@

# Borrowed from zope.schema to avoid an import of a private name
_isuri = re.compile(
r"[a-zA-z0-9+.-]+:" # scheme
r"\S*$" # non space (should be pickier)
r'[a-zA-z0-9+.-]+:' # scheme
r'\S*$' # non space (should be pickier)
).match


Expand Down Expand Up @@ -162,7 +162,10 @@ def update(self):
self.processSave()
elif 'form.button.Cancel' in self.request.form:
self.request.response.redirect(
"%s/@@overview-controlpanel" % self.context.absolute_url())
'{0}/@@overview-controlpanel'.format(
self.context.absolute_url()
)
)

def processSave(self):

Expand Down Expand Up @@ -273,7 +276,7 @@ def processSave(self):
# Validate purging settings
for cachingProxy in cachingProxies:
if not _isuri(cachingProxy):
self.errors['cachingProxies'] = _(u"Invalid URL: ${url}", mapping={'url': cachingProxy}) # noqa
self.errors['cachingProxies'] = _(u'Invalid URL: ${url}', mapping={'url': cachingProxy}) # noqa

for domain in domains:
if not _isuri(domain):
Expand All @@ -286,16 +289,16 @@ def processSave(self):
try:
ramCacheMaxEntries = int(ramCacheMaxEntries)
except (ValueError, TypeError,):
self.errors['ramCacheMaxEntries'] = _(u"An integer is required.")
self.errors['ramCacheMaxEntries'] = _(u'An integer is required.')
else:
if ramCacheMaxEntries < 0:
self.errors['ramCacheMaxEntries'] = _(
u"A positive number is required."
u'A positive number is required.'
)
try:
ramCacheMaxAge = int(ramCacheMaxAge)
except (ValueError, TypeError,):
self.errors['ramCacheMaxAge'] = _(u"An integer is required.")
self.errors['ramCacheMaxAge'] = _(u'An integer is required.')
else:
if ramCacheMaxAge < 0:
self.errors['ramCacheMaxAge'] = _(
Expand All @@ -317,7 +320,7 @@ def processSave(self):
# Check for errors
if self.errors:
IStatusMessage(self.request).addStatusMessage(
_(u"There were errors."), "error")
_(u'There were errors.'), 'error')
return

# Save settings
Expand Down Expand Up @@ -476,7 +479,7 @@ def hasGlobalOptions(self, operationType):
return False

for option in options:
if '%s.%s' % (prefix, option,) in self.registry:
if '{0}.{1}'.format(prefix, option,) in self.registry:
return True

return False
Expand All @@ -489,7 +492,7 @@ def hasRulesetOptions(self, operationType, ruleset):
return False

for option in options:
if '%s.%s.%s' % (prefix, ruleset, option,) in self.registry:
if '{0}.{1}.{2}'.format(prefix, ruleset, option,) in self.registry:
return True

return False
Expand All @@ -509,26 +512,28 @@ def processImport(self):
snapshot = self.request.form.get('snapshot', True)

if not profile:
self.errors['profile'] = _(u"You must select a profile to import.")
self.errors['profile'] = _(u'You must select a profile to import.')

if self.errors:
IStatusMessage(self.request).addStatusMessage(
_(u"There were errors."), "error")
_(u'There were errors.'), 'error')
return

portal_setup = getToolByName(self.context, 'portal_setup')

# Create a snapshot
if snapshot:
snapshotId = "plone.app.caching.beforeimport.%s" % (
snapshotId = 'plone.app.caching.beforeimport.{0}'.format(
datetime.datetime.now().isoformat().replace(':', '.'))
portal_setup.createSnapshot(snapshotId)

# Import the new profile
portal_setup.runAllImportStepsFromProfile("profile-%s" % profile)
portal_setup.runAllImportStepsFromProfile(
'profile-{0}'.format(profile)
)

IStatusMessage(self.request).addStatusMessage(
_(u"Import complete."), "info")
_(u'Import complete.'), 'info')

@property
@memoize
Expand Down Expand Up @@ -558,11 +563,11 @@ def processPurge(self):
sync = self.request.form.get('synchronous', True)

if not urls:
self.errors['urls'] = _(u"No URLs or paths entered.")
self.errors['urls'] = _(u'No URLs or paths entered.')

if self.errors:
IStatusMessage(self.request).addStatusMessage(
_(u"There were errors."), "error")
_(u'There were errors.'), 'error')
return

purger = getUtility(IPurger)
Expand All @@ -574,11 +579,11 @@ def purge(url):

log = url
if xcache:
log += " (X-Cache header: " + xcache + ")"
log += ' (X-Cache header: ' + xcache + ')'
if xerror:
log += " -- " + xerror
log += ' -- ' + xerror
if not str(status).startswith('2'):
log += " -- WARNING status " + str(status)
log += ' -- WARNING status ' + str(status)
self.purgeLog.append(log)
else:
purger.purgeAsync(url)
Expand Down Expand Up @@ -638,13 +643,13 @@ def processPurge(self):

if self.ramCache is None:
IStatusMessage(self.request).addStatusMessage(
_(u"RAM cache not installed."), "error")
_(u'RAM cache not installed.'), 'error')

if self.errors:
IStatusMessage(self.request).addStatusMessage(
_(u"There were errors."), "error")
_(u'There were errors.'), 'error')
return

self.ramCache.invalidateAll()
IStatusMessage(self.request).addStatusMessage(
_(u"Cache purged."), "info")
_(u'Cache purged.'), 'info')
24 changes: 15 additions & 9 deletions plone/app/caching/browser/edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,14 @@ def update(self):

for option in self.operation.options:
newField = None
fieldName = "%s.%s" % (prefix, option)
fieldName = '{0}.{1}'.format(prefix, option)

if self.rulesetName:
rulesetFieldName = "%s.%s.%s" % (
prefix, self.rulesetName, option)
rulesetFieldName = '{0}.{1}.{2}'.format(
prefix,
self.rulesetName,
option,
)

if rulesetFieldName in self.registry.records:
newField = self.cloneField(self.registry.records[
Expand Down Expand Up @@ -149,14 +152,14 @@ def getContent(self):
options = self.operation.options

for option in options:
recordName = "%s.%s" % (prefix, option,)
recordName = '{0}.{1}'.format(prefix, option,)

# If a ruleset-specific record does not exist, we can fall back on
# a global record, since the per-ruleset records will be created
# as necessary in applyChanges()

if self.rulesetName:
rulesetRecordName = "%s.%s.%s" % (
rulesetRecordName = '{0}{1}{2}'.format(
prefix, self.rulesetName, option,)

if rulesetRecordName in self.registry.records:
Expand Down Expand Up @@ -255,7 +258,7 @@ def save(self, action):
@button.buttonAndHandler(_(u'Cancel'), name='cancel')
def cancel(self, action):
IStatusMessage(self.request).addStatusMessage(
_(u"Edit cancelled."), type="info")
_(u"Edit cancelled."), type='info')
self.request.response.redirect(
'{0}/@@caching-controlpanel#detailed-settings'.format(
self.context.absolute_url()
Expand All @@ -269,14 +272,17 @@ def cancel(self, action):
)
def clear(self, action):
for key in self.getContent().keys():
assert key.startswith("%s.%s." % (
self.operation.prefix, self.rulesetName,))
key_suffix = '{0}.{1}.'.format(
self.operation.prefix,
self.rulesetName,
)
assert key.startswith(key_suffix)

if key in self.registry.records:
del self.registry.records[key]

IStatusMessage(self.request).addStatusMessage(
_(u"Ruleset-specific settings removed."), type="info")
_(u"Ruleset-specific settings removed."), type='info')
self.request.response.redirect(
'{0}/@@caching-controlpanel#detailed-settings'.format(
self.context.absolute_url()
Expand Down
2 changes: 1 addition & 1 deletion plone/app/caching/operations/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def modifyResponse(self, rulename, response, class_=None):
if cacheStop(self.request, rulename):
# only stop with etags if configured
if etags:
etag = "%s%d" % (time.time(), random.randint(0, 1000))
etag = '{0}{1}'.format(time.time(), random.randint(0, 1000))
return setCacheHeaders(
self.published,
self.request,
Expand Down
2 changes: 1 addition & 1 deletion plone/app/caching/operations/etags.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def __call__(self):
return None
if portal_state.anonymous():
return None
return "%s%d" % (time.time(), random.randint(0, 1000))
return '{0}{1}'.format(time.time(), random.randint(0, 1000))


@implementer(IETagValue)
Expand Down
24 changes: 13 additions & 11 deletions plone/app/caching/operations/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def cacheInBrowser(published, request, response, etag=None, lastModified=None):
"""

if etag is not None:
response.setHeader('ETag', '"%s"' % etag, literal=1)
response.setHeader('ETag', '"{0}"'.format(etag), literal=1)

if lastModified is not None:
response.setHeader('Last-Modified', formatDateTime(lastModified))
Expand Down Expand Up @@ -169,14 +169,16 @@ def cacheInProxy(
del response.headers['last-modified']

if etag is not None:
response.setHeader('ETag', '"%s"' % etag, literal=1)
response.setHeader('ETag', '"{0}"'.format(etag), literal=1)

if vary is not None:
response.setHeader('Vary', vary)

response.setHeader('Expires', formatDateTime(getExpiration(0)))
response.setHeader(
'Cache-Control', 'max-age=0, s-maxage=%d, must-revalidate' % smaxage)
'Cache-Control',
'max-age=0, s-maxage={0}, must-revalidate'.format(smaxage),
)


def cacheInBrowserAndProxy(
Expand Down Expand Up @@ -205,22 +207,22 @@ def cacheInBrowserAndProxy(
del response.headers['last-modified']

if etag is not None:
response.setHeader('ETag', '"%s"' % etag, literal=1)
response.setHeader('ETag', '"{0}"'.format(etag), literal=1)

if vary is not None:
response.setHeader('Vary', vary)

response.setHeader('Expires', formatDateTime(getExpiration(maxage)))

if smaxage is not None:
maxage = '%s, s-maxage=%s' % (maxage, smaxage)
maxage = '{0}, s-maxage={1}'.format(maxage, smaxage)

# Substituting proxy-validate in place of must=revalidate here because of
# Safari bug
# https://bugs.webkit.org/show_bug.cgi?id=13128
response.setHeader(
'Cache-Control',
'max-age=%s, proxy-revalidate, public' % maxage
'max-age={0}, proxy-revalidate, public'.format(maxage)
)


Expand Down Expand Up @@ -328,7 +330,7 @@ def notModified(published, request, response, etag=None, lastModified=None):
del response.headers['cache-control']

response.setStatus(304)
return u""
return u''


#
Expand Down Expand Up @@ -422,7 +424,7 @@ def isModified(request, etag=None, lastModified=None):
if (lastModified - ifModifiedSince) > delta_sec:
return True
except TypeError:
logger.exception("Could not compare dates")
logger.exception('Could not compare dates')

# If we expected an ETag and the client didn't give us one, consider
# that an error. This may be more conservative than the spec requires.
Expand Down Expand Up @@ -468,7 +470,7 @@ def checkType(context):
while (
published is not None and
not checkType(published) and
hasattr(published, '__parent__',)
getattr(published, '__parent__')
):
published = published.__parent__

Expand Down Expand Up @@ -622,7 +624,7 @@ def getETag(published, request, keys=(), extraTokens=()):
(published, request), IETagValue, name=key)
if component is None:
logger.warning(
"Could not find value adapter for ETag component %s", key)
'Could not find value adapter for ETag component %s', key)
tokens.append('')
else:
value = component()
Expand Down Expand Up @@ -729,7 +731,7 @@ def getRAMCacheKey(request, etag=None, lastModified=None):
is needed to ensure the key changes when the resource view changes.
"""

resourceKey = "%s%s?%s" % (
resourceKey = '{0}{1}?{2}'.format(
request.get('SERVER_URL', ''),
request.get('PATH_INFO', ''),
request.get('QUERY_STRING', ''),
Expand Down
4 changes: 2 additions & 2 deletions plone/app/caching/purge.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,12 @@ def fieldFilter(field):

yield prefix + '/at_download/' + field.getName()

fieldURL = "%s/%s" % (prefix, field.getName(),)
fieldURL = '{0}/{1}'.format(prefix, field.getName(),)
yield fieldURL

if IImageField.providedBy(field):
for size in field.getAvailableSizes(self.context).keys():
yield "%s_%s" % (fieldURL, size,)
yield '{0}_{1}'.format(fieldURL, size,)

def getAbsolutePaths(self):
return []
Expand Down
Loading

0 comments on commit eb804c1

Please sign in to comment.