Skip to content

Commit

Permalink
Merge pull request #63 from plone/plone.base-overhaul
Browse files Browse the repository at this point in the history
Plone.base overhaul
  • Loading branch information
mauritsvanrees authored May 4, 2022
2 parents 3e869bf + 2ed9526 commit a9ea5d5
Show file tree
Hide file tree
Showing 22 changed files with 440 additions and 481 deletions.
2 changes: 2 additions & 0 deletions news/63.breaking
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
isort, black, pyupgrade. Use plone.base and dependency cleanup.
[jensens]
3 changes: 1 addition & 2 deletions plone/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
# -*- coding: utf-8 -*-
__import__('pkg_resources').declare_namespace(__name__)
__import__("pkg_resources").declare_namespace(__name__)
3 changes: 1 addition & 2 deletions plone/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
# -*- coding: utf-8 -*-
__import__('pkg_resources').declare_namespace(__name__)
__import__("pkg_resources").declare_namespace(__name__)
2 changes: 1 addition & 1 deletion plone/app/registry/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from plone.app.registry.registry import Registry
from plone.app.registry.registry import Registry
1 change: 0 additions & 1 deletion plone/app/registry/browser/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
# -*- coding: utf-8 -*-
49 changes: 21 additions & 28 deletions plone/app/registry/browser/controlpanel.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
from zope.component import getUtility

from plone.autoform.form import AutoExtensibleForm
from plone.registry.interfaces import IRegistry

from z3c.form import form, button

from plone.z3cform import layout
from plone.autoform.form import AutoExtensibleForm

from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.statusmessages.interfaces import IStatusMessage

from z3c.form import button
from z3c.form import form
from zope.component import getUtility
from zope.component.hooks import getSite
from zope.i18nmessageid import MessageFactory

_ = MessageFactory('plone')

_ = MessageFactory("plone")


class RegistryEditForm(AutoExtensibleForm, form.EditForm):
Expand Down Expand Up @@ -46,43 +43,39 @@ class MyForm(RegistryEditForm):

def getContent(self):
return getUtility(IRegistry).forInterface(
self.schema,
prefix=self.schema_prefix)
self.schema, prefix=self.schema_prefix
)

def updateActions(self):
super(RegistryEditForm, self).updateActions()
self.actions['save'].addClass("btn btn-primary")
self.actions['cancel'].addClass("btn btn-secondary")
super().updateActions()
self.actions["save"].addClass("btn btn-primary")
self.actions["cancel"].addClass("btn btn-secondary")

@button.buttonAndHandler(_(u"Save"), name='save')
@button.buttonAndHandler(_("Save"), name="save")
def handleSave(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
self.applyChanges(data)
IStatusMessage(self.request).addStatusMessage(
_(u"Changes saved."),
"info")
IStatusMessage(self.request).addStatusMessage(_("Changes saved."), "info")
self.request.response.redirect(self.request.getURL())

@button.buttonAndHandler(_(u"Cancel"), name='cancel')
@button.buttonAndHandler(_("Cancel"), name="cancel")
def handleCancel(self, action):
IStatusMessage(self.request).addStatusMessage(
_(u"Changes canceled."),
"info")
self.request.response.redirect(u"{0}/{1}".format(
getSite().absolute_url(),
self.control_panel_view
))
IStatusMessage(self.request).addStatusMessage(_("Changes canceled."), "info")
self.request.response.redirect(
f"{getSite().absolute_url()}/{self.control_panel_view}"
)


class ControlPanelFormWrapper(layout.FormWrapper):
"""Use this form as the plone.z3cform layout wrapper to get the control
panel layout.
"""
index = ViewPageTemplateFile('templates/controlpanel_layout.pt')

index = ViewPageTemplateFile("templates/controlpanel_layout.pt")

@property
def control_panel_url(self):
return u"{0}/@@overview-controlpanel".format(getSite().absolute_url())
return f"{getSite().absolute_url()}/@@overview-controlpanel"
15 changes: 7 additions & 8 deletions plone/app/registry/browser/delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,18 @@


class RecordDeleteView(BrowserView):

def __call__(self):
if self.request.REQUEST_METHOD == 'POST':
name = self.request.form.get('name')
if self.request.REQUEST_METHOD == "POST":
name = self.request.form.get("name")
if isinstance(name, list) and len(name) > 0:
name = name[0]
if self.request.form.get('form.buttons.delete'):
if self.request.form.get("form.buttons.delete"):
if name in self.context:
del self.context.records[name]
messages = IStatusMessage(self.request)
messages.add(u"Successfully deleted field %s" % name, type=u"info")
elif self.request.form.get('form.buttons.cancel') and name:
messages.add("Successfully deleted field %s" % name, type="info")
elif self.request.form.get("form.buttons.cancel") and name:
messages = IStatusMessage(self.request)
messages.add(u"Successfully deleted field %s" % name, type=u"info")
messages.add("Successfully deleted field %s" % name, type="info")
return self.request.response.redirect(self.context.absolute_url())
return super(RecordDeleteView, self).__call__()
return super().__call__()
59 changes: 25 additions & 34 deletions plone/app/registry/browser/edit.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
# -*- coding: utf-8 -*-
from Acquisition import ImplicitAcquisitionWrapper
from plone.z3cform import layout
from Products.statusmessages.interfaces import IStatusMessage
from z3c.form import form, field, button
from z3c.form import button
from z3c.form import field
from z3c.form import form
from zope.i18nmessageid import MessageFactory
from zope.interface import implementer
from zope.publisher.interfaces import IPublishTraverse

_ = MessageFactory('plone')

_ = MessageFactory("plone")


class RecordEditForm(form.EditForm):
"""Edit a single record
"""
"""Edit a single record"""

record = None

Expand All @@ -21,46 +22,36 @@ def action(self):
return f"{self.context.absolute_url()}/edit/{self.record.__name__}"

def getContent(self):
return ImplicitAcquisitionWrapper(
{'value': self.record.value},
self.context
)
return ImplicitAcquisitionWrapper({"value": self.record.value}, self.context)

def update(self):
self.fields = field.Fields(self.record.field, )
super(RecordEditForm, self).update()
self.fields = field.Fields(
self.record.field,
)
super().update()

def updateActions(self):
super(RecordEditForm, self).updateActions()
self.actions['save'].addClass("btn btn-primary")
self.actions['cancel'].addClass("btn btn-secondary")
super().updateActions()
self.actions["save"].addClass("btn btn-primary")
self.actions["cancel"].addClass("btn btn-secondary")

@property
def label(self):
return _(
u"Edit record: ${name}",
mapping={'name': self.record.__name__}
)
return _("Edit record: ${name}", mapping={"name": self.record.__name__})

@button.buttonAndHandler(_(u"Save"), name='save')
@button.buttonAndHandler(_("Save"), name="save")
def handleSave(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
self.record.value = data['value']
IStatusMessage(self.request).addStatusMessage(
_(u"Changes saved."),
"info"
)
self.record.value = data["value"]
IStatusMessage(self.request).addStatusMessage(_("Changes saved."), "info")
self.request.response.redirect(self.context.absolute_url())

@button.buttonAndHandler(_(u"Cancel"), name='cancel')
@button.buttonAndHandler(_("Cancel"), name="cancel")
def handleCancel(self, action):
IStatusMessage(self.request).addStatusMessage(
_(u"Edit cancelled."),
"info"
)
IStatusMessage(self.request).addStatusMessage(_("Edit cancelled."), "info")
self.request.response.redirect(self.context.absolute_url())


Expand All @@ -69,14 +60,14 @@ class RecordEditView(layout.FormWrapper):
form = RecordEditForm

def __init__(self, context, request):
super(RecordEditView, self).__init__(context, request)
self.request['disable_border'] = True
super().__init__(context, request)
self.request["disable_border"] = True

def publishTraverse(self, request, name):
path = self.request['TraversalRequestNameStack'] + [name]
path = self.request["TraversalRequestNameStack"] + [name]
path.reverse()
key = '/'.join(path)
del self.request['TraversalRequestNameStack'][:]
key = "/".join(path)
del self.request["TraversalRequestNameStack"][:]
record = self.context.records[key]
self.record = record
self.form_instance.record = record
Expand Down
62 changes: 29 additions & 33 deletions plone/app/registry/browser/exportxml.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
# -*- coding: utf-8 -*-
from lxml import etree
from plone.registry.interfaces import IRegistry
from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.component import getUtility

import os
import six


_current_dir = os.path.dirname(__file__)

Expand All @@ -23,27 +22,27 @@ class RegistryExporterView(BrowserView):
"""

template = ViewPageTemplateFile(
os.path.join(_current_dir, 'templates', 'exportxml.pt')
os.path.join(_current_dir, "templates", "exportxml.pt")
)

def __call__(self):
interface = self.request.form.get('interface', None)
name = self.request.form.get('name', None)
interface = self.request.form.get("interface", None)
name = self.request.form.get("name", None)
if not interface and not name:
return self.template()
return self.export(sinterface=interface, sname=name)

def interfaces(self):
prefixes = []
registry = getUtility(IRegistry)
baseurl = '{0}/@@configuration_registry_export_xml?interface='.format(
baseurl = "{}/@@configuration_registry_export_xml?interface=".format(
self.context.absolute_url()
)
for record in registry.records.values():
if record.interfaceName is None:
continue
name = record.interfaceName
url = '{0}{1}'.format(baseurl, record.interfaceName)
url = f"{baseurl}{record.interfaceName}"
pair = (name, url)
if pair not in prefixes:
prefixes.append(pair)
Expand All @@ -53,22 +52,22 @@ def interfaces(self):
def prefixes(self):
prefixes = []
registry = getUtility(IRegistry)
baseurl = '{0}/@@configuration_registry_export_xml?'.format(
baseurl = "{}/@@configuration_registry_export_xml?".format(
self.context.absolute_url()
)
for record in registry.records.values():
if record.interfaceName == record.__name__:
continue

def add_split(part):
url = '{0}name={1}'.format(baseurl, part)
url = f"{baseurl}name={part}"
pair = (part, url)
if pair not in prefixes:
prefixes.append(pair)
if part.rfind('/') > part.rfind('.'):
new_parts = part.rsplit('/', 1)
if part.rfind("/") > part.rfind("."):
new_parts = part.rsplit("/", 1)
else:
new_parts = part.rsplit('.', 1)
new_parts = part.rsplit(".", 1)
if len(new_parts) > 1:
add_split(new_parts[0])

Expand All @@ -77,7 +76,7 @@ def add_split(part):

def export(self, sinterface=None, sname=None):
registry = getUtility(IRegistry)
root = etree.Element('registry')
root = etree.Element("registry")
values = {} # full prefix to valuerecord
interface2values = {}
interface2prefix = {}
Expand All @@ -86,54 +85,51 @@ def export(self, sinterface=None, sname=None):
continue
if sname and not record.__name__.startswith(sname):
continue
prefix, value_key = record.__name__.rsplit('.', 1)
xmlvalue = etree.Element('value')
prefix, value_key = record.__name__.rsplit(".", 1)
xmlvalue = etree.Element("value")
if record.value is None:
continue
if isinstance(record.value, (list, tuple)):
for element in record.value:
xmlel = etree.SubElement(xmlvalue, 'element')
xmlel = etree.SubElement(xmlvalue, "element")
xmlel.text = element
elif isinstance(record.value, bool):
xmlvalue.text = 'True' if record.value else 'False'
elif isinstance(record.value, six.string_types):
xmlvalue.text = "True" if record.value else "False"
elif isinstance(record.value, str):
xmlvalue.text = record.value
else:
xmlvalue.text = str(record.value)

if record.interfaceName:
xmlvalue.attrib['key'] = value_key
xmlvalue.attrib["key"] = value_key
if record.interfaceName not in interface2values:
interface2values[record.interfaceName] = []
interface2values[record.interfaceName].append(record.__name__)
interface2prefix[record.interfaceName] = prefix
values[record.__name__] = xmlvalue

for ifname in sorted(interface2values):
xmlrecord = etree.SubElement(root, 'records')
xmlrecord.attrib['interface'] = ifname
xmlrecord.attrib['prefix'] = interface2prefix[ifname]
xmlrecord = etree.SubElement(root, "records")
xmlrecord.attrib["interface"] = ifname
xmlrecord.attrib["prefix"] = interface2prefix[ifname]
for value in sorted(interface2values[ifname]):
xmlrecord.append(values.pop(value))
for name, xmlvalue in values.items():
xmlrecord = etree.SubElement(root, 'records')
xmlrecord.attrib['prefix'] = name
xmlrecord = etree.SubElement(root, "records")
xmlrecord.attrib["prefix"] = name
xmlrecord.append(xmlvalue)

self.request.response.setHeader('Content-Type', 'text/xml')
filename = ''
self.request.response.setHeader("Content-Type", "text/xml")
filename = ""
if sinterface:
filename += sinterface
if sinterface and sname:
filename += '_-_'
filename += "_-_"
if sname:
filename += sname
self.request.response.setHeader(
'Content-Disposition',
'attachment; filename={0}.xml'.format(filename))
"Content-Disposition", f"attachment; filename={filename}.xml"
)
return etree.tostring(
root,
pretty_print=True,
xml_declaration=True,
encoding='UTF-8'
root, pretty_print=True, xml_declaration=True, encoding="UTF-8"
)
Loading

0 comments on commit a9ea5d5

Please sign in to comment.