code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
============= Generic Forms ============= The `browser:form` allows the developer to use the form and widget framework without relying on a particular context object. Instead, it is up to the developer to implement two simple methods that handle the retrieval and mutation of the data in form of a dictionary. But I am getting ahead of myself. We first need to define a schema that we would like to use for our form: >>> import zope.interface >>> import zope.schema >>> class IName(zope.interface.Interface): ... """The name of a person.""" ... ... first = zope.schema.TextLine( ... title=u"First Name", ... required=False) ... ... last = zope.schema.TextLine( ... title=u"Last Name", ... required=True) Now we are almost ready to create the form view. But first we have to create a class that knows how to get and set values for the fields described by the schema. The system calls for a class (that will be used as a mixin) that implements a method called `getData()` that returns a dictionary mapping field names to values and a second method called `setData(data)` that takes a data dictionary as argument and handles the data in any way fit. In our case, let's store the data in a global attribute called name: >>> name = ['John', 'Doe'] >>> class DataHandler(object): ... ... def getData(self): ... global name ... return {'first': name[0], 'last': name[1]} ... ... def setData(self, data): ... global name ... name[0] = data['first'] ... name[1] = data['last'] ... return u"Saved changes." We now imitate the form-directive's behavior and create the view class: >>> from zope.app.form.browser.formview import FormView >>> View = type('View', (DataHandler, FormView), {'schema': IName}) To initialize the view, you still need a context and a request. The context is useful because it gives you a location, so that you can look up local components to store the data, such as the principal annotations. In our case we do not care about the context, so it will be just `None`: >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> view = View(None, request) We can now look at the widgets and see that the data was correctly loaded: >>> print(view.first_widget()) <input class="textType" id="field.first" name="field.first" size="20" type="text" value="John" /> >>> print(view.last_widget()) <input class="textType" id="field.last" name="field.last" size="20" type="text" value="Doe" /> Now when a request is sent in, the data is transmitted in the form >>> request.form['field.first'] = u'Stephan' >>> request.form['field.last'] = u'Richter' >>> request.form['UPDATE_SUBMIT'] = u'' and as soon as the `update()` method is called >>> print(view.update()) Saved changes. the global name variable is changed: >>> print(name[0]) Stephan >>> print(name[1]) Richter And that's pretty much all that there is to it. The rest behaves exactly like an edit form, from which the form view was derived. Of course you can also completely overwrite the `update()` method like for the edit view removing the requirement to implement the `getData()` and `setData()` methods. Using the `browser:form` directive ================================== Let's now see how the form directive works. The first task is to load the necessary meta-configuration: >>> from zope.configuration import xmlconfig >>> import zope.component >>> context = xmlconfig.file('meta.zcml', zope.component) >>> import zope.app.form.browser >>> context = xmlconfig.file('meta.zcml', zope.app.form.browser, context) Before we run the directive, make sure that no view exists: >>> class IAnything(zope.interface.Interface): ... pass >>> @zope.interface.implementer(IAnything) ... class Anything(object): ... pass >>> from zope.publisher.browser import TestRequest >>> from zope.component import queryMultiAdapter >>> queryMultiAdapter((Anything(), TestRequest()), name='name.html') Now that we know that the view did not exist before the registration, let's execute the form directive: >>> import sys >>> sys.modules['form'] = type( ... 'Module', (), ... {'DataHandler': DataHandler, ... 'IAnything': IAnything, ... 'IName': IName})() >>> context = xmlconfig.string(''' ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:browser="http://namespaces.zope.org/browser" ... i18n_domain="zope"> ... ... <view ... type="zope.publisher.interfaces.browser.IBrowserRequest" ... for="zope.schema.interfaces.ITextLine" ... provides="zope.formlib.interfaces.IInputWidget" ... factory="zope.app.form.browser.TextWidget" ... permission="zope.Public" ... /> ... ... <browser:form ... for="form.IAnything" ... schema="form.IName" ... class="form.DataHandler" ... name="name.html" ... label="Edit the name" ... fields="first last" ... permission="zope.Public" /> ... ... </configure> ... ''', context) and try to look up the view again: >>> queryMultiAdapter( ... (Anything(), TestRequest()), name='name.html') #doctest:+ELLIPSIS <zope.browserpage.simpleviewclass.SimpleViewClass from edit.pt ...> Now, if I do not specify my own template, and my class does not overwrite the `update()` method, then the class *must* implement `getData()` and `setData(data)`, otherwise a configuration error is raised: >>> class NewDataHandler(object): ... ... def getData(self): ... return {} >>> sys.modules['form'].NewDataHandler = NewDataHandler >>> xmlconfig.string(''' ... <configure ... xmlns:browser="http://namespaces.zope.org/browser" ... i18n_domain="zope"> ... ... <browser:form ... for="form.IAnything" ... schema="form.IName" ... class="form.NewDataHandler" ... name="name.html" ... label="Edit the name" ... fields="first last" ... permission="zope.Public" /> ... ... </configure> ... ''', context) Traceback (most recent call last): ... ZopeXMLConfigurationError: You must specify a class that implements `getData()` and `setData()`, if you do not overwrite `update()`. File "<string>", line 6.6 zope.configuration.exceptions.ConfigurationError Now we need to clean up afterwards. >>> del sys.modules['form']
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/form.rst
form.rst
"""Browser widgets for items""" __docformat__ = 'restructuredtext' # BBB the implementation has moved to zope.formlib.itemswidgets from zope.formlib.itemswidgets import EXPLICIT_EMPTY_SELECTION from zope.formlib.itemswidgets import ChoiceCollectionDisplayWidget from zope.formlib.itemswidgets import ChoiceCollectionInputWidget from zope.formlib.itemswidgets import ChoiceDisplayWidget from zope.formlib.itemswidgets import ChoiceInputWidget from zope.formlib.itemswidgets import CollectionDisplayWidget from zope.formlib.itemswidgets import CollectionInputWidget from zope.formlib.itemswidgets import DropdownWidget from zope.formlib.itemswidgets import ItemDisplayWidget from zope.formlib.itemswidgets import ItemsEditWidgetBase from zope.formlib.itemswidgets import ItemsMultiDisplayWidget from zope.formlib.itemswidgets import ItemsMultiEditWidgetBase from zope.formlib.itemswidgets import ItemsWidgetBase from zope.formlib.itemswidgets import ListDisplayWidget from zope.formlib.itemswidgets import MultiCheckBoxWidget from zope.formlib.itemswidgets import MultiDataHelper from zope.formlib.itemswidgets import MultiSelectFrozenSetWidget from zope.formlib.itemswidgets import MultiSelectSetWidget from zope.formlib.itemswidgets import MultiSelectWidget from zope.formlib.itemswidgets import OrderedMultiSelectWidget from zope.formlib.itemswidgets import RadioWidget from zope.formlib.itemswidgets import SelectWidget from zope.formlib.itemswidgets import SetDisplayWidget from zope.formlib.itemswidgets import SingleDataHelper from zope.formlib.itemswidgets import TranslationHook __all__ = [ 'ChoiceCollectionDisplayWidget', 'ChoiceCollectionInputWidget', 'ChoiceDisplayWidget', 'ChoiceInputWidget', 'CollectionDisplayWidget', 'CollectionInputWidget', 'DropdownWidget', 'EXPLICIT_EMPTY_SELECTION', 'ItemDisplayWidget', 'ItemsEditWidgetBase', 'ItemsMultiDisplayWidget', 'ItemsMultiEditWidgetBase', 'ItemsWidgetBase', 'ListDisplayWidget', 'MultiCheckBoxWidget', 'MultiDataHelper', 'MultiSelectFrozenSetWidget', 'MultiSelectSetWidget', 'MultiSelectWidget', 'OrderedMultiSelectWidget', 'RadioWidget', 'SelectWidget', 'SetDisplayWidget', 'SingleDataHelper', 'TranslationHook', ]
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/itemswidgets.py
itemswidgets.py
"""Form and Widget specific 'browser' ZCML namespace interfaces""" __docformat__ = 'restructuredtext' from zope.browsermenu.field import MenuField 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.configuration.fields import PythonIdentifier from zope.configuration.fields import Tokens from zope.interface import Interface from zope.schema import Id from zope.schema import TextLine from zope.security.zcml import Permission class ICommonInformation(Interface): """ Common information for all successive directives """ name = TextLine( title="Name", description="The name of the generated view.", required=True ) schema = GlobalInterface( title="Schema", description="The schema from which the form is generated.", required=True ) for_ = GlobalInterface( title="Interface", description=""" The interface this page (view) applies to. The view will be for all objects that implement this interface. The schema is used if the for attribute is not specified. If the for attribute is specified, then the objects views must implement or be adaptable to the schema.""", required=False ) permission = Permission( title="Permission", description="The permission needed to use the view.", required=True ) layer = GlobalInterface( title="Layer", description="The later the view is in. Default: 'default'", required=False ) template = Path( title="Template", description="An alternate template to use for the form.", required=False ) class_ = GlobalObject( title="Class", description=""" A class to provide custom widget definitions or methods to be used by a custom template. This class is used as a mix-in class. As a result, it needn't subclass any special classes, such as BrowserView.""", required=False ) class ICommonFormInformation(ICommonInformation): """ Common information for browser forms """ label = MessageID( title="Label", description="A label to be used as the heading for the form.", required=False ) menu = MenuField( title="The browser menu to include the form in.", description=""" Many views are included in menus. It's convenient to name the menu in the page directive, rather than having to give a separate menuItem directive.""", required=False ) title = MessageID( title="Menu title", description="The browser menu label for the form.", required=False ) fields = Tokens( title="Fields", description=""" Here you can specify the names of the fields you wish to display. The order in this list is also the order the fields will be displayed in. If this attribute is not specified, all schema fields will be displayed in the order specified in the schema itself.""", required=False, value_type=PythonIdentifier() ) class ICommonAddInformation(Interface): """ Common information for add forms """ content_factory = GlobalObject( title="Content factory", description=""" An object to call to create new content objects. This attribute isn't used if a class is specified that implements createAndAdd.""", required=False ) content_factory_id = Id( title="Content factory id", description="A factory id to create new content objects", required=False, ) arguments = Tokens( title="Arguments", description=""" A list of field names to supply as positional arguments to the factory.""", required=False, value_type=PythonIdentifier() ) keyword_arguments = Tokens( title="Keyword arguments", description=""" A list of field names to supply as keyword arguments to the factory.""", required=False, value_type=PythonIdentifier() ) set_before_add = Tokens( title="Set before add", description=""" A list of fields to be assigned to the newly created object before it is added.""", required=False, value_type=PythonIdentifier(), ) set_after_add = Tokens( title="Set after add", description=""" A list of fields to be assigned to the newly created object after it is added.""", required=False, value_type=PythonIdentifier() ) class IFormDirective(ICommonFormInformation): """ Define an automatically generated form. The form directive does nto require the data to be stored in its context, but leaves the storing procedure to the to a method. """ class_ = GlobalObject( title="Class", description=""" A class to provide the `getData()` and `setData()` methods or completely custom methods to be used by a custom template. This class is used as a mix-in class. As a result, it needn't subclass any special classes, such as BrowserView.""", required=True ) class IEditFormDirective(ICommonFormInformation): """ Define an automatically generated edit form The editform directive creates and registers a view for editing an object based on a schema. """ class ISubeditFormDirective(ICommonInformation): """ Define a subedit form """ label = TextLine( title="Label", description="A label to be used as the heading for the form.", required=False ) fulledit_path = TextLine( title="Path (relative URL) to the full edit form", required=False ) fulledit_label = MessageID( title="Label of the full edit form", required=False ) class IAddFormDirective(ICommonFormInformation, ICommonAddInformation): """ Define an automatically generated add form The addform directive creates and registers a view for adding an object based on a schema. Adding an object is a bit trickier than editing an object, because the object the schema applies to isn't available when forms are being rendered. The addform directive provides a customization interface to overcome this difficulty. See zope.app.form.browser.interfaces.IAddFormCustomization. """ description = MessageID( title="A longer description of the add form.", description=""" A UI may display this with the item or display it when the user requests more assistance.""", required=False ) class ISchemaDisplayDirective(ICommonFormInformation): """ Define an automatically generated display form. The schemadisplay directive creates and registers a view for displaying an object based on a schema. """ title = MessageID( title="The browser menu label for the edit form", description="This attribute defaults to 'Edit'.", required=False ) class IWidgetSubdirective(Interface): """Register custom widgets for a form. This directive allows you to quickly generate custom widget directives for a form. Besides the two required arguments, field and class, you can specify any amount of keyword arguments, e.g. style='background-color:#fefefe;'. The keywords will be stored as attributes on the widget instance. To see which keywords are sensible, you should look at the code of the specified widget class. """ field = TextLine( title="Field Name", description=""" The name of the field/attribute/property for which this widget will be used.""", required=True, ) class_ = GlobalObject( title="Widget Class", description="""The class that will create the widget.""", required=False, ) # Arbitrary keys and values are allowed to be passed to the CustomWidget. IWidgetSubdirective.setTaggedValue('keyword_arguments', True)
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/metadirectives.py
metadirectives.py
"""Support for display-only pages based on schema.""" __docformat__ = 'restructuredtext' import zope.component from zope.browserpage import ViewPageTemplateFile from zope.browserpage.simpleviewclass import SimpleViewClass from zope.interface import Interface from zope.publisher.browser import BrowserView from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.schema import getFieldNamesInOrder from zope.security.checker import NamesChecker from zope.security.checker import defineChecker from zope.app.form.utility import setUpDisplayWidgets class DisplayView(BrowserView): """Simple display-view base class. Subclasses should provide a `schema` attribute defining the schema to be displayed. """ errors = () update_status = '' label = '' # Fall-back field names computes from schema fieldNames = property(lambda self: getFieldNamesInOrder(self.schema)) def __init__(self, context, request): super().__init__(context, request) self._setUpWidgets() def _setUpWidgets(self): self.adapted = self.schema(self.context) setUpDisplayWidgets(self, self.schema, source=self.adapted, names=self.fieldNames) def setPrefix(self, prefix): for widget in self.widgets(): widget.setPrefix(prefix) def widgets(self): return [getattr(self, name+'_widget') for name in self.fieldNames] def DisplayViewFactory(name, schema, label, permission, layer, template, default_template, bases, for_, fields, fulledit_path=None, fulledit_label=None): class_ = SimpleViewClass(template, used_for=schema, bases=bases, name=name) class_.schema = schema class_.label = label class_.fieldNames = fields class_.fulledit_path = fulledit_path if fulledit_path and (fulledit_label is None): fulledit_label = "Full display" class_.fulledit_label = fulledit_label class_.generated_form = ViewPageTemplateFile(default_template) defineChecker(class_, NamesChecker(("__call__", "__getitem__", "browserDefault"), permission)) if layer is None: layer = IDefaultBrowserLayer sm = zope.component.getGlobalSiteManager() sm.registerAdapter(class_, (for_, layer), Interface, name)
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/schemadisplay.py
schemadisplay.py
"""Add Form View class""" __docformat__ = 'restructuredtext' import sys import zope.component from zope.browserpage import ViewPageTemplateFile from zope.browserpage.simpleviewclass import SimpleViewClass from zope.component.interfaces import IFactory from zope.event import notify from zope.formlib.interfaces import IInputWidget from zope.formlib.interfaces import WidgetsError from zope.interface import Interface from zope.lifecycleevent import Attributes from zope.lifecycleevent import ObjectCreatedEvent from zope.lifecycleevent import ObjectModifiedEvent from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.schema.interfaces import ValidationError from zope.security.checker import NamesChecker from zope.security.checker import defineChecker from zope.app.form.browser.editview import EditView from zope.app.form.browser.i18n import _ from zope.app.form.browser.submit import Update from zope.app.form.utility import getWidgetsData from zope.app.form.utility import setUpWidgets class AddView(EditView): """Simple edit-view base class. Subclasses should provide a schema attribute defining the schema to be edited. """ def _setUpWidgets(self): setUpWidgets(self, self.schema, IInputWidget, names=self.fieldNames) def update(self): if self.update_status is not None: # We've been called before. Just return the previous result. return self.update_status if Update in self.request: self.update_status = '' try: data = getWidgetsData(self, self.schema, names=self.fieldNames) self.createAndAdd(data) except WidgetsError as errors: self.errors = errors self.update_status = _("An error occurred.") return self.update_status self.request.response.redirect(self.nextURL()) return self.update_status def create(self, *args, **kw): """Do the actual instantiation.""" return self._factory(*args, **kw) def createAndAdd(self, data): """Add the desired object using the data in the data argument. The data argument is a dictionary with the data entered in the form. """ args = [] if self._arguments: for name in self._arguments: args.append(data[name]) kw = {} if self._keyword_arguments: for name in self._keyword_arguments: if name in data: kw[str(name)] = data[name] content = self.create(*args, **kw) errors = [] if self._set_before_add: adapted = self.schema(content) for name in self._set_before_add: if name in data: field = self.schema[name] try: field.set(adapted, data[name]) except ValidationError: errors.append(sys.exc_info()[1]) if errors: raise WidgetsError(*errors) notify(ObjectCreatedEvent(content)) content = self.add(content) if self._set_after_add: adapted = self.schema(content) for name in self._set_after_add: if name in data: if data[name] is not None: field = self.schema[name] try: field.set(adapted, data[name]) except ValidationError: errors.append(sys.exc_info()[1]) # We have modified the object, so we need to publish an # object-modified event: description = Attributes(self.schema, *self._set_after_add) notify(ObjectModifiedEvent(content, description)) if errors: raise WidgetsError(*errors) return content def add(self, content): return self.context.add(content) def nextURL(self): return self.context.nextURL() # helper for factory resp. content_factory handling def _getFactory(self): # get factory or factory id factory = self.__dict__.get('_factory_or_id', self._factory_or_id) if type(factory) is str: # factory id return zope.component.getUtility(IFactory, factory, self.context) else: return factory def _setFactory(self, value): self.__dict__['_factory_or_id'] = value def AddViewFactory(name, schema, label, permission, layer, template, default_template, bases, for_, fields, content_factory, arguments, keyword_arguments, set_before_add, set_after_add): class_ = SimpleViewClass( template, used_for=schema, bases=bases, name=name) class_.schema = schema class_.label = label class_.fieldNames = fields class_._factory_or_id = content_factory class_._factory = property(_getFactory, _setFactory) class_._arguments = arguments class_._keyword_arguments = keyword_arguments class_._set_before_add = set_before_add class_._set_after_add = set_after_add class_.generated_form = ViewPageTemplateFile(default_template) defineChecker(class_, NamesChecker( ("__call__", "__getitem__", "browserDefault", "publishTraverse"), permission, ) ) if layer is None: layer = IDefaultBrowserLayer s = zope.component.getGlobalSiteManager() s.registerAdapter(class_, (for_, layer), Interface, name)
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/add.py
add.py
"""Browser widgets""" __docformat__ = 'restructuredtext' # the implementation of widgets has moved to zope.formlib.widgets # import directly from there instead. from zope.formlib.widget import BrowserWidget from zope.formlib.widget import DisplayWidget from zope.formlib.widget import UnicodeDisplayWidget from zope.formlib.widgets import ASCIIAreaWidget from zope.formlib.widgets import ASCIIDisplayWidget from zope.formlib.widgets import ASCIIWidget from zope.formlib.widgets import BooleanDropdownWidget from zope.formlib.widgets import BooleanRadioWidget from zope.formlib.widgets import BooleanSelectWidget from zope.formlib.widgets import BytesAreaWidget from zope.formlib.widgets import BytesDisplayWidget from zope.formlib.widgets import BytesWidget from zope.formlib.widgets import CheckBoxWidget from zope.formlib.widgets import ChoiceCollectionDisplayWidget from zope.formlib.widgets import ChoiceCollectionInputWidget from zope.formlib.widgets import ChoiceDisplayWidget from zope.formlib.widgets import ChoiceInputWidget from zope.formlib.widgets import CollectionDisplayWidget from zope.formlib.widgets import CollectionInputWidget from zope.formlib.widgets import DateDisplayWidget from zope.formlib.widgets import DateI18nWidget from zope.formlib.widgets import DatetimeDisplayWidget from zope.formlib.widgets import DatetimeI18nWidget from zope.formlib.widgets import DatetimeWidget from zope.formlib.widgets import DateWidget from zope.formlib.widgets import DecimalWidget from zope.formlib.widgets import DropdownWidget from zope.formlib.widgets import FileWidget from zope.formlib.widgets import FloatWidget from zope.formlib.widgets import IntWidget from zope.formlib.widgets import ItemDisplayWidget from zope.formlib.widgets import ItemsMultiDisplayWidget from zope.formlib.widgets import ListDisplayWidget from zope.formlib.widgets import ListSequenceWidget from zope.formlib.widgets import MultiCheckBoxWidget from zope.formlib.widgets import MultiSelectFrozenSetWidget from zope.formlib.widgets import MultiSelectSetWidget from zope.formlib.widgets import MultiSelectWidget from zope.formlib.widgets import ObjectWidget from zope.formlib.widgets import OrderedMultiSelectWidget from zope.formlib.widgets import PasswordWidget from zope.formlib.widgets import RadioWidget from zope.formlib.widgets import SelectWidget from zope.formlib.widgets import SequenceDisplayWidget from zope.formlib.widgets import SequenceWidget from zope.formlib.widgets import SetDisplayWidget from zope.formlib.widgets import TextAreaWidget from zope.formlib.widgets import TextWidget from zope.formlib.widgets import TupleSequenceWidget from zope.formlib.widgets import URIDisplayWidget __all__ = [ 'BrowserWidget', 'DisplayWidget', 'UnicodeDisplayWidget', 'TextWidget', 'BytesWidget', 'TextAreaWidget', 'BytesAreaWidget', 'PasswordWidget', 'FileWidget', 'ASCIIWidget', 'ASCIIAreaWidget', 'IntWidget', 'FloatWidget', 'DecimalWidget', 'DatetimeWidget', 'DateWidget', 'DatetimeI18nWidget', 'DateI18nWidget', 'DatetimeDisplayWidget', 'DateDisplayWidget', 'BytesDisplayWidget', 'ASCIIDisplayWidget', 'URIDisplayWidget', 'CheckBoxWidget', 'BooleanRadioWidget', 'BooleanSelectWidget', 'BooleanDropdownWidget', 'ItemDisplayWidget', 'ItemsMultiDisplayWidget', 'SetDisplayWidget', 'ListDisplayWidget', 'ChoiceDisplayWidget', 'ChoiceInputWidget', 'CollectionDisplayWidget', 'CollectionInputWidget', 'ChoiceCollectionDisplayWidget', 'ChoiceCollectionInputWidget', 'SelectWidget', 'DropdownWidget', 'RadioWidget', 'MultiSelectWidget', 'MultiSelectSetWidget', 'MultiSelectFrozenSetWidget', 'MultiCheckBoxWidget', 'OrderedMultiSelectWidget', 'SequenceWidget', 'TupleSequenceWidget', 'ListSequenceWidget', 'SequenceDisplayWidget', 'ObjectWidget', ]
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/__init__.py
__init__.py
==================== Internationalization ==================== Forms are fully internationalized. The field names, descriptions, labels, and hints are all automatically translated if they are made i18n messages in the schema. Let's take this simple add form... >>> print(http(r""" ... GET /addfieldcontent.html HTTP/1.1 ... """, handle_errors=False)) HTTP/1.1 200 Ok ... with an error... >>> print(http(r""" ... POST /addfieldcontent.html HTTP/1.1 ... Content-Length: 670 ... Content-Type: multipart/form-data; boundary=---------------------------19588947601368617292863650127 ... ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="field.title" ... ... ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="field.somenumber" ... ... 0 ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Hinzufxgen ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------19588947601368617292863650127-- ... """, handle_errors=False)) HTTP/1.1 200 Ok ... There are <strong>1</strong> input errors. ... Translated ========== And now the add form in German: >>> print(http(r""" ... GET /addfieldcontent.html HTTP/1.1 ... Accept-Language: de ... """, handle_errors=False)) HTTP/1.1 200 Ok ...Felderinhalt hinzuf... ...Eine kurz...Titel... ...Eine ausf...Beschreibung... ...Irgendeine Zahl... ...Irgendeine Liste... The same with an input error: >>> print(http(r""" ... POST /addfieldcontent.html HTTP/1.1 ... Accept-Language: de ... Content-Length: 670 ... Content-Type: multipart/form-data; boundary=---------------------------19588947601368617292863650127 ... ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="field.title" ... ... ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="field.description" ... ... ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="field.somenumber" ... ... 0 ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="UPDATE_SUBMIT" ... ... Hinzufxgen ... -----------------------------19588947601368617292863650127 ... Content-Disposition: form-data; name="add_input_name" ... ... ... -----------------------------19588947601368617292863650127-- ... """, handle_errors=False)) HTTP/1.1 200 Ok ...Felderinhalt hinzuf... ...<strong>1</strong>... ...Eine kurz...Titel... ...Eine ausf...Beschreibung... ...Irgendeine Zahl... Source widgets ============== Titles of terms are translated by the source widgets. Let's create a source for which the terms create message ids: >>> import zc.sourcefactory.basic >>> from zope.i18nmessageid import MessageFactory >>> _ = MessageFactory('coffee') >>> class Coffees(zc.sourcefactory.basic.BasicSourceFactory): ... def getValues(self): ... return ['arabica', 'robusta', 'liberica', 'excelsa'] ... def getTitle(self, value): ... return _(value, default='Translated %s' % value) >>> import zope.schema >>> from zope.publisher.browser import TestRequest >>> coffee = zope.schema.Choice( ... __name__ = 'coffee', ... title=u"Kinds of coffee beans", ... source=Coffees()) >>> request = TestRequest() >>> import zope.formlib.source >>> widget = zope.formlib.source.SourceDisplayWidget( ... coffee, coffee.source, request) >>> print(widget()) Nothing >>> from zope.formlib.interfaces import IBrowserWidget >>> IBrowserWidget.providedBy(widget) True >>> widget.setRenderedValue('arabica') >>> print(widget()) Translated arabica
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/i18n.rst
i18n.rst
"""Configuration handlers for forms and widgets""" __docformat__ = 'restructuredtext' import os import zope.component from zope.browser.interfaces import IAdding from zope.browsermenu.metaconfigure import menuItemDirective from zope.configuration.exceptions import ConfigurationError from zope.configuration.xmlconfig import ZopeXMLConfigurationError from zope.formlib.interfaces import IDisplayWidget from zope.formlib.interfaces import IInputWidget from zope.formlib.interfaces import IWidgetFactory from zope.formlib.widget import CustomWidgetFactory from zope.interface import implementedBy from zope.publisher.interfaces.browser import IBrowserRequest from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.schema import getFieldNamesInOrder from zope.security.checker import CheckerPublic from zope.app.form.browser.add import AddView from zope.app.form.browser.add import AddViewFactory from zope.app.form.browser.editview import EditView from zope.app.form.browser.editview import EditViewFactory from zope.app.form.browser.formview import FormView from zope.app.form.browser.i18n import _ from zope.app.form.browser.schemadisplay import DisplayView from zope.app.form.browser.schemadisplay import DisplayViewFactory class BaseFormDirective: # to be overriden by the subclasses view = None default_template = None # default basic information for_ = None layer = IDefaultBrowserLayer permission = CheckerPublic template = None class_ = None # default form information title = None label = None menu = None fields = None def __init__(self, _context, **kwargs): self._context = _context for key, value in kwargs.items(): if not (value is None and hasattr(self, key)): setattr(self, key, value) self._normalize() self._widgets = {} def widget(self, _context, field, **kw): attrs = kw class_ = attrs.pop("class_", None) # Try to do better than accepting the string value by looking through # the interfaces and trying to find the field, so that we can use # 'fromUnicode()' if isinstance(class_, type): ifaces = implementedBy(class_) for name, value in kw.items(): for iface in ifaces: if name in iface: attrs[name] = iface[name].fromUnicode(value) break if class_ is None: # The _default_widget_factory is required to allow the # <widget> directive to be given without a "class" # attribute. This can be used to override some of the # presentational attributes of the widget implementation. class_ = self._default_widget_factory # don't wrap a factory into a factory if IWidgetFactory.providedBy(class_): factory = class_ else: factory = CustomWidgetFactory(class_, **attrs) self._widgets[field+'_widget'] = factory def _processWidgets(self): if self._widgets: customWidgetsObject = type('CustomWidgetsMixin', (object,), self._widgets) self.bases = self.bases + (customWidgetsObject,) def _normalize(self): if self.for_ is None: self.for_ = self.schema if self.class_ is None: self.bases = (self.view,) else: self.bases = (self.class_, self.view) if self.template is not None: self.template = os.path.abspath(str(self.template)) if not os.path.isfile(self.template): raise ConfigurationError("No such file", self.template) else: self.template = self.default_template self.names = getFieldNamesInOrder(self.schema) if self.fields: for name in self.fields: if name not in self.names: raise ValueError("Field name is not in schema", name, self.schema) else: self.fields = self.names def _args(self): permission = self.permission if permission == 'zope.Public': # Translate public permission to CheckerPublic permission = CheckerPublic return (self.name, self.schema, self.label, permission, self.layer, self.template, self.default_template, self.bases, self.for_, self.fields) def _discriminator(self): return ('view', self.for_, self.name, IBrowserRequest, self.layer) class AddFormDirective(BaseFormDirective): view = AddView default_template = 'add.pt' for_ = IAdding # default add form information description = None content_factory_id = None content_factory = None arguments = None keyword_arguments = None set_before_add = None set_after_add = None def _default_widget_factory(self, field, request): # `field` is a bound field return zope.component.getMultiAdapter( (field, request), IInputWidget) def _handle_menu(self): if self.menu or self.title: if (not self.menu) or (not self.title): raise ValueError("If either menu or title are specified, " "they must both be specified") # Add forms are really for IAdding components, so do not use # for=self.schema. menuItemDirective( self._context, self.menu, self.for_, '@@' + self.name, self.title, permission=self.permission, layer=self.layer, description=self.description) def _handle_arguments(self, leftover=None): schema = self.schema fields = self.fields arguments = self.arguments keyword_arguments = self.keyword_arguments set_before_add = self.set_before_add set_after_add = self.set_after_add if leftover is None: leftover = fields if arguments: missing = [n for n in arguments if n not in fields] if missing: raise ValueError("Some arguments are not included in the form", missing) optional = [n for n in arguments if not schema[n].required] if optional: raise ValueError("Some arguments are optional, use" " keyword_arguments for them", optional) leftover = [n for n in leftover if n not in arguments] if keyword_arguments: missing = [n for n in keyword_arguments if n not in fields] if missing: raise ValueError( "Some keyword_arguments are not included in the form", missing) leftover = [n for n in leftover if n not in keyword_arguments] if set_before_add: missing = [n for n in set_before_add if n not in fields] if missing: raise ValueError( "Some set_before_add are not included in the form", missing) leftover = [n for n in leftover if n not in set_before_add] if set_after_add: missing = [n for n in set_after_add if n not in fields] if missing: raise ValueError( "Some set_after_add are not included in the form", missing) leftover = [n for n in leftover if n not in set_after_add] self.set_after_add += leftover else: self.set_after_add = leftover def _handle_content_factory(self): if self.content_factory is None: self.content_factory = self.content_factory_id def __call__(self): self._processWidgets() self._handle_menu() self._handle_content_factory() self._handle_arguments() self._context.action( discriminator=self._discriminator(), callable=AddViewFactory, args=self._args()+(self.content_factory, self.arguments, self.keyword_arguments, self.set_before_add, self.set_after_add), ) class EditFormDirectiveBase(BaseFormDirective): view = EditView def _default_widget_factory(self, field, request): # `field` is a bound field if field.readonly: iface = IDisplayWidget else: iface = IInputWidget return zope.component.getMultiAdapter( (field, request), iface) class EditFormDirective(EditFormDirectiveBase): default_template = 'edit.pt' title = _('Edit') def _handle_menu(self): if self.menu: menuItemDirective( self._context, self.menu, self.for_ or self.schema, '@@' + self.name, self.title, permission=self.permission, layer=self.layer) def __call__(self): self._processWidgets() self._handle_menu() self._context.action( discriminator=self._discriminator(), callable=EditViewFactory, args=self._args(), ) class FormDirective(EditFormDirective): view = FormView def __init__(self, _context, **kwargs): super().__init__(_context, **kwargs) attrs = self.class_.__dict__.keys() if 'template' not in kwargs.keys() and 'update' not in attrs and \ ('getData' not in attrs or 'setData' not in attrs): raise ZopeXMLConfigurationError( "You must specify a class that implements `getData()` " "and `setData()`, if you do not overwrite `update()`.", ConfigurationError()) class SubeditFormDirective(EditFormDirectiveBase): default_template = 'subedit.pt' # default subedit form directive fulledit_path = None fulledit_label = None def __call__(self): self._processWidgets() self._context.action( discriminator=self._discriminator(), callable=EditViewFactory, args=self._args()+(self.fulledit_path, self.fulledit_label), ) class SchemaDisplayDirective(EditFormDirective): view = DisplayView default_template = 'display.pt' def __call__(self): self._processWidgets() self._handle_menu() self._context.action( discriminator=self._discriminator(), callable=DisplayViewFactory, args=self._args()+(self.menu,) )
zope.app.form
/zope.app.form-6.0-py3-none-any.whl/zope/app/form/browser/metaconfigure.py
metaconfigure.py
File Synchronization for Zope3 ============================== The FSSync project (zope.app.fssync) provides support for filesystem synchronization of Zope3 content that resides in a ZODB. This package defines a Web-based API with basic support for some standard zope.app content types and the standard security policy. This project is build on top of the more general zope.fssync package which provides object serialization and deserialization tools. If you need a pure Python API which is independent of the ZODB and the Zope3 security machinery you should look at zope.fssync. FSSync includes a command line client that resembles svn or cvs. Type:: bin/zsync help for available commands and further information. If you want to see the zsync client in action you can run the demo application:: bin/demo start Open http://localhost:8080/manage in your browser and login with ``zsync`` as your username and password. Add a ``demo`` folder with some files via the ZMI. After that run the command line client for an initial checkout:: bin/zsync checkout http://zsync:zsync@localhost:8080/demo ./parts/checkout Edit one of the files in the checkout directory and commit the changes:: bin/zsync commit ./parts/checkout The modified file should now be available on the server. SSH --- Zsync now supports communication over ssh in addition to http. ssh urls look like:: zsync+ssh://user:passwd@host:port/path The zsync protocol is the same as over HTTP, it simply is sent via ssh. On the server side, the ssh server can check public keys to enforce security (though the demo server doesn't bother), and is responsible for passing the zsync request to zope and returning the response over ssh. There is an example ssh server in src/zope/app/fssync/demo_server.py To use it, first make sure that zope is running. Then start the server:: sudo bin/demo-ssh-server This starts a demo ssh server on port 2200. The server must be run as root in order to read the ssh host keys. In another terminal use the zsync client to connect to it:: bin/zsync co zsync+ssh://zsync:zsync@localhost:2200/demo parts/co2 This checks out the demo folder into the parts/co2 folder. You should be able to work in the check out normally. Zsync will use ssh to communicate, but will otherwise act normally. Extending zsync --------------- The zsync script is generated by the following part of the buildout.cfg:: [zsync] recipe = zc.recipe.egg eggs = zope.app.fssync entry-points = zsync=zope.app.fssync.main:main If you want to use zope.app.fssync in your own application you propably have to define application specific serializers and deserializers. See zope/app/fssync/fssync.txt for further documentation. You probably also need your own zsync script with additional dependencies. Simply add the necessary eggs to the corresponding buildout snippet of your project.
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/README.txt
README.txt
__docformat__ = 'restructuredtext' import tempfile from zope import interface from zope import component from zope import proxy from zope.security.management import checkPermission from zope.security.checker import ProxyFactory from zope.fssync import synchronizer from zope.fssync import task from zope.fssync import repository from zope.fssync import interfaces from zope.fssync import pickle def getSynchronizer(obj, raise_error=True): """Returns a synchronizer. Looks for a named factory first and returns a default serializer if the dotted class name is not known. Checks also for the permission to call the factory in the context of the given object. Removes the security proxy for the adapted object if a call is allowed and adds a security proxy to the synchronizer instead. """ dn = synchronizer.dottedname(obj.__class__) factory = component.queryUtility(interfaces.ISynchronizerFactory, name=dn) if factory is None: factory = component.queryUtility(interfaces.ISynchronizerFactory) if factory is None: if raise_error: raise synchronizer.MissingSynchronizer(dn) return None checker = getattr(factory, '__Security_checker__', None) if checker is None: return factory(obj) permission = checker.get_permissions['__call__'] if checkPermission(permission, obj): return ProxyFactory(factory(proxy.removeAllProxies(obj))) def toFS(obj, name, location): filesystem = repository.FileSystemRepository() checkout = task.Checkout(getSynchronizer, filesystem) return checkout.perform(obj, name, location) def toSNARF(obj, name): temp = tempfile.TemporaryFile() # TODO: Since we do not know anything about the target system here, # we try to be on the save side. Case-sensivity and NFD should be # determined from the request. snarf = repository.SnarfRepository(temp, case_insensitive=True, enforce_nfd=True) checkout = task.Checkout(getSynchronizer, snarf) checkout.perform(obj, name) return temp
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/syncer.py
syncer.py
__docformat__ = 'restructuredtext' import cPickle from cStringIO import StringIO import zope.interface from zope import location from zope.location.interfaces import ILocation from zope.location.traversing import LocationPhysicallyLocatable from zope.location.tests import TLocation from zope.traversing.interfaces import IContainmentRoot from zope.traversing.interfaces import ITraverser PARENT_MARKER = ".." # We're not ready to use protocol 2 yet; this can be changed when # zope.xmlpickle.ppml gets updated to support protocol 2. PICKLE_PROTOCOL = 1 def dumps(ob): parent = getattr(ob, '__parent__', None) if parent is None: return cPickle.dumps(ob) sio = StringIO() persistent = ParentPersistentIdGenerator(ob) p = cPickle.Pickler(sio, PICKLE_PROTOCOL) p.persistent_id = persistent.id p.dump(ob) data = sio.getvalue() return data def loads(data, location, parent=None): sio = StringIO(data) if parent is None: persistent = PersistentLoader(location) else: persistent = ParentPersistentLoader(location, parent) u = cPickle.Unpickler(sio) u.persistent_load = persistent.load return u.load() class ParentPersistentIdGenerator(object): """ >>> from zope.location.tests import TLocation >>> root = TLocation() >>> zope.interface.directlyProvides(root, IContainmentRoot) >>> o1 = TLocation(); o1.__parent__ = root; o1.__name__ = 'o1' >>> o2 = TLocation(); o2.__parent__ = root; o2.__name__ = 'o2' >>> o3 = TLocation(); o3.__parent__ = o1; o3.__name__ = 'o3' >>> root.o1 = o1 >>> root.o2 = o2 >>> o1.foo = o2 >>> o1.o3 = o3 >>> gen = ParentPersistentIdGenerator(o1) >>> gen.id(root) '..' >>> gen.id(o2) u'/o2' >>> gen.id(o3) >>> gen.id(o1) >>> gen = ParentPersistentIdGenerator(o3) >>> gen.id(root) u'/' """ def __init__(self, top): self.location = top self.parent = getattr(top, "__parent__", None) self.root = LocationPhysicallyLocatable(top).getRoot() def id(self, object): if ILocation.providedBy(object): if location.inside(object, self.location): return None elif object is self.parent: # emit special parent marker return PARENT_MARKER elif location.inside(object, self.root): return LocationPhysicallyLocatable(object).getPath() elif object.__parent__ is None: return None raise ValueError( "object implementing ILocation found outside tree") else: return None class PersistentLoader(object): def __init__(self, context): locatable = LocationPhysicallyLocatable(context) __traceback_info__ = (context, locatable) self.root = locatable.getRoot() self.traverse = ITraverser(self.root).traverse def load(self, path): if path[:1] == u"/": # outside object: if path == "/": return self.root else: return self.traverse(path[1:]) raise ValueError("unknown persistent object reference: %r" % path) class ParentPersistentLoader(PersistentLoader): def __init__(self, context, parent): self.parent = parent PersistentLoader.__init__(self, context) def load(self, path): if path == PARENT_MARKER: return self.parent else: return PersistentLoader.load(self, path) class DataLocation(TLocation): """Sample data container class used in doctests.""" def __init__(self, name, parent, data): self.__name__ = name self.__parent__ = parent if parent is not None: setattr(parent, name, self) self.data = data super(DataLocation, self).__init__()
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/fspickle.py
fspickle.py
import getopt import os.path import sys from zope.fssync.fsutil import Error class Usage(Error): """Subclass for usage error (command-line syntax). You should return an exit status of 2 rather than 1 when catching this. """ class Command(object): def __init__(self, name=None, usage=None): if name is None: name = os.path.basename(sys.argv[0]) self.program = name if usage is None: import __main__ usage = __main__.__doc__ self.helptext = usage self.command_table = {} self.global_options = [] self.local_options = [] self.command = None def addCommand(self, name, function, short="", long="", aliases=""): names = [name] + aliases.split() cmdinfo = short, long.split(), function for n in names: assert n not in self.command_table self.command_table[n] = cmdinfo def main(self, args=None): try: self.realize() self.run() except Usage, msg: self.usage(sys.stderr, msg) self.usage(sys.stderr, 'for help use "%(program)s help"') return 2 except Error, msg: self.usage(sys.stderr, msg) return 1 except SystemExit: raise else: return None def realize(self, args=None): if "help" not in self.command_table: self.addCommand("help", self.help) short, long, func = self.command_table["help"] for alias in ("h", "?"): if alias not in self.command_table: self.addCommand(alias, func, short, " ".join(long)) if args is None: args = sys.argv[1:] self.global_options, args = self.getopt("global", args, "h", ["help"], self.helptext) if not args: raise Usage("missing command argument") self.command = args.pop(0) if self.command not in self.command_table: raise Usage("unrecognized command") cmdinfo = self.command_table[self.command] short, long, func = cmdinfo short = "h" + short long = ["help"] + list(long) self.local_options, self.args = self.getopt(self.command, args, short, long, func.__doc__) def getopt(self, cmd, args, short, long, helptext): try: opts, args = getopt.getopt(args, short, long) except getopt.error, e: raise Usage("%s option error: %s", cmd, e) for opt, arg in opts: if opt in ("-h", "--help"): self.usage(sys.stdout, helptext) sys.exit() return opts, args def run(self): _, _, func = self.command_table[self.command] func(self.local_options, self.args) def usage(self, file, text): text = str(text) try: text = text % {"program": self.program} except: pass print >>file, text def help(self, opts, args): """%(program)s help [COMMAND ...] Display help text. If COMMAND is specified, help text about each named command is displayed, otherwise general help about using %(program)s is shown. """ if not args: self.usage(sys.stdout, self.helptext) else: for cmd in args: if cmd not in self.command_table: print >>sys.stderr, "unknown command:", cmd first = True for cmd in args: cmdinfo = self.command_table.get(cmd) if cmdinfo is None: continue _, _, func = cmdinfo if first: first = False else: print self.usage(sys.stdout, func.__doc__)
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/command.py
command.py
import os import sys import shutil import urllib import filecmp import htmllib import httplib import tempfile import urlparse import formatter from StringIO import StringIO import os.path from os.path import exists, isfile, isdir from os.path import dirname, basename, split, join from os.path import realpath, normcase, normpath from zope.fssync.metadata import Metadata, dump_entries from zope.fssync.fsmerger import FSMerger from zope.fssync.fsutil import Error from zope.fssync import fsutil from zope.fssync.snarf import Snarfer, Unsnarfer from zope.app.fssync.passwd import PasswordManager from zope.app.fssync.ssh import SSHConnection import zope.app.fssync.merge if sys.platform[:3].lower() == "win": DEV_NULL = r".\nul" else: DEV_NULL = "/dev/null" class Network(PasswordManager): """Handle network communication. This class has various methods for managing the root url (which is stored in a file @@Zope/Root) and has a method to send an HTTP(S) request to the root URL, expecting a snarf file back (that's all the application needs). Public instance variables: rooturl -- full root url, e.g. 'http://user:passwd@host:port/path' roottype -- 'http' or 'https' user_passwd -- 'user:passwd' host_port -- 'host:port' rootpath -- '/path' """ def __init__(self, rooturl=None): """Constructor. Optionally pass the root url.""" super(Network, self).__init__() self.setrooturl(rooturl) def loadrooturl(self, target): """Load the root url for the given target. This calls findrooturl() to find the root url for the target, and then calls setrooturl() to set it. If self.findrooturl() can't find a root url, Error() is raised. """ rooturl = self.findrooturl(target) if not rooturl: raise Error("can't find root url for target", target) self.setrooturl(rooturl) def saverooturl(self, target): """Save the root url in the target's @@Zope directory. This writes the file <target>/@@Zope/Root; the directory <target>/@@Zope must already exist. """ if self.rooturl: dir = join(target, "@@Zope") if not exists(dir): os.mkdir(dir) fn = join(dir, "Root") self.writefile(self.rooturl + "\n", fn) def findrooturl(self, target): """Find the root url for the given target. This looks in <target>/@@Zope/Root, and then in the corresponding place for target's parent, and then further ancestors, until the filesystem root is reached. If no root url is found, return None. """ dir = realpath(target) while dir: rootfile = join(dir, "@@Zope", "Root") try: data = self.readfile(rootfile) except IOError: pass else: data = data.strip() if data: return data head, tail = split(dir) if tail in fsutil.unwanted: break dir = head return None def setrooturl(self, rooturl): """Set the root url. If the argument is None or empty, self.rooturl and all derived instance variables are set to None. Otherwise, self.rooturl is set to the argument the broken-down root url is stored in the other instance variables. """ if not rooturl: rooturl = roottype = rootpath = user_passwd = host_port = None else: roottype, rest = urllib.splittype(rooturl) if roottype not in ("http", "https", "zsync+ssh"): raise Error("root url must be 'http', 'https', or 'zsync+ssh'", rooturl) if roottype == "https" and not hasattr(httplib, "HTTPS"): raise Error("https not supported by this Python build") netloc, rootpath = urllib.splithost(rest) if not rootpath: rootpath = "/" user_passwd, host_port = urllib.splituser(netloc) self.rooturl = rooturl self.roottype = roottype self.rootpath = rootpath self.user_passwd = user_passwd self.host_port = host_port def readfile(self, file, mode="r"): # Internal helper to read a file f = open(file, mode) try: return f.read() finally: f.close() def writefile(self, data, file, mode="w"): # Internal helper to write a file f = open(file, mode) try: f.write(data) finally: f.close() def httpreq(self, path, view, datasource=None, content_type="application/x-snarf", expected_type="application/x-snarf"): """Issue an HTTP or HTTPS request. The request parameters are taken from the root url, except that the requested path is constructed by concatenating the path and view arguments. If the optional 'datasource' argument is not None, it should be a callable with a stream argument which, when called, writes data to the stream. In this case, a POST request is issued, and the content-type header is set to the 'content_type' argument, defaulting to 'application/x-snarf'. Otherwise (if datasource is None), a GET request is issued and no input document is sent. If the request succeeds and returns a document whose content-type is 'application/x-snarf', the return value is a tuple (fp, headers) where fp is a non-seekable stream from which the return document can be read, and headers is a case-insensitive mapping giving the response headers. If the request returns an HTTP error, the Error exception is raised. If it returns success (error code 200) but the content-type of the result is not 'application/x-snarf', the Error exception is also raised. In these error cases, if the result document's content-type is a text type (anything starting with 'text/'), the text of the result document is included in the Error exception object; in the specific case that the type is text/html, HTML formatting is removed using a primitive formatter. TODO: This doesn't support proxies or redirect responses. """ # TODO: Don't change the case of the header names; httplib might # not treat them in a properly case-insensitive manner. assert self.rooturl if not path.endswith("/"): path += "/" path = urllib.quote(path) path += view if self.roottype == "https": conn = httplib.HTTPSConnection(self.host_port) elif self.roottype == "zsync+ssh": conn = SSHConnection(self.host_port, self.user_passwd) else: conn = httplib.HTTPConnection(self.host_port) if datasource is None: conn.putrequest("GET", path) else: conn.putrequest("POST", path) conn.putheader("Content-type", content_type) #conn.putheader("Transfer-encoding", "chunked") #XXX Chunking works only with the zserver. Twisted responds with # HTTP error 400 (Bad Request); error document: # Excess 4 bytes sent in chunk transfer mode #We use a buffer as workaround and compute the Content-Length in #advance tmp = tempfile.TemporaryFile('w+b') datasource(tmp) conn.putheader("Content-Length", str(tmp.tell())) if self.user_passwd: if ":" not in self.user_passwd: auth = self.getToken(self.roottype, self.host_port, self.user_passwd) else: auth = self.createToken(self.user_passwd) conn.putheader('Authorization', 'Basic %s' % auth) conn.putheader("Host", self.host_port) conn.putheader("Connection", "close") conn.endheaders() if datasource is not None: #XXX If chunking works again, replace the following lines with # datasource(PretendStream(conn)) # conn.send("0\r\n\r\n") tmp.seek(0) data = tmp.read(1<<16) while data: conn.send(data) data = tmp.read(1<<16) tmp.close() response = conn.getresponse() if response.status != 200: raise Error("HTTP error %s (%s); error document:\n%s", response.status, response.reason, self.slurptext(response.fp, response.msg)) elif expected_type and response.msg["Content-type"] != expected_type: raise Error(self.slurptext(response.fp, response.msg)) else: return response.fp, response.msg def slurptext(self, fp, headers): """Helper to read the result document. This removes the formatting from a text/html document; returns other text documents as-is; and for non-text documents, returns just a string giving the content-type. """ # Too often, we just get HTTP response code 200 (OK), with an # HTML document that explains what went wrong. data = fp.read() ctype = headers.get("Content-type", 'unknown') if ctype == "text/html": s = StringIO() f = formatter.AbstractFormatter(formatter.DumbWriter(s)) p = htmllib.HTMLParser(f) p.feed(data) p.close() return s.getvalue().strip() if ctype.startswith("text/"): return data.strip() return "Content-type: %s" % ctype class PretendStream(object): """Helper class to turn writes into chunked sends.""" def __init__(self, conn): self.conn = conn def write(self, s): self.conn.send("%x\r\n" % len(s)) self.conn.send(s) class DataSource(object): """Helper class to provide a data source for httpreq.""" def __init__(self, head, tail): self.head = head self.tail = tail def __call__(self, f): snf = Snarfer(f) snf.add(join(self.head, self.tail), self.tail) snf.addtree(join(self.head, "@@Zope"), "@@Zope/") class FSSync(object): def __init__(self, metadata=None, network=None, rooturl=None, overwrite_local=False): if metadata is None: metadata = Metadata() if network is None: network = Network() self.metadata = metadata self.network = network self.network.setrooturl(rooturl) self.fsmerger = FSMerger(self.metadata, self.reporter, overwrite_local) def login(self, url=None, user=None): scheme, host_port, user = self.get_login_info(url, user) token = self.network.getToken(scheme, host_port, user) self.network.addToken(scheme, host_port, user, token) def logout(self, url=None, user=None): scheme, host_port, user = self.get_login_info(url, user) if scheme: ok = self.network.removeToken(scheme, host_port, user) else: # remove both, if present ok1 = self.network.removeToken("http", host_port, user) ok2 = self.network.removeToken("https", host_port, user) ok = ok1 or ok2 if not ok: raise Error("matching login info not found") def get_login_info(self, url, user): if url: parts = urlparse.urlsplit(url) scheme = parts[0] host_port = parts[1] if not (scheme and host_port): raise Error( "URLs must include both protocol (http or https)" " and host information") if "@" in host_port: user_passwd, host_port = host_port.split("@", 1) if not user: if ":" in user_passwd: user = user_passwd.split(":", 1)[0] else: user = user_passwd else: self.network.loadrooturl(os.curdir) scheme = self.network.roottype host_port = self.network.host_port if not user: upw = self.network.user_passwd if ":" in upw: user = upw.split(":", 1)[0] else: user = upw if not user: user = raw_input("Username: ").strip() if not user: raise Error("username cannot be empty") return scheme, host_port, user def checkout(self, target): rootpath = self.network.rootpath if not rootpath: raise Error("root url not set") if self.metadata.getentry(target): raise Error("target already registered", target) if exists(target) and not isdir(target): raise Error("target should be a directory", target) fsutil.ensuredir(target) i = rootpath.rfind("/") tail = rootpath[i+1:] tail = tail or "root" fp, headers = self.network.httpreq(rootpath, "@@toFS.snarf") try: self.merge_snarffile(fp, target, tail) finally: fp.close() self.network.saverooturl(target) def multiple(self, args, method, *more): if not args: args = [os.curdir] for target in args: if self.metadata.getentry(target): method(target, *more) else: names = self.metadata.getnames(target) if not names: # just raise Error directly? method(target, *more) # Will raise an exception else: for name in names: method(join(target, name), *more) def commit(self, target, note="fssync_commit", raise_on_conflicts=False): entry = self.metadata.getentry(target) if not entry: raise Error("nothing known about", target) self.network.loadrooturl(target) path = entry["id"] view = "@@fromFS.snarf?note=%s" % urllib.quote(note) if raise_on_conflicts: view += "&raise=1" head, tail = split(realpath(target)) data = DataSource(head, tail) fp, headers = self.network.httpreq(path, view, data) try: self.merge_snarffile(fp, head, tail) finally: fp.close() def checkin(self, target, note="fssync_checkin"): rootpath = self.network.rootpath if not rootpath: raise Error("root url not set") if rootpath == "/": raise Error("root url should name an inferior object") i = rootpath.rfind("/") path, name = rootpath[:i], rootpath[i+1:] if not path: path = "/" if not name: raise Error("root url should not end in '/'") entry = self.metadata.getentry(target) if not entry: raise Error("nothing known about", target) qnote = urllib.quote(note) qname = urllib.quote(name) head, tail = split(realpath(target)) qsrc = urllib.quote(tail) view = "@@checkin.snarf?note=%s&name=%s&src=%s" % (qnote, qname, qsrc) data = DataSource(head, tail) fp, headers = self.network.httpreq(path, view, data, expected_type=None) message = self.network.slurptext(fp, headers) if message: print message def update(self, target): entry = self.metadata.getentry(target) if not entry: raise Error("nothing known about", target) self.network.loadrooturl(target) head, tail = fsutil.split(target) path = entry["id"] fp, headers = self.network.httpreq(path, "@@toFS.snarf") try: self.merge_snarffile(fp, head, tail) finally: fp.close() def merge(self, args): source = args[0] if len(args) == 1: target = os.curdir else: target = args[1] # make sure that we're merging from compatible directories if not self.metadata.getentry(target): names = self.metadata.getnames(target) if len(names) == 1: target = join(target, names[0]) target_entry = self.metadata.getentry(target) if not target_entry: print 'Target must be a fssync checkout directory' return if not self.metadata.getentry(source): names = self.metadata.getnames(source) if len(names) == 1: source = join(source, names[0]) source_entry = self.metadata.getentry(source) if not source_entry: print 'Source must be a fssync checkout directory' return if source_entry[u'id'] != target_entry[u'id']: print 'Cannot merge from %s to %s' % (source_entry[u'id'], target_entry[u'id']) return zope.app.fssync.merge.merge(os.path.abspath(source), os.path.abspath(target), self) print 'All done.' def merge_snarffile(self, fp, localdir, tail): uns = Unsnarfer(fp) tmpdir = tempfile.mktemp() try: os.mkdir(tmpdir) uns.unsnarf(tmpdir) self.fsmerger.merge(join(localdir, tail), join(tmpdir, tail)) self.metadata.flush() print "All done." finally: if isdir(tmpdir): shutil.rmtree(tmpdir) def resolve(self, target): entry = self.metadata.getentry(target) if "conflict" in entry: del entry["conflict"] self.metadata.flush() elif isdir(target): self.dirresolve(target) def dirresolve(self, target): assert isdir(target) names = self.metadata.getnames(target) for name in names: t = join(target, name) e = self.metadata.getentry(t) if e: self.resolve(t) def revert(self, target): entry = self.metadata.getentry(target) if not entry: raise Error("nothing known about", target) flag = entry.get("flag") orig = fsutil.getoriginal(target) if flag == "added": entry.clear() elif flag == "removed": if exists(orig): shutil.copyfile(orig, target) del entry["flag"] elif "conflict" in entry: if exists(orig): shutil.copyfile(orig, target) del entry["conflict"] elif isfile(orig): if filecmp.cmp(target, orig, shallow=False): return shutil.copyfile(orig, target) elif isdir(target): # TODO: how to recurse? self.dirrevert(target) self.metadata.flush() if os.path.isdir(target): target = join(target, "") self.reporter("Reverted " + target) def dirrevert(self, target): assert isdir(target) names = self.metadata.getnames(target) for name in names: t = join(target, name) e = self.metadata.getentry(t) if e: self.revert(t) def reporter(self, msg): if msg[0] not in "/*": print msg.encode('utf-8') # uo: is encode needed here? def diff(self, target, mode=1, diffopts="", need_original=True): assert mode == 1, "modes 2 and 3 are not yet supported" entry = self.metadata.getentry(target) if not entry: raise Error("diff target '%s' doesn't exist", target) if "flag" in entry and need_original: raise Error("diff target '%s' is added or deleted", target) if isdir(target): self.dirdiff(target, mode, diffopts, need_original) return orig = fsutil.getoriginal(target) if not isfile(target): if entry.get("flag") == "removed": target = DEV_NULL else: raise Error("diff target '%s' is file nor directory", target) have_original = True if not isfile(orig): if entry.get("flag") != "added": raise Error("can't find original for diff target '%s'", target) have_original = False orig = DEV_NULL if have_original and filecmp.cmp(target, orig, shallow=False): return print "Index:", target sys.stdout.flush() cmd = ("diff %s %s %s" % (diffopts, quote(orig), quote(target))) os.system(cmd) def dirdiff(self, target, mode=1, diffopts="", need_original=True): assert isdir(target) names = self.metadata.getnames(target) for name in names: t = join(target, name) e = self.metadata.getentry(t) if e and (("flag" not in e) or not need_original): self.diff(t, mode, diffopts, need_original) def add(self, path, type=None, factory=None): entry = self.basicadd(path, type, factory) head, tail = fsutil.split(path) pentry = self.metadata.getentry(head) if not pentry: raise Error("can't add '%s': its parent is not registered", path) if "id" not in pentry: raise Error("can't add '%s': its parent has no 'id' key", path) zpath = fsutil.encode(pentry["id"]) if not zpath.endswith("/"): zpath += "/" zpath += tail entry["id"] = zpath self.metadata.flush() if isdir(path): # Force Entries.xml to exist, even if it wouldn't normally zopedir = join(path, "@@Zope") efile = join(zopedir, "Entries.xml") if not exists(efile): if not exists(zopedir): os.makedirs(zopedir) self.network.writefile(dump_entries({}), efile) print "A", join(path, "") else: print "A", path def basicadd(self, path, type=None, factory=None): if not exists(path): raise Error("nothing known about '%s'", path) entry = self.metadata.getentry(path) if entry: raise Error("object '%s' is already registered", path) entry["flag"] = "added" if type: entry["type"] = type if factory: entry["factory"] = factory return entry def copy(self, src, dst=None, children=True): if not exists(src): raise Error("%s does not exist" % src) dst = dst or '' if (not dst) or isdir(dst): target_dir = dst target_name = basename(os.path.abspath(src)) else: target_dir, target_name = os.path.split(dst) if target_dir: if not exists(target_dir): raise Error("destination directory does not exist: %r" % target_dir) if not isdir(target_dir): import errno err = IOError(errno.ENOTDIR, "Not a directory", target_dir) raise Error(str(err)) if not self.metadata.getentry(target_dir): raise Error("nothing known about '%s'" % target_dir) srcentry = self.metadata.getentry(src) from zope.fssync import copier if srcentry: # already known to fssync; we need to deal with metadata, # Extra, and Annotations copier = copier.ObjectCopier(self) else: copier = copier.FileCopier(self) copier.copy(src, join(target_dir, target_name), children) def mkdir(self, path): dir, name = split(path) if dir: if not exists(dir): raise Error("directory %r does not exist" % dir) if not isdir(dir): raise Error("%r is not a directory" % dir) else: dir = os.curdir entry = self.metadata.getentry(dir) if not entry: raise Error("know nothing about container for %r" % path) if exists(path): raise Error("%r already exists" % path) os.mkdir(path) self.add(path) def remove(self, path): if exists(path): raise Error("'%s' still exists", path) entry = self.metadata.getentry(path) if not entry: raise Error("nothing known about '%s'", path) zpath = entry.get("id") if not zpath: raise Error("can't remote '%s': its zope path is unknown", path) if entry.get("flag") == "added": entry.clear() else: entry["flag"] = "removed" self.metadata.flush() print "R", path def status(self, target, descend_only=False, verbose=True): entry = self.metadata.getentry(target) flag = entry.get("flag") if isfile(target): if not entry: if not self.fsmerger.ignore(target): print "?", target elif flag == "added": print "A", target elif flag == "removed": print "R(reborn)", target else: original = fsutil.getoriginal(target) if isfile(original): if filecmp.cmp(target, original): if verbose: print "=", target else: print "M", target else: print "M(lost-original)", target elif isdir(target): pname = join(target, "") if not entry: if not descend_only and not self.fsmerger.ignore(target): print "?", pname elif flag == "added": print "A", pname elif flag == "removed": print "R(reborn)", pname elif verbose: print "/", pname if entry: # Recurse down the directory namesdir = {} for name in os.listdir(target): ncname = normcase(name) if ncname != fsutil.nczope: namesdir[ncname] = name for name in self.metadata.getnames(target): ncname = normcase(name) namesdir[ncname] = name ncnames = namesdir.keys() ncnames.sort() for ncname in ncnames: self.status(join(target, namesdir[ncname]), verbose=verbose) elif exists(target): if not entry: if not self.fsmerger.ignore(target): print "?", target elif flag: print flag[0].upper() + "(unrecognized)", target else: print "M(unrecognized)", target else: if not entry: print "nonexistent", target elif flag == "removed": print "R", target elif flag == "added": print "A(lost)", target else: print "lost", target annotations = fsutil.getannotations(target) if isdir(annotations): self.status(annotations, True, verbose=verbose) extra = fsutil.getextra(target) if isdir(extra): self.status(extra, True, verbose=verbose) def quote(s): """Helper to put quotes around arguments passed to shell if necessary.""" if os.name == "posix": meta = "\\\"'*?[&|()<>`#$; \t\n" else: meta = " " needquotes = False for c in meta: if c in s: needquotes = True break if needquotes: if os.name == "posix": # use ' to quote, replace ' by '"'"' s = "'" + s.replace("'", "'\"'\"'") + "'" else: # (Windows) use " to quote, replace " by "" s = '"' + s.replace('"', '""') + '"' return s
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/fssync.py
fssync.py
""" $Id: main.py 73012 2007-03-06 17:16:44Z oestermeier $ """ import os import urlparse from zope.app.fssync.command import Command, Usage from zope.app.fssync.fssync import FSSync from zope.fssync import fsutil def main(): """Main program. The return value is the suggested sys.exit() status code: 0 or None for success 2 for command line syntax errors 1 or other for later errors """ cmd = Command(usage=__doc__) for func, aliases, short, long in command_table: cmd.addCommand(func.__name__, func, short, long, aliases) return cmd.main() def checkout(opts, args): """%(program)s checkout [-u user] URL [TARGETDIR] URL should be of the form ``http://user:password@host:port/path''. Only http and https are supported (and https only where Python has been built to support SSL). This should identify a Zope 3 server; user:password should have management privileges; /path should be the traversal path to an existing object, not including views or skins. The user may be specified using the -u option instead of encoding it in the URL, since the URL syntax for username and password isn't so well known. The password may be omitted; if so, an authentication token stored using '%(program)s login' will be used if available; otherwise you will be propted for the password. TARGETDIR should be a directory; if it doesn't exist, it will be created. The object tree rooted at /path is copied to a subdirectory of TARGETDIR whose name is the last component of /path. TARGETDIR defaults to the current directory. A metadata directory named @@Zope is also created in TARGETDIR. """ if not args: raise Usage("checkout requires a URL argument") rooturl = args[0] if len(args) > 1: target = args[1] if len(args) > 2: raise Usage("checkout requires at most one TARGETDIR argument") else: target = os.curdir user = _getuseroption(opts) if user: parts = list(urlparse.urlsplit(rooturl)) netloc = parts[1] if "@" in netloc: user_passwd, host_port = netloc.split("@", 1) if ":" in user_passwd: u, p = user_passwd.split(":", 1) else: u = user_passwd # only scream if the -u option and the URL disagree: if u != user: raise Usage("-u/--user option and URL disagree on user name") else: # no username in URL; insert parts[1] = "%s@%s" % (user, netloc) rooturl = urlparse.urlunsplit(tuple(parts)) fs = FSSync(rooturl=rooturl) fs.checkout(target) def commit(opts, args): """%(program)s commit [-m message] [-r] [TARGET ...] Commit the TARGET files or directories to the Zope 3 server identified by the checkout command. TARGET defaults to the current directory. Each TARGET is committed separately. Each TARGET should be up-to-date with respect to the state of the Zope 3 server; if not, a detailed error message will be printed, and you should use the update command to bring your working directory in sync with the server. The -m option specifies a message to label the transaction. The default message is 'fssync_commit'. """ message, opts = extract_message(opts, "commit") raise_on_conflicts = False for o, a in opts: if o in ("-r", "--raise-on-conflicts"): raise_on_conflicts = True fs = FSSync(overwrite_local=True) fs.multiple(args, fs.commit, message, raise_on_conflicts) def update(opts, args): """%(program)s update [TARGET ...] Bring the TARGET files or directories in sync with the corresponding objects on the Zope 3 server identified by the checkout command. TARGET defaults to the current directory. Each TARGET is updated independently. This command will merge your changes with changes made on the server; merge conflicts will be indicated by diff3 markings in the file and noted by a 'C' in the update output. """ fs = FSSync() fs.multiple(args, fs.update) def add(opts, args): """%(program)s add [-t TYPE] [-f FACTORY] TARGET ... Add the TARGET files or directories to the set of registered objects. Each TARGET must exist. The next commit will add them to the Zope 3 server. The options -t and -f can be used to set the type and factory of the newly created object; these should be dotted names of Python objects. Usually only the factory needs to be specified. If no factory is specified, the type will be guessed when the object is inserted into the Zope 3 server based on the filename extension and the contents of the data. For example, some common image types are recognized by their contents, and the extensions .pt and .dtml are used to create page templates and DTML templates, respectively. """ type = None factory = None for o, a in opts: if o in ("-t", "--type"): type = a elif o in ("-f", "--factory"): factory = a if not args: raise Usage("add requires at least one TARGET argument") fs = FSSync() for a in args: fs.add(a, type, factory) def copy(opts, args): """%(program)s copy [-l | -R] SOURCE [TARGET] """ recursive = None for o, a in opts: if o in ("-l", "--local"): if recursive: raise Usage("%r conflicts with %r" % (o, recursive)) recursive = False elif o in ("-R", "--recursive"): if recursive is False: raise Usage("%r conflicts with -l" % o) recursive = o if not args: raise Usage("copy requires at least one argument") if len(args) > 2: raise Usage("copy allows at most two arguments") source = args[0] if len(args) == 2: target = args[1] else: target = None if recursive is None: recursive = True else: recursive = bool(recursive) fs = FSSync() fs.copy(source, target, children=recursive) def remove(opts, args): """%(program)s remove TARGET ... Remove the TARGET files or directories from the set of registered objects. No TARGET must exist. The next commit will remove them from the Zope 3 server. """ if not args: raise Usage("remove requires at least one TARGET argument") fs = FSSync() for a in args: fs.remove(a) diffflags = ["-b", "-B", "--brief", "-c", "-C", "--context", "-i", "-u", "-U", "--unified"] def diff(opts, args): """%(program)s diff [diff_options] [TARGET ...] Write a diff listing for the TARGET files or directories to standard output. This shows the differences between the working version and the version seen on the server by the last update. Nothing is printed for files that are unchanged from that version. For directories, a recursive diff is used. Various GNU diff options can be used, in particular -c, -C NUMBER, -u, -U NUMBER, -b, -B, --brief, and -i. """ diffopts = [] mode = 1 need_original = True for o, a in opts: if o == '-1': mode = 1 elif o == '-2': mode = 2 elif o == '-3': mode = 3 elif o == '-N': need_original = False elif o in diffflags: if a: diffopts.append(o + " " + a) else: diffopts.append(o) diffopts = " ".join(diffopts) fs = FSSync() fs.multiple(args, fs.diff, mode, diffopts, need_original) def status(opts, args): """%(program)s status [-v] [--verbose] [TARGET ...] Print brief (local) status for each target, without changing any files or contacting the Zope server. If the -v or --verbose switches are provided, prints a complete list of local files regardless of their status. """ verbose = False for o, a in opts: if o in ('-v', '--verbose'): verbose = True fs = FSSync() fs.multiple(args, fs.status, False, verbose) def checkin(opts, args): """%(program)s checkin [-m message] URL [TARGETDIR] URL should be of the form ``http://user:password@host:port/path''. Only http and https are supported (and https only where Python has been built to support SSL). This should identify a Zope 3 server; user:password should have management privileges; /path should be the traversal path to a non-existing object, not including views or skins. TARGETDIR should be a directory; it defaults to the current directory. The object tree rooted at TARGETDIR is copied to /path. subdirectory of TARGETDIR whose name is the last component of /path. """ message, opts = extract_message(opts, "checkin") if not args: raise Usage("checkin requires a URL argument") rooturl = args[0] if len(args) > 1: target = args[1] if len(args) > 2: raise Usage("checkin requires at most one TARGETDIR argument") else: target = os.curdir fs = FSSync(rooturl=rooturl, overwrite_local=True) fs.checkin(target, message) def login(opts, args): """%(program)s login [-u user] [URL] Save a basic authentication token for a URL that doesn't include a password component. """ _loginout(opts, args, "login", FSSync().login) def logout(opts, args): """%(program)s logout [-u user] [URL] Remove a saved basic authentication token for a URL. """ _loginout(opts, args, "logout", FSSync().logout) def _loginout(opts, args, cmdname, cmdfunc): url = user = None if args: if len(args) > 1: raise Usage("%s allows at most one argument" % cmdname) url = args[0] user = _getuseroption(opts) cmdfunc(url, user) def _getuseroption(opts): user = None for o, a in opts: if o in ("-u", "--user"): if user: raise Usage("-u/--user may only be specified once") user = a return user def mkdir(opts, args): """%(program)s mkdir PATH ... Create new directories in directories that are already known to %(program)s and schedule the new directories for addition. """ fs = FSSync() fs.multiple(args, fs.mkdir) def resolve(opts, args): """%(program)s resolve [PATH ...] Clear any conflict markers associated with PATH. This would allow commits to proceed for the relevant files. """ fs = FSSync() fs.multiple(args, fs.resolve) def revert(opts, args): """%(program)s revert [TARGET ...] Revert changes to targets. Modified files are overwritten by the unmodified copy cached in @@Zope/Original/ and scheduled additions and deletions are de-scheduled. Additions that are de-scheduled do not cause the working copy of the file to be removed. """ fs = FSSync() fs.multiple(args, fs.revert) def merge(opts, args): """%(program)s merge [TARGETDIR] SOURCEDIR Merge changes from one sandbox directory to another. If two directories are specified then the first one is the target and the second is the source. If only one directory is specified, then the target directory is assumed to the be current sandbox. """ if len(args) not in (1,2): raise Usage('Merge requires one or two arguments') fs = FSSync() fs.merge(args) def extract_message(opts, cmd): L = [] message = None msgfile = None for o, a in opts: if o in ("-m", "--message"): if message: raise Usage(cmd + " accepts at most one -m/--message option") message = a elif o in ("-F", "--file"): if msgfile: raise Usage(cmd + " accepts at most one -F/--file option") msgfile = a else: L.append((o, a)) if not message: if msgfile: message = open(msgfile).read() else: message = "fssync_" + cmd elif msgfile: raise Usage(cmd + " requires at most one of -F/--file or -m/--message") return message, L command_table = [ # name is taken from the function name # function, aliases, short opts, long opts (add, "", "f:t:", "factory= type="), (checkin, "", "F:m:", "file= message="), (checkout, "co", "u:", "user="), (commit, "ci", "F:m:r", "file= message= raise-on-conflicts"), (copy, "cp", "lR", "local recursive"), (diff, "di", "bBcC:iNuU:", "brief context= unified="), (login, "", "u:", "user="), (logout, "", "u:", "user="), (merge, "", "", ""), (mkdir, "", "", ""), (remove, "del delete rm", "", ""), (resolve, "resolved","", ""), (revert, "", "", ""), (status, "stat st", "v", "verbose"), (update, "up", "", ""), ]
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/main.py
main.py
import os import os.path import shutil import zope.fssync.fsutil import zope.fssync.copier class MergeCopier(zope.fssync.copier.ObjectCopier): """ Copies from a checkout to another checkout, but doesn't add sync entries in the destination checkout, since they should already be present. """ def copy(self, source, target, children=True): if os.path.isdir(source): shutil.copymode(source, target) self.addEntry(source, target) else: shutil.copy(source, target) self.addEntry(source, target) def _copyspecials(self, source, target, getwhat): src = getwhat(source) if os.path.isdir(src): dst = getwhat(target) zope.fssync.fsutil.ensuredir(dst) copier = MergeCopier(self.sync) for name in self.sync.metadata.getnames(src): copier.copy(os.path.join(src, name), os.path.join(dst, name)) self.sync.metadata.flush() def _syncadd(self, target, type, factory): pass def same_type(path1, path2): if (os.path.isfile(path1) == os.path.isfile(path2) or os.path.isdir(path1) == os.path.isdir(path2)): return True return False def same_file(path1, path2): chunk_size = 32768 f1 = open(path1) f2 = open(path2) while True: s1 = f1.read(chunk_size) s2 = f2.read(chunk_size) if s1 != s2: return False if not s1: break f1.close() f2.close() return True def same_entries(path1, path2, metadata): names1 = metadata.getnames(path1) names2 = metadata.getnames(path2) if names1 != names2: return False for name in names1: f1 = os.path.join(path1, name) f2 = os.path.join(path2, name) if not same_file(f1, f2): return False return True def same_specials(path1, path2, metadata): extra1 = zope.fssync.fsutil.getextra(path1) extra2 = zope.fssync.fsutil.getextra(path2) if os.path.exists(extra1) != os.path.exists(extra2): return False if os.path.exists(extra1) and os.path.exists(extra2): if not same_entries(extra1, extra2, metadata): return False annotations1 = zope.fssync.fsutil.getannotations(path1) annotations2 = zope.fssync.fsutil.getannotations(path2) if os.path.exists(annotations1) != os.path.exists(annotations2): return False if os.path.exists(annotations1) and os.path.exists(annotations2): if not same_entries(annotations1, annotations2, metadata): return False return True def merge(source, target, sync): """ Merge difference from source into target. Treat differences as local changes in target. Don't delete anything from target, only add things from source. Only merge stuff from target if it is actually in the repository (thus don't copy temp files, svn files, etc.) """ metadata = sync.metadata object_copier = zope.fssync.copier.ObjectCopier(sync) merge_copier = MergeCopier(sync) for root, dirs, files in os.walk(source): if '@@Zope' in dirs: dirs.remove('@@Zope') for filename in ([''] + files): source_path = os.path.join(root, filename) if metadata.getentry(source_path): directory = root[len(source) + 1:] target_path = os.path.join(target, directory, filename) if not metadata.getentry(target_path): object_copier.copy(source_path, target_path, False) elif not same_type(source_path, target_path): print 'C %s' % target_path metadata.getentry(target_path)['conflict'] = True metadata.flush() elif os.path.isfile(source_path): if (not same_file(source_path, target_path) or not same_specials(source_path, target_path, metadata)): print 'M %s' % target_path merge_copier.copy(source_path, target_path, False) elif os.path.isdir(source_path): if not same_specials(source_path, target_path, metadata): print 'M %s' % target_path merge_copier.copy(source_path, target_path, False)
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/merge.py
merge.py
import base64 import httplib import os from cStringIO import StringIO from zope.fssync import fsutil DEFAULT_FILENAME = os.path.expanduser(os.path.join("~", ".zsyncpass")) class PasswordManager(object): """Manager for a cache of basic authentication tokens for zsync. This stores tokens in a file, and allows them to be retrieved by the zsync application. The tokens are stored in their 'cooked' form, so while someone could easily decode them or use them to make requests, the casual reader won't be able to use them easily. The cache file is created with restricted permissions, so other users should not be able to read it unless the permissions are modified. """ def __init__(self, filename=None): if not filename: filename = DEFAULT_FILENAME self.authfile = filename def getPassword(self, user, host_port): """Read a password from the user.""" import getpass prompt = "Password for %s at %s: " % (user, host_port) return getpass.getpass(prompt) def createToken(self, user_passwd): """Generate a basic authentication token from 'user:password'.""" return base64.encodestring(user_passwd).strip() def getToken(self, scheme, host_port, user): """Get an authentication token for the user for a specific server. If a corresponding token exists in the cache, that is retured, otherwise the user is prompted for their password and a new token is generated. A new token is not automatically stored in the cache. """ host_port = _normalize_host(scheme, host_port) prefix = [scheme, host_port, user] if os.path.exists(self.authfile): f = open(self.authfile, "r") try: for line in f: line = line.strip() if line[:1] in ("#", ""): continue parts = line.split() if parts[:3] == prefix: return parts[3] finally: f.close() # not in ~/.zsyncpass pw = self.getPassword(user, host_port) user_passwd = "%s:%s" % (user, pw) return self.createToken(user_passwd) def addToken(self, scheme, host_port, user, token): """Add a token to the persistent cache. If a corresponding token already exists in the cache, it is replaced. """ host_port = _normalize_host(scheme, host_port) record = "%s %s %s %s\n" % (scheme, host_port, user, token) if os.path.exists(self.authfile): prefix = [scheme, host_port, user] f = open(self.authfile) sio = StringIO() found = False for line in f: parts = line.split() if parts[:3] == prefix: sio.write(record) found = True else: sio.write(line) f.close() if not found: sio.write(record) text = sio.getvalue() else: text = record f = self.createAuthFile() f.write(text) f.close() def removeToken(self, scheme, host_port, user): """Remove a token from the authentication database. Returns True if a token was found and removed, or False if no matching token was found. If the resulting cache file contains only blank lines, it is removed. """ if not os.path.exists(self.authfile): return False host_port = _normalize_host(scheme, host_port) prefix = [scheme, host_port, user] found = False sio = StringIO() f = open(self.authfile) nonblank = False for line in f: parts = line.split() if parts[:3] == prefix: found = True else: if line.strip(): nonblank = True sio.write(line) f.close() if found: if nonblank: text = sio.getvalue() f = self.createAuthFile() f.write(text) f.close() else: # nothing left in the file but blank lines; remove it os.unlink(self.authfile) return found def createAuthFile(self): """Create the token cache file with the right permissions.""" new = not os.path.exists(self.authfile) if os.name == "posix": old_umask = os.umask(0077) try: f = open(self.authfile, "w", 0600) finally: os.umask(old_umask) else: f = open(self.authfile, "w") if new: f.write(_NEW_FILE_HEADER) return f _NEW_FILE_HEADER = """\ # # Stored authentication tokens for zsync. # Manipulate this data using the 'zsync login' and 'zsync logout'; # read the zsync documentation for more information. # """ def _normalize_host(scheme, host_port): if scheme == "http": return _normalize_port(host_port, httplib.HTTP_PORT) elif scheme == "https": return _normalize_port(host_port, httplib.HTTPS_PORT) elif scheme == "zsync+ssh": return _normalize_port(host_port, None) else: raise fsutil.Error("unsupported URL scheme: %r" % scheme) def _normalize_port(host_port, default_port): if ":" in host_port: host, port = host_port.split(":", 1) try: port = int(port) except ValueError: raise fsutil.Error("invalid port specification: %r" % port) if port <= 0: raise fsutil.Error("invalid port: %d" % port) if port == default_port: host_port = host return host_port.lower()
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/passwd.py
passwd.py
import httplib import logging import socket import paramiko logging.basicConfig(level=logging.DEBUG) class Server(paramiko.ServerInterface): """ Demo server configuration """ def check_channel_request(self, kind, chanid): if kind == 'session': return paramiko.OPEN_SUCCEEDED return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED def check_auth_publickey(self, username, key): # All public keys are accepted for the demo, in a real server # you would probably check public keys against keys of # authorized users. return paramiko.AUTH_SUCCESSFUL def get_allowed_auths(self, username): return 'publickey' class ZsyncHandler(paramiko.SubsystemHandler): """ An example handler that forwards request to a zope server over HTTP. A real server would probably communicate a different way. """ def parse_request(self, channel, transport): f = channel.makefile('r') line = f.readline().strip('\r\n') command, path = line.split(' ', 1) command = command.strip() path = path.strip() headers = {} while transport.is_active: line = f.readline().strip('\r\n') if not line: break key, value = line.split(':', 1) headers[key.strip().lower()] = value.strip() body = '' length = int(headers.get('content-length', 0)) if length: body = f.read(length) return command, path, headers, body def start_subsystem(self, name, transport, channel): command, path, headers, body = self.parse_request(channel, transport) connection = httplib.HTTPConnection('localhost', 8080) if body: connection.request(command, path, body=body, headers=headers) else: connection.request(command, path, headers=headers) response = connection.getresponse() channel.send('HTTP/1.0 %s %s\r\n' % ( response.status, response.reason)) for name, value in response.getheaders(): channel.send('%s: %s\r\n' % (name, value)) channel.send('\r\n') body = response.read() channel.sendall(body) def main(port=2200): # read host keys host_key = paramiko.RSAKey(filename = '/etc/ssh/ssh_host_rsa_key') # start ssh server, install zsync handler sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(None) sock.bind(('', port)) sock.listen(100) while True: client, addr = sock.accept() client.settimeout(None) t = paramiko.Transport(client) t.add_server_key(host_key) t.set_subsystem_handler('zsync', ZsyncHandler) t.start_server(server = Server())
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/demo_server.py
demo_server.py
import getpass import httplib import os.path import socket import paramiko import sys class FileSocket(object): """ Adapts a file to the socket interface for use with http.HTTPResponse """ def __init__(self, file): self.file = file def makefile(self, *args): return self.file class ConfirmationPolicy(paramiko.WarningPolicy, paramiko.RejectPolicy, paramiko.AutoAddPolicy): def _add_key(self, client, hostname, key): paramiko.AutoAddPolicy.missing_host_key(self, client, hostname, key) client.save_host_keys(SSHConnection.key_file_name) def missing_host_key(self, client, hostname, key): paramiko.WarningPolicy.missing_host_key(self, client, hostname, key) answer = raw_input("Are you sure you want to continue connecting (yes/no)? ") yes_no = {'no': paramiko.RejectPolicy.missing_host_key, 'yes': ConfirmationPolicy._add_key,} while answer.lower() not in yes_no: print "Please type 'yes' or 'no'." answer = raw_input("Are you sure you want to continue connecting (yes/no)? ") return yes_no[answer.lower()](self, client, hostname, key) class SSHConnection(object): """ SSH connection that implements parts of the httplib.HTTPConnection interface """ if sys.platform == 'win32': sys_key_file_name = os.path.expanduser('~/ssh/known_hosts') key_file_name = os.path.expanduser('~/ssh/fssync_known_hosts') else: sys_key_file_name = os.path.expanduser('~/.ssh/known_hosts') key_file_name = os.path.expanduser('~/.ssh/fssync_known_hosts') # This and the __new__ method are to ensure that the SSHConnection doesn't # get garbage collected by paramiko too early. clients = {} def __new__(cls, host_port, user_passwd=None): if host_port in cls.clients: return cls.clients[host_port] else: cls.clients[host_port] = object.__new__( cls, host_port, user_passwd) return cls.clients[host_port] def __init__(self, host_port, user_passwd=None): if not hasattr(self, 'headers'): self.headers = {} self.host, self.port = host_port.split(':') self.port = int(self.port) # if username is specified in URL then use it, otherwise # default to local userid if user_passwd: self.remote_user_name = user_passwd.split(':')[0] else: self.remote_user_name = getpass.getuser() self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(ConfirmationPolicy()) self.client.load_system_host_keys(self.sys_key_file_name) try: self.client.load_host_keys(self.key_file_name) except IOError, ioe: # This will get handled later in the ConfirmationPolicy. We can # pass for now. pass try: self.client.connect(self.host, self.port, self.remote_user_name) except paramiko.PasswordRequiredException, pre: password = getpass.getpass("Password to unlock password-protected key? ") self.client.connect( self.host, self.port, self.remote_user_name, password=password) def putrequest(self, method, path): # start zsync subsystem on server self.channel = self.client.get_transport().open_session() self.channel.invoke_subsystem('zsync') self.channelr = self.channel.makefile('rb') self.channelw = self.channel.makefile('wb') # start sending request self.channelw.write('%s %s\r\n' % (method, path)) def putheader(self, name, value): self.channelw.write('%s: %s\r\n' % (name, value)) def endheaders(self): self.channelw.write('\r\n') def send(self, data): self.channelw.write(data) def getresponse(self): response = httplib.HTTPResponse(FileSocket(self.channelr)) response.begin() return response
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/ssh.py
ssh.py
__docformat__ = 'restructuredtext' from zope import interface from zope import component from zope.fssync import synchronizer from zope.fssync import interfaces from zope.app.component.interfaces import ISite from zope.app.component.site import LocalSiteManager class FolderSynchronizer(synchronizer.DirectorySynchronizer): """Adapter to provide an fssync serialization of folders """ interface.implements(interfaces.IDirectorySynchronizer) def iteritems(self): """Compute a folder listing. A folder listing is a list of the items in the folder. It is a combination of the folder contents and the site-manager, if a folder is a site. The adapter will take any mapping: >>> adapter = FolderSynchronizer({'x': 1, 'y': 2}) >>> len(list(adapter.iteritems())) 2 If a folder is a site, then we'll get ++etc++site included. >>> import zope.interface >>> class SiteManager(dict): ... pass >>> class Site(dict): ... zope.interface.implements(ISite) ... ... def getSiteManager(self): ... return SiteManager() >>> adapter = FolderSynchronizer(Site({'x': 1, 'y': 2})) >>> len(list(adapter.iteritems())) 3 """ for key, value in self.context.items(): yield (key, value) if ISite.providedBy(self.context): sm = self.context.getSiteManager() yield ('++etc++site', sm) def __setitem__(self, key, value): """Sets a folder item. Note that the ++etc++site key can also be handled by the LocalSiteManagerGenerator below. >>> from zope.app.folder import Folder >>> folder = Folder() >>> adapter = FolderSynchronizer(folder) >>> adapter[u'test'] = 42 >>> folder[u'test'] 42 Since non-unicode names must be 7bit-ascii we try to convert them to unicode first: >>> adapter['t\xc3\xa4st'] = 43 >>> adapter[u't\xe4st'] 43 """ if key == '++etc++site': self.context.setSiteManager(value) else: if not isinstance(key, unicode): key = unicode(key, encoding='utf-8') self.context[key] = value class LocalSiteManagerGenerator(object): """A generator for a LocalSiteManager. A LocalSiteManager has a special __init__ method. Therefore we must provide a create method. """ interface.implements(interfaces.IObjectGenerator) def create(self, context, name): """Creates a sitemanager in the given context.""" sm = LocalSiteManager(context) context.setSiteManager(sm) return sm
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/folder/adapter.py
adapter.py
__docformat__ = 'restructuredtext' import os import cgi import shutil import tempfile import transaction from zope.traversing.api import getName, getParent, getRoot from zope.publisher.browser import BrowserView from zope.fssync.snarf import Snarfer, Unsnarfer from zope.fssync.metadata import Metadata from zope.app.fssync import syncer from zope.i18nmessageid import ZopeMessageFactory as _ from zope.fssync import task from zope.fssync import repository from zope.app.fssync.syncer import getSynchronizer def snarf_dir(response, dirname): """Helper to snarf a directory to the response.""" temp = tempfile.TemporaryFile() snf = Snarfer(temp) snf.addtree(dirname) temp.seek(0) response.setStatus(200) response.setHeader('Content-type', 'application/x-snarf') return temp class SnarfFile(BrowserView): """View returning a snarfed representation of an object tree. This applies to any object (for="zope.interface.Interface"). """ def show(self): """Return the snarfed response.""" temp = syncer.toSNARF(self.context, getName(self.context) or "root") temp.seek(0) response = self.request.response response.setStatus(200) response.setHeader('Content-type', 'application/x-snarf') return temp # uo: remove # class NewMetadata(Metadata): # """Subclass of Metadata that sets the ``added`` flag in all entries.""" # # def getentry(self, file): # entry = Metadata.getentry(self, file) # if entry: # entry["flag"] = "added" # return entry class SnarfSubmission(BrowserView): """Base class for the commit and checkin views.""" def run(self): self.check_content_type() self.set_transaction() self.parse_args() self.set_note() try: self.make_tempdir() self.set_arguments() #self.make_metadata() #uo: self.unsnarf_body() return self.run_submission() finally: self.remove_tempdir() def check_content_type(self): if not self.request.getHeader("Content-Type") == "application/x-snarf": raise ValueError(_("Content-Type is not application/x-snarf")) def set_transaction(self): self.txn = transaction.get() def parse_args(self): # The query string in the URL didn't get parsed, because we're # getting a POST request with an unrecognized content-type qs = self.request._environ.get("QUERY_STRING") if qs: self.args = cgi.parse_qs(qs) else: self.args = {} def get_arg(self, key): value = self.request.get(key) if value is None: values = self.args.get(key) if values is not None: value = " ".join(values) return value def set_note(self): note = self.get_arg("note") if note: self.txn.note(note) tempdir = None def make_tempdir(self): self.tempdir = tempfile.mktemp() os.mkdir(self.tempdir) def remove_tempdir(self): if self.tempdir and os.path.exists(self.tempdir): shutil.rmtree(self.tempdir) def unsnarf_body(self): stream = self.request.bodyStream.getCacheStream() uns = Unsnarfer(stream) uns.unsnarf(self.tempdir) class SnarfCheckin(SnarfSubmission): """View for checking a new sub-tree into Zope. The input should be a POST request whose data is a snarf archive. This creates a brand new tree and doesn't return anything. """ def run_submission(self): stream = self.request.bodyStream.getCacheStream() snarf = repository.SnarfRepository(stream) checkin = task.Checkin(getSynchronizer, snarf) checkin.perform(self.container, self.name, self.fspath) return "" def set_arguments(self): # Compute self.{name, container, fspath} for checkin() name = self.get_arg("name") if not name: raise ValueError(_("required argument 'name' missing")) src = self.get_arg("src") if not src: src = name self.container = self.context self.name = name self.fspath = src # os.path.join(self.tempdir, src) class SnarfCommit(SnarfSubmission): """View for committing changes to an existing tree. The input should be a POST request whose data is a snarf archive. It returns an updated snarf archive, or a text document with errors. """ def run_submission(self): self.call_checker() if self.errors: return self.send_errors() else: stream = self.request.bodyStream.getCacheStream() snarf = repository.SnarfRepository(stream) c = task.Commit(getSynchronizer, snarf) c.perform(self.container, self.name, self.fspath) return self.send_archive() def set_arguments(self): # Compute self.{name, container, fspath} for commit() self.name = getName(self.context) self.container = getParent(self.context) if self.container is None and self.name == "": # Hack to get loading the root to work self.container = getRoot(self.context) self.fspath = 'root' else: self.fspath = self.name def get_checker(self, raise_on_conflicts=False): from zope.app.fssync import syncer from zope.fssync import repository stream = self.request.bodyStream.getCacheStream() stream.seek(0) snarf = repository.SnarfRepository(stream) return task.Check(getSynchronizer, snarf, raise_on_conflicts=raise_on_conflicts) def call_checker(self): if self.get_arg("raise"): c = self.get_checker(True) else: c = self.get_checker() c.check(self.container, self.name, self.fspath) self.errors = c.errors() def send_errors(self): self.txn.abort() lines = [_("Up-to-date check failed:")] tempdir_sep = os.path.join(self.tempdir, "") # E.g. foo -> foo/ for e in self.errors: lines.append(e.replace(tempdir_sep, "")) lines.append("") self.request.response.setHeader("Content-Type", "text/plain") return "\n".join(lines) def send_archive(self): temp = syncer.toSNARF(self.context, getName(self.context) or "root") temp.seek(0) response = self.request.response response.setStatus(200) response.setHeader('Content-type', 'application/x-snarf') return temp
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/browser/__init__.py
__init__.py
__docformat__ = 'restructuredtext' from zope import interface from zope import component from zope.fssync import synchronizer from zope.fssync import interfaces from zope.app.file import file class FileSynchronizer(synchronizer.Synchronizer): """Adapter to provide a fssync serialization of a file. >>> sample = file.File('some data', 'text/plain') >>> sample.getSize() 9 >>> class Writeable(object): ... def write(self, data): ... print data >>> synchronizer = FileSynchronizer(sample) >>> synchronizer.dump(Writeable()) some data >>> sample.data = 'other data' >>> synchronizer.dump(Writeable()) other data >>> sorted(synchronizer.extras().items()) [('contentType', 'text/plain')] If we deserialize the file we must use chunking in for large files: >>> class Readable(object): ... size = file.MAXCHUNKSIZE + 1 ... data = size * 'x' ... def read(self, bytes=None): ... result = Readable.data[:bytes] ... Readable.data = Readable.data[bytes:] ... return result >>> synchronizer.load(Readable()) >>> len(sample.data) == file.MAXCHUNKSIZE + 1 True >>> sample.getSize() == file.MAXCHUNKSIZE + 1 True """ interface.implements(interfaces.IFileSynchronizer) def metadata(self): md = super(FileSynchronizer, self).metadata() if not self.context.contentType or \ not self.context.contentType.startswith('text'): md['binary'] = 'true' return md def dump(self, writeable): data = self.context._data if isinstance(data, file.FileChunk): chunk = data while chunk: writeable.write(chunk._data) chunk = chunk.next else: writeable.write(self.context.data) def extras(self): return synchronizer.Extras(contentType=self.context.contentType) def load(self, readable): chunk = None size = 0 data = readable.read(file.MAXCHUNKSIZE) while data: size += len(data) next = file.FileChunk(data) if chunk is None: self.context._data = next else: chunk.next = next chunk = next data = readable.read(file.MAXCHUNKSIZE) self.context._size = size if size < file.MAXCHUNKSIZE: self.context.data = self.context.data
zope.app.fssync
/zope.app.fssync-3.6.0.tar.gz/zope.app.fssync-3.6.0/src/zope/app/fssync/file/adapter.py
adapter.py
===================== How FTP Works in Zope ===================== - The FTP server implementation is in `zope.server.ftp.server`. See the README.txt file there. The publisher-based ftp server is in `zope.server.ftp.publisher`. The FTP server gets wired up with a request factory that creates ftp requests with ftp publication objects. - The ftp request object is defined in `zope.publisher.ftp`. - The ftp publication object is defined in `zope.app.publication.ftp`. The publication object gets views to handle ftp requests. It looks up a separate view for each method defined in `zope.publisher.interfaces.ftp.IFTPPublisher`. We provide a single class here that implements all of these methods. The view, in turn, uses adapters for the `IReadFile`, `IWriteFile`, `IReadDirectory`, `IWriteDirectory`, `IFileFactory`, and `IDirectoryFactory`, defined in `zope.filerepresentation.interfaces`.
zope.app.ftp
/zope.app.ftp-3.5.0.tar.gz/zope.app.ftp-3.5.0/src/zope/app/ftp/README.txt
README.txt
__docformat__ = 'restructuredtext' from zope.interface import implements from zope.component import queryAdapter from zope.publisher.interfaces.ftp import IFTPPublisher from zope.security.proxy import removeSecurityProxy from zope.security.checker import canAccess from zope.event import notify from zope.lifecycleevent import ObjectCreatedEvent from zope.dublincore.interfaces import IZopeDublinCore from zope.filerepresentation.interfaces import IReadFile, IWriteFile from zope.filerepresentation.interfaces import IReadDirectory from zope.filerepresentation.interfaces import IWriteDirectory from zope.filerepresentation.interfaces import IFileFactory from zope.filerepresentation.interfaces import IDirectoryFactory from zope.copypastemove.interfaces import IContainerItemRenamer from zope.container.interfaces import IContainer class FTPView(object): implements(IFTPPublisher) def __init__(self, context, request): self.context = context self.request = request self._dir = IReadDirectory(self.context) def publishTraverse(self, request, name): return self._dir[name] def _type(self, file): if IReadDirectory(file, None) is not None: return 'd' else: return 'f' def type(self, name=None): if not name: return 'd' file = self._dir.get(name) if file is not None: return self._type(file) def names(self, filter=None): if filter is None: return list(self._dir) return [name for name in self._dir is filter(name)] def ls(self, filter=None): lsinfo = self._lsinfo dir = self._dir if filter is None: return [lsinfo(name, dir[name]) for name in dir] else: return [lsinfo(name, dir[name]) for name in dir if filter(name)] def _lsinfo(self, name, file): info = {'name': name, 'mtime': self._mtime(file), } f = IReadDirectory(file, None) if f is not None: # It's a directory info['type'] = 'd' info['group_readable'] = hasattr(f, 'get') f = IWriteDirectory(file, None) info['group_writable'] = hasattr(f, '__setitem__') else: # It's a file info['type'] = 'f' f = IReadFile(file, None) if f is not None: size = getattr(f, 'size', self) if size is not self: info['group_readable'] = True info['size'] = size() else: info['group_readable'] = False f = IWriteFile(file, None) info['group_writable'] = hasattr(f, 'write') return info def readfile(self, name, outstream, start = 0, end = None): file = self._dir[name] file = IReadFile(file) data = file.read() if end is not None: data = data[:end] if start: data = data[start:] ## Some output streams don't support unicode data. if isinstance(data, unicode): data = data.encode('utf-8') outstream.write(data) def lsinfo(self, name=None): if not name: return self._lsinfo('.', self) return self._lsinfo(name, self._dir[name]) def _mtime(self, file): ## Getting the modification time is not a big security hole dc = IZopeDublinCore(removeSecurityProxy(file), None) if dc is not None: return dc.modified def mtime(self, name=None): if name: return self._mtime(self._dir[name]) return self._mtime(self) def _size(self, file): file = IReadFile(file, None) if file is not None: return file.size() return 0 def size(self, name=None): if name: return self._size(self._dir[name]) return 0 def mkdir(self, name): dir = IWriteDirectory(self.context, None) factory = IDirectoryFactory(self.context) newdir = factory(name) notify(ObjectCreatedEvent(newdir)) dir[name] = newdir def remove(self, name): dir = IWriteDirectory(self.context, None) del dir[name] def rmdir(self, name): self.remove(name) def rename(self, old, new): dir = IContainer(self.context, None) IContainerItemRenamer(dir).renameItem(old, new) def _overwrite(self, name, instream, start=None, end=None, append=False): file = self._dir[name] if append: reader = IReadFile(file, None) data = reader.read() + instream.read() elif start is not None or end is not None: reader = IReadFile(file, None) data = reader.read() if start is not None: prefix = data[:start] else: prefix = '' start = 0 if end is not None: l = end - start newdata = instream.read(l) data = prefix + newdata + data[start+len(newdata):] else: newdata = instream.read() data = prefix + newdata else: data = instream.read() f = IWriteFile(self._dir[name], None) f.write(data) def writefile(self, name, instream, start=None, end=None, append=False): if name in self._dir: return self._overwrite(name, instream, start, end, append) if end is not None: l = end - (start or 0) data = instream.read(l) else: data = instream.read() if start is not None: data = ('\0' * start) + data # Find the extension ext_start = name.rfind('.') if ext_start > 0: ext = name[ext_start:] else: ext = "." dir = IWriteDirectory(self.context, None) factory = queryAdapter(self.context, IFileFactory, ext) if factory is None: factory = IFileFactory(self.context) newfile = factory(name, '', data) notify(ObjectCreatedEvent(newfile)) dir[name] = newfile def writable(self, name): if name in self._dir: f = IWriteFile(self._dir[name], None) if f is not None: return canAccess(f, 'write') return False d = IWriteDirectory(self.context, None) return canAccess(d, '__setitem__') def readable(self, name): if name in self._dir: f = IReadFile(self._dir[name], None) if f is not None: return canAccess(f, 'read') d = IReadDirectory(self._dir[name], None) if d is not None: return canAccess(d, 'get') return False
zope.app.ftp
/zope.app.ftp-3.5.0.tar.gz/zope.app.ftp-3.5.0/src/zope/app/ftp/__init__.py
__init__.py
======= CHANGES ======= 5.0 (2023-02-07) ---------------- - Drop support for Python 2.7, 3.4, 3.5, 3.6. - Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11. 4.0.0 (2017-05-09) ------------------ - Add support for Python 3.4, 3.5, 3.6 and PyPy. - Fix the ``evolve`` view to use independent transactions instead of committing or aborting the thread-local current transaction. - Drop dependency on ``zope.app.renderer``. - Drop test dependency on ``zope.app.testing``, ``zope.app.zcmlfiles`` and others. 3.7.1 (2012-01-23) ------------------ - Replaced an undeclared test dependency on ``zope.app.authentication`` with ``zope.password``. 3.7.0 (2010-09-18) ------------------ - Depends now on the extracted ``zope.generations``. 3.6.0 (2010-09-17) ------------------ - ``zope.app.generations`` depended on ``zope.app.applicationcontrol`` but did not declare it. Modernized dependecy to ``zope.applicationcontrol`` as the needed interface has been moved there. - Using python's ``doctest`` module instead of deprecated ``zope.testing.doctest[unit]``. - Replaced a testing dependency on ``zope.app.securitypolicy`` with one on ``zope.securitypolicy``. 3.5.1 (2010-01-08) ------------------ - Depend on new ``zope.processlifetime`` interfaces instead of using BBB imports from ``zope.app.appsetup``. - Fix ftesting.zcml due to ``zope.securitypolicy`` update. - Fix tests using a newer zope.publisher that requires zope.login. 3.5.0 (2009-04-05) ------------------ - Moved ``getRootFolder`` utility method from ``zope.app.zopeappgenerations`` to ``zope.app.generations.utility``. - Removed not necessary install dependency on ``zope.app.testing``. 3.4.2 (2009-01-27) ------------------ - Provide more logging output for the various stages and actions of evolving a database. - Fixed bug: A failing last generation would allow starting an app server without having evolved to the minimum generation. - Substitute zope.app.zapi by direct calls to its wrapped apis. See bug 219302. - Corrected author email and home page address. 3.4.1 (2007-10-31) ------------------ - Resolve ``ZopeSecurityPolicy`` deprecation warning. 3.4.0 (2007-10-24) ------------------ - Initial release independent of the main Zope tree.
zope.app.generations
/zope.app.generations-5.0.tar.gz/zope.app.generations-5.0/CHANGES.rst
CHANGES.rst
__docformat__ = "reStructuredText" import docutils.core import zope.component from zope.generations.interfaces import ISchemaManager from zope.publisher.browser import BrowserView class _ReStructuredTextToHTMLRenderer(BrowserView): r"""An Adapter to convert from Restructured Text to HTML. Examples:: >>> from zope.publisher.browser import TestRequest >>> source = u''' ... This is source. ... ... Header 3 ... -------- ... This is more source. ... ''' >>> renderer = _ReStructuredTextToHTMLRenderer(source, TestRequest()) >>> print(renderer.render().strip()) <p>This is source.</p> <div class="section" id="header-3"> <h3>Header 3</h3> <p>This is more source.</p> </div> """ # Lifted from zope.app.renderers.rest def render(self, settings_overrides={}): """See zope.app.interfaces.renderer.IHTMLRenderer Let's make sure that inputted unicode stays as unicode: >>> renderer = _ReStructuredTextToHTMLRenderer(u'b\xc3h', None) >>> output = renderer.render() >>> isinstance(output, bytes) False >>> text = u''' ... ========= ... Heading 1 ... ========= ... ... hello world ... ... Heading 2 ... =========''' >>> overrides = {'initial_header_level': 2, ... 'doctitle_xform': 0 } >>> renderer = _ReStructuredTextToHTMLRenderer(text, None) >>> print(renderer.render(overrides)) <div class="section" id="heading-1"> <h2>Heading 1</h2> <p>hello world</p> <div class="section" id="heading-2"> <h3>Heading 2</h3> </div> </div> <BLANKLINE> """ # default settings for the renderer overrides = { 'halt_level': 6, 'input_encoding': 'unicode', 'output_encoding': 'unicode', 'initial_header_level': 3, } overrides.update(settings_overrides) parts = docutils.core.publish_parts( self.context, writer_name='html', settings_overrides=overrides, ) return ''.join((parts['body_pre_docinfo'], parts['docinfo'], parts['body'])) class ManagerDetails: r"""Show Details of a particular Schema Manager's Evolvers This method needs to use the component architecture, so we'll set it up: >>> from zope.component.testing import setUp, tearDown >>> setUp() We need to define some schema managers. We'll define just one: >>> from zope.generations.generations import SchemaManager >>> from zope import component as ztapi >>> app1 = SchemaManager(0, 3, 'zope.generations.demo') >>> ztapi.provideUtility(app1, ISchemaManager, 'foo.app1') Now let's create the view: >>> from zope.publisher.browser import TestRequest >>> details = ManagerDetails() >>> details.context = None >>> details.request = TestRequest(environ={'id': 'foo.app1'}) Let's now see that the view gets the ID correctly from the request: >>> details.id 'foo.app1' Now check that we get all the info from the evolvers: >>> info = details.getEvolvers() >>> for item in info: ... print(sorted(item.items())) [('from', 0), ('info', u'<p>Evolver 1</p>\n'), ('to', 1)] [('from', 1), ('info', u'<p>Evolver 2</p>\n'), ('to', 2)] [('from', 2), ('info', ''), ('to', 3)] We'd better clean up: >>> tearDown() """ request = None context = None id = property(lambda self: self.request['id']) def getEvolvers(self): id = self.id manager = zope.component.getUtility(ISchemaManager, id) evolvers = [] for gen in range(manager.minimum_generation, manager.generation): info = manager.getInfo(gen + 1) if info is None: info = '' else: renderer = _ReStructuredTextToHTMLRenderer( info.decode('utf-8') if isinstance(info, bytes) else info, self.request) info = renderer.render() evolvers.append({'from': gen, 'to': gen + 1, 'info': info}) return evolvers
zope.app.generations
/zope.app.generations-5.0.tar.gz/zope.app.generations-5.0/src/zope/app/generations/browser/managerdetails.py
managerdetails.py
__docformat__ = 'restructuredtext' import zope.component from transaction import TransactionManager from zope.generations.generations import Context from zope.generations.generations import generations_key from zope.generations.interfaces import ISchemaManager request_key_format = "evolve-app-%s" class Managers: def __init__(self, context, request): self.context = context self.request = request def _getdb(self): # TODO: There needs to be a better api for this return self.request.publication.db def evolve(self): """Perform a requested evolution This method needs to use the component architecture, so we'll set it up: >>> from zope.component.testing import setUp, tearDown >>> setUp() We also need a test request: >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() We also need to give it a publication with a database: >>> class Publication(object): ... pass >>> request.setPublication(Publication()) >>> from ZODB.MappingStorage import DB >>> db = DB() >>> request.publication.db = db We need to define some schema managers. We'll define two using the demo package: >>> from zope.generations.generations import SchemaManager >>> from zope import component as ztapi >>> app1 = SchemaManager(0, 1, 'zope.generations.demo') >>> ztapi.provideUtility(app1, ISchemaManager, 'foo.app1') >>> app2 = SchemaManager(0, 0, 'zope.generations.demo') >>> ztapi.provideUtility(app2, ISchemaManager, 'foo.app2') And we need to record some data for them in the database. >>> from zope.generations.generations import evolve >>> evolve(db) This sets up the data and actually evolves app1: >>> conn = db.open() >>> conn.root()[generations_key]['foo.app1'] 1 >>> conn.root()[generations_key]['foo.app2'] 0 To evolve a data base schema, the user clicks on a submit button. If they click on the button for add1, a item will be added to the request, which we simulate: >>> request.form['evolve-app-foo.app1'] = 'evolve' We'll also increase the generation of app1: >>> app1.generation = 2 Now we can create our view: >>> view = Managers(None, request) Now, if we call its `evolve` method, it should see that the app1 evolve button was pressed and evolve app1 to the next generation. >>> status = view.evolve() >>> conn.sync() >>> conn.root()[generations_key]['foo.app1'] 2 The demo evolver just writes the generation to a database key: >>> from zope.generations.demo import key >>> conn.root()[key] ('installed', 'installed', 2) Note that, because the demo package has an install script, we have entries for that script. Which the returned status should indicate: >>> status['app'] u'foo.app1' >>> status['to'] 2 Now, given that the database is at the maximum generation for app1, we can't evolve it further. Calling evolve again won't evolve anything: >>> status = view.evolve() >>> conn.sync() >>> conn.root()[generations_key]['foo.app1'] 2 >>> conn.root()[key] ('installed', 'installed', 2) as the status will indicate by returning a 'to' generation of 0: >>> status['app'] u'foo.app1' >>> status['to'] 0 If the request doesn't have the key: >>> request.form.clear() Then calling evolve does nothing: >>> view.evolve() >>> conn.sync() >>> conn.root()[generations_key]['foo.app1'] 2 >>> conn.root()[key] ('installed', 'installed', 2) We'd better clean upp: >>> db.close() >>> tearDown() """ self.managers = managers = dict( zope.component.getUtilitiesFor(ISchemaManager)) db = self._getdb() transaction_manager = TransactionManager() conn = db.open(transaction_manager=transaction_manager) transaction_manager.begin() try: generations = conn.root().get(generations_key, ()) request = self.request for key in generations: generation = generations[key] rkey = request_key_format % key if rkey in request: manager = managers[key] if generation >= manager.generation: return {'app': key, 'to': 0} context = Context() context.connection = conn generation += 1 manager.evolve(context, generation) generations[key] = generation transaction_manager.commit() return {'app': key, 'to': generation} finally: transaction_manager.abort() conn.close() def applications(self): """Get information about database-generation status This method needs to use the component architecture, so we'll set it up: >>> from zope.component.testing import setUp, tearDown >>> setUp() We also need a test request: >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() We also need to give it a publication with a database: >>> class Publication(object): ... pass >>> request.setPublication(Publication()) >>> from ZODB.MappingStorage import DB >>> db = DB() >>> request.publication.db = db We need to define some schema managers. We'll define two using the demo package: >>> from zope.generations.generations import SchemaManager >>> from zope import component as ztapi >>> app1 = SchemaManager(0, 1, 'zope.generations.demo') >>> ztapi.provideUtility(app1, ISchemaManager, 'foo.app1') >>> app2 = SchemaManager(0, 0, 'zope.generations.demo') >>> ztapi.provideUtility(app2, ISchemaManager, 'foo.app2') And we need to record some data for them in the database. >>> from zope.generations.generations import evolve >>> evolve(db) This sets up the data and actually evolves app1: >>> conn = db.open() >>> conn.root()[generations_key]['foo.app1'] 1 >>> conn.root()[generations_key]['foo.app2'] 0 Now, let's increment app1's generation: >>> app1.generation += 1 so we can evolve it. Now we can create our view: >>> view = Managers(None, request) We call its applications method to get data about application generations. We are required to call evolve first: >>> view.evolve() >>> data = list(view.applications()) >>> data.sort(key=lambda d1: d1['id']) >>> for info in data: ... print(info['id']) ... print(info['min'], info['max'], info['generation']) ... print('evolve?', info['evolve'] or None) foo.app1 0 2 1 evolve? evolve-app-foo.app1 foo.app2 0 0 0 evolve? None We'd better clean up: >>> db.close() >>> tearDown() """ result = [] db = self._getdb() transaction_manager = TransactionManager() conn = db.open(transaction_manager=transaction_manager) transaction_manager.begin() try: managers = self.managers generations = conn.root().get(generations_key, ()) for key, generation in generations.items(): manager = managers.get(key) if manager is None: # pragma: no cover continue result.append({ 'id': key, 'min': manager.minimum_generation, 'max': manager.generation, 'generation': generation, 'evolve': (generation < manager.generation and request_key_format % key or '' ), }) return result finally: transaction_manager.abort() conn.close()
zope.app.generations
/zope.app.generations-5.0.tar.gz/zope.app.generations-5.0/src/zope/app/generations/browser/managers.py
managers.py
__docformat__ = "reStructuredText" from zope.interface import Interface from zope.schema import Field, Bool, Choice from zope.app.homefolder.i18n import _ class IHomeFolder(Interface): """Describes the home directory of a principal.""" homeFolder = Field( title=_("Home Folder"), description=_("The principal's home folder; if none has been " "defined, this attribute will be `None`.")) class IHomeFolderManager(Interface): """Home Folder Manager This utility manages the assignments of home folders to principals. It will create and expect all """ homeFolderBase = Field( title=_("Base Folder"), description=_("The Base Folder for the Principal Home Folder."), required=True) createHomeFolder = Bool( title=_("Create Home Folder"), description=_("Whether home folders should be created upon adding " "a assignment, if missing."), required=True, default=True) autoCreateAssignment = Bool( title=_("Auto create assignment"), description=_("Whether assignment and folder should be created when " "calling getHomeFolder, if not existing."), required=True, default=False) homeFolderRole = Choice( title=_("Local Home Folder Role"), description=_("The local role that the user will have in " "its home folder. This role is only set on folders " "that are created by the manager."), vocabulary="Role Ids", default=u'zope.Manager' ) containerObject = Field( title=_("Container Type to create"), description=_("The container type that will be created upon first " "call of getHomeFolder (if autoCreate is on)"), required=True, default=u'zope.app.folder.Folder' ) def assignHomeFolder(principalId, folderName=None, create=None): """Assigns a particular folder as the home folder of a principal. If the `folderName` is `None`, then the principal id will be used as the folder name. If `createHomeFolder` or `create` is set to `True`, the method is also responsible for creating the folder. During creation, the principal should get manager rights inside the folder. If `create` is specifically set to `False`, then the folder is never created even if `createHomeFolder` is `True`. """ def unassignHomeFolder(principalId, delete=False): """Remove a home folder assignment. If `delete` is `True`, then delete the home folder including all of its content. """ def getHomeFolder(principalId): """Get the home folder instance of the specified principal. If a assignment does not exist and `autoCreateAssignment` is set to `True`, then create the assignment and the homefolder. The homefolder will always be created regardless of the value of createHomeFolder. The folder will be given the same name like the principalId. During creation, the principal should get the rights specified in homeFolderRole inside the folder. If the home folder does not exist and `autoCreateAssignment` is set to `False`, then return `None`. """
zope.app.homefolder
/zope.app.homefolder-3.5.0.tar.gz/zope.app.homefolder-3.5.0/src/zope/app/homefolder/interfaces.py
interfaces.py
__docformat__ = "reStructuredText" import zope.schema from zope.schema.vocabulary import SimpleVocabulary from zope.security.proxy import removeSecurityProxy from zope.traversing.interfaces import TraversalError from zope.traversing.api import getPath, getRoot, traverse from zope.dottedname.resolve import resolve from zope.app.form.browser import TextWidget, MultiSelectWidget from zope.app.form.utility import setUpWidget from zope.app.form.interfaces import IInputWidget from zope.app.form.interfaces import ConversionError from zope.app.homefolder.i18n import _ from zope.app.security.vocabulary import PrincipalSource class PathWidget(TextWidget): def _toFieldValue(self, input): path = super(PathWidget, self)._toFieldValue(input) root = getRoot(self.context.context) try: proxy = traverse(root, path) except TraversalError, e: raise ConversionError(_('path is not correct !'), e) else: return removeSecurityProxy(proxy) def _toFormValue(self, value): if value is None: return '' return getPath(value) class DottedNameWidget(TextWidget): """ Checks if the input is a resolvable class. """ def _toFieldValue(self, input): try: objectToCreate = resolve(input) except ImportError, e: raise ConversionError(_('dotted name is not correct !'), e) else: return input class AssignHomeFolder(object): def setupWidgets(self): self.principal_field = zope.schema.Choice( __name__ = 'principal', title=u'Principal Id', source=PrincipalSource(), required=False) self.folderName_field = zope.schema.TextLine( __name__ = 'folderName', title=u'Folder Name', required=False) self.selectedPrincipals_field = zope.schema.List( __name__ = 'selectedPrincipals', title=u'Existing Assignments', value_type=zope.schema.Choice( vocabulary=SimpleVocabulary.fromItems( [('%s (%s)' %(key, value), key) for key, value in self.context.assignments.items()] )), required=False) setUpWidget(self, 'principal', self.principal_field, IInputWidget) setUpWidget(self, 'folderName', self.folderName_field, IInputWidget) self.selectedPrincipals_widget = MultiSelectWidget( self.selectedPrincipals_field.bind(self), self.selectedPrincipals_field.value_type.vocabulary, self.request) self.selectedPrincipals_widget.setRenderedValue([]) def update(self): self.setupWidgets() if 'SUBMIT_ASSIGN' in self.request: if not self.principal_widget.hasInput(): return u'' principal = self.principal_widget.getInputValue() name = self.folderName_widget.getInputValue() self.context.assignHomeFolder(principal, name) self.setupWidgets() return u'Home Folder assignment was successful.' if 'SUBMIT_UNASSIGN' in self.request: if not self.selectedPrincipals_widget.hasInput(): return u'' for id in self.selectedPrincipals_widget.getInputValue(): self.context.unassignHomeFolder(id) self.setupWidgets() return u'Principals were successfully unassigned.' return u''
zope.app.homefolder
/zope.app.homefolder-3.5.0.tar.gz/zope.app.homefolder-3.5.0/src/zope/app/homefolder/browser.py
browser.py
===================== Principal Home Folder ===================== The principal home folder subscriber lets you assign home folders to principals as you would do in any OS. This particular implementation of such a feature is intended as a demo of the power of the way to handle principals and not as the holy grail. If you have concerns about the assumptions made in this implementation (which are probably legitimate), just ignore this package altogether. Managing the Home Folders ------------------------- Let's say we have a principal and we want to have a home folder for it. The first task is to create the home folder manager, which keeps track of the principal's home folders: >>> from zope.app.homefolder.homefolder import HomeFolderManager >>> manager = HomeFolderManager() Now the manager will not be able to do much, because it does not know where to look for the principal home folders. Therefore we have to specify a folder container: >>> from zope.container.btree import BTreeContainer >>> baseFolder = BTreeContainer() >>> manager.homeFolderBase = baseFolder Now we can assign a home folder to a principal: >>> manager.assignHomeFolder('stephan') Since we did not specify the name of the home folder, it is just the same as the principal id: >>> manager.assignments['stephan'] 'stephan' Since the home folder did not exist and the `createHomeFolder` option was turned on, the directory was created for you: >>> 'stephan' in baseFolder True When creating the home folder, the principal also automatically receives the `zope.Manager` role: >>> from zope.securitypolicy.interfaces import IPrincipalRoleManager >>> roles = IPrincipalRoleManager(baseFolder['stephan']) >>> [(role, str(setting)) ... for role, setting in roles.getRolesForPrincipal('stephan')] [(u'zope.Manager', 'PermissionSetting: Allow')] If a folder already exists for the provided name, then the creation is simply skipped silently: >>> from zope.app.folder import Folder >>> baseFolder['sc3'] = Folder() >>> manager.assignHomeFolder('sc3') >>> manager.assignments['sc3'] 'sc3' This has the advantage that you can choose your own `IContainer` implementation instead of relying on the vanilla folder. Now let's look at some derivations of the same task. 1. Sometimes you want to specify an alternative folder name: >>> manager.assignHomeFolder('jim', folderName='J1m') >>> manager.assignments['jim'] 'J1m' >>> 'J1m' in baseFolder True 2. Even though folders are created by default, you can specifically turn that behavior off for a particular assignment: >>> manager.assignHomeFolder('dreamcatcher', create=False) >>> manager.assignments['dreamcatcher'] 'dreamcatcher' >>> 'dreamcatcher' in baseFolder False 3. You wish not to create a folder by default: >>> manager.createHomeFolder = False >>> manager.assignHomeFolder('philiKON') >>> manager.assignments['philiKON'] 'philiKON' >>> 'philiKON' in baseFolder False 4. You do not want to create a folder by default, you want to create the folder for a specific user: >>> manager.assignHomeFolder('stevea', create=True) >>> manager.assignments['stevea'] 'stevea' >>> 'stevea' in baseFolder True Let's now look at removing home folder assignments. By default, removing an assignment will *not* delete the actual folder: >>> manager.unassignHomeFolder('stevea') >>> 'stevea' not in manager.assignments True >>> 'stevea' in baseFolder True But if you specify the `delete` argument, then the folder will be deleted: >>> 'J1m' in baseFolder True >>> manager.unassignHomeFolder('jim', delete=True) >>> 'jim' not in manager.assignments True >>> 'J1m' in baseFolder False Next, let's have a look at retrieving the home folder for a principal. This can be done as follows: >>> homeFolder = manager.getHomeFolder('stephan') >>> homeFolder is baseFolder['stephan'] True If you try to get a folder and it does not yet exist, `None` will be returned if autoCreateAssignment is False. Remember 'dreamcatcher', which has an assignment, but not a folder: >>> 'dreamcatcher' in baseFolder False >>> homeFolder = manager.getHomeFolder('dreamcatcher') >>> homeFolder is None True However, if autoCreateAssignment is True and you try to get a home folder of a principal which has no assignment, the assignment and the folder will be automatically created. The folder will always be created, regardless of the value of createHomeFolder. The name of the folder will be identically to the principalId: >>> manager.autoCreateAssignment = True >>> homeFolder = manager.getHomeFolder('florian') >>> 'florian' in manager.assignments True >>> 'florian' in baseFolder True Sometimes you want to create a homefolder which is not a zope.app.Folder. You can change the object type that is being created by changing the containerObject property. It defaults to 'zope.app.folder.Folder'. Let's create a homefile. >>> manager.containerObject = 'zope.app.file.File' >>> manager.assignHomeFolder('fileuser', create=True) >>> homeFolder = manager.getHomeFolder('fileuser') >>> print homeFolder #doctest: +ELLIPSIS <zope.app.file.file.File object at ...> You see that now a File object has been created. We reset containerObject to zope,folder.Folder to not confuse the follow tests. >>> manager.containerObject = 'zope.folder.Folder' Accessing the Home Folder ------------------------- But how does the home folder get assigned to a principal? There are two ways of accessing the homefolder. The first is via a simple adapter that provides a `homeFolder` attribute. The second method provides the folder via a path adapter called `homefolder`. Let's start by creating a principal: >>> from zope.security.interfaces import IPrincipal >>> from zope.interface import implements >>> class Principal: ... implements(IPrincipal) ... def __init__(self, id): ... self.id = id >>> principal = Principal('stephan') We also need to register our manager as a utility: >>> from zope.app.testing import ztapi >>> from zope.app.homefolder.interfaces import IHomeFolderManager >>> ztapi.provideUtility(IHomeFolderManager, manager, 'manager') (1) Now we can access the home folder via the adapter: >>> from zope.app.homefolder.interfaces import IHomeFolder >>> adapter = IHomeFolder(principal) >>> adapter.homeFolder is baseFolder['stephan'] True (2) Or alternatively via the path adapter: >>> import zope.component >>> from zope.traversing.interfaces import IPathAdapter >>> zope.component.getAdapter(principal, IPathAdapter, ... "homefolder") is baseFolder['stephan'] True As you can see, the path adapter just returns the homefolder. This way we can guarantee that the folder's full API is always available. Of course the real way it will be used is via a TALES expression: Setup of the Engine >>> from zope.app.pagetemplate.engine import Engine >>> from zope.tales.tales import Context >>> context = Context(Engine, {'principal': principal}) Executing the TALES expression >>> bytecode = Engine.compile('principal/homefolder:keys') >>> list(bytecode(context)) [] >>> baseFolder['stephan'][u'documents'] = Folder() >>> list(bytecode(context)) [u'documents']
zope.app.homefolder
/zope.app.homefolder-3.5.0.tar.gz/zope.app.homefolder-3.5.0/src/zope/app/homefolder/README.txt
README.txt
__docformat__ = "reStructuredText" from persistent import Persistent from BTrees.OOBTree import OOBTree from zope.interface import implements from zope import component from zope.securitypolicy.interfaces import IPrincipalRoleManager from zope.container.contained import Contained from zope.dottedname.resolve import resolve from zope.app.homefolder.interfaces import IHomeFolder, IHomeFolderManager class HomeFolderManager(Persistent, Contained): """ """ implements(IHomeFolderManager) # See IHomeFolderManager homeFolderBase = None createHomeFolder = True autoCreateAssignment = False homeFolderRole = u'zope.Manager' containerObject = u'zope.app.folder.Folder' def __init__(self): self.assignments = OOBTree() def assignHomeFolder(self, principalId, folderName=None, create=None): """See IHomeFolderManager""" # The name of the home folder is folderName, if specified, otherwise # it is the principal id name = folderName or principalId # Make the assignment. self.assignments[principalId] = name # Create a home folder instance, if the correct flags are set. if (create is True) or (create is None and self.createHomeFolder): if name not in self.homeFolderBase: objectToCreate = resolve(self.containerObject) self.homeFolderBase[name] = objectToCreate() principal_roles = IPrincipalRoleManager(self.homeFolderBase[name]) principal_roles.assignRoleToPrincipal( self.homeFolderRole, principalId) def unassignHomeFolder(self, principalId, delete=False): """See IHomeFolderManager""" folderName = self.assignments[principalId] if delete is True: del self.homeFolderBase[folderName] del self.assignments[principalId] def getHomeFolder(self, principalId): """See IHomeFolderManager""" if principalId not in self.assignments: if self.autoCreateAssignment: self.assignHomeFolder(principalId, create=True) else: return None return self.homeFolderBase.get(self.assignments[principalId], None) class HomeFolder(object): """Home folder adapter for a principal.""" implements(IHomeFolder) def __init__(self, principal): self.principal = principal homeFolder = property(lambda self: getHomeFolder(self.principal)) def getHomeFolder(principal): """Get the home folder instance of the principal.""" principalId = principal.id for name, manager in component.getUtilitiesFor(IHomeFolderManager): folder = manager.getHomeFolder(principalId) if folder is not None: return folder return None
zope.app.homefolder
/zope.app.homefolder-3.5.0.tar.gz/zope.app.homefolder-3.5.0/src/zope/app/homefolder/homefolder.py
homefolder.py
"""HTTP `PUT` verb""" __docformat__ = 'restructuredtext' import zope.publisher.interfaces.http import zope.traversing.browser from zope.component import queryAdapter from zope.event import notify from zope.filerepresentation.interfaces import IFileFactory from zope.filerepresentation.interfaces import IReadDirectory from zope.filerepresentation.interfaces import IWriteDirectory from zope.filerepresentation.interfaces import IWriteFile from zope.interface import implementer from zope.lifecycleevent import ObjectCreatedEvent from zope.app.http.interfaces import INullResource @implementer(INullResource) class NullResource: """Object representing objects to be created by a `PUT`. """ def __init__(self, container, name): self.container = container self.name = name class NullPUT: """Put handler for null resources (new file-like things) This view creates new objects in containers. """ def __init__(self, context, request): self.context = context self.request = request def PUT(self): request = self.request body = request.bodyStream name = self.context.name container = self.context.container # Find the extension ext_start = name.rfind('.') if ext_start > 0: ext = name[ext_start:] else: ext = "." # Get a "directory" surrogate for the container # TODO: Argh. Why don't we have a unioned Interface for that?!? dir_write = IWriteDirectory(container) dir_read = IReadDirectory(container) # Now try to get a custom factory for he container factory = queryAdapter(container, IFileFactory, ext) # Fall back to a non-custom one if factory is None: factory = IFileFactory(container, None) if factory is None: raise zope.publisher.interfaces.http.MethodNotAllowed( container, self.request) # TODO: Need to add support for large files data = body.read() newfile = factory(name, request.getHeader('content-type', ''), data) notify(ObjectCreatedEvent(newfile)) dir_write[name] = newfile # Ickyness with non-predictable support for containment: # make sure we get a containment proxy newfile = dir_read[name] request.response.setStatus(201) request.response.setHeader( 'Location', zope.traversing.browser.absoluteURL(newfile, request)) return b'' class FilePUT: """Put handler for existing file-like things """ def __init__(self, context, request): self.context = context self.request = request def PUT(self): body = self.request.bodyStream file = self.context adapter = IWriteFile(file, None) if adapter is None: raise zope.publisher.interfaces.http.MethodNotAllowed( self.context, self.request) length = int(self.request.get('CONTENT_LENGTH', -1)) adapter.write(body.read(length)) return b''
zope.app.http
/zope.app.http-5.0.tar.gz/zope.app.http-5.0/src/zope/app/http/put.py
put.py
"""HTTP Server Date/Time utilities """ import calendar import re import string import time def concat(*args): return ''.join(args) def join(seq, field=' '): return field.join(seq) def group(s): return '(' + s + ')' short_days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] long_days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] short_day_reg = group(join(short_days, '|')) long_day_reg = group(join(long_days, '|')) daymap = {} for i in range(7): daymap[short_days[i]] = i daymap[long_days[i]] = i hms_reg = join(3 * [group('[0-9][0-9]')], ':') months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] monmap = {} for i in range(12): monmap[months[i]] = i+1 months_reg = group(join(months, '|')) # From draft-ietf-http-v11-spec-07.txt/3.3.1 # Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 # Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 # Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format # rfc822 format rfc822_date = join( [concat(short_day_reg, ','), # day group('[0-9][0-9]?'), # date months_reg, # month group('[0-9]+'), # year hms_reg, # hour minute second 'gmt' ], ' ' ) rfc822_reg = re.compile(rfc822_date) def unpack_rfc822(m): g = m.group a = string.atoi return ( a(g(4)), # year monmap[g(3)], # month a(g(2)), # day a(g(5)), # hour a(g(6)), # minute a(g(7)), # second 0, 0, 0 ) # rfc850 format rfc850_date = join( [concat(long_day_reg, ','), join( [group('[0-9][0-9]?'), months_reg, group('[0-9]+') ], '-' ), hms_reg, 'gmt' ], ' ' ) rfc850_reg = re.compile(rfc850_date) # they actually unpack the same way def unpack_rfc850(m): g = m.group a = string.atoi return ( a(g(4)), # year monmap[g(3)], # month a(g(2)), # day a(g(5)), # hour a(g(6)), # minute a(g(7)), # second 0, 0, 0 ) # parsdate.parsedate - ~700/sec. # parse_http_date - ~1333/sec. weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] monthname = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] def build_http_date(when): year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when) return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( weekdayname[wd], day, monthname[month], year, hh, mm, ss) def parse_http_date(d): d = d.lower() m = rfc850_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc850(m))) else: m = rfc822_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc822(m))) else: return 0 return retval
zope.app.http
/zope.app.http-5.0.tar.gz/zope.app.http-5.0/src/zope/app/http/httpdate.py
httpdate.py
========= CHANGES ========= 4.1.0 (2020-10-07) ================== - Add compatibility with ``zope.i18n >= 4.7``. We fulfill the interface for plural messages now, although we do not provide any implementation. This is documented and raises NotImplementedError. 4.0.1 (2019-07-10) ================== - Add support for Python 3.7. - Fix deprecation warning about importing IRegistered/IUnregistered from their old locations in zope.component.interfaces instead of their current locations in zope.interface.interfaces. 4.0.0 (2017-05-25) ================== - Add support for Python 3.5, 3.6 and PyPy. - Replace dependency on ``ZODB3`` with ``BTrees`` and ``persistent``. - Drop test dependency on ``zope.app.testing``. - The synchronization view now uses Python's built-in transport for handling Basic Authentication. As a reminder, Basic Authentication does not permit a colon (``:``) in the username, but does allow colons in the password (if the server properly conforms to the specification). 3.6.4 (2012-12-14) ================== - Fix translate() when used with ZODB 4. - Remove test dependency on zope.app.component 3.6.3 (2010-09-01) ================== - Remove undeclared dependency on zope.deferredimport. - Use zope.publisher >= 3.9 instead of zope.app.publisher. 3.6.2 (2009-10-07) ================== - Fix test_translate and follow recent change of HTTPResponse.redirect. 3.6.1 (2009-08-15) ================== - Added a missing testing dependency on zope.app.component. 3.6.0 (2009-03-18) ================== - Some of ZCML configuration was moved into another packages: * The global INegotiator utility registration was moved into ``zope.i18n``. * The include of ``zope.i18n.locales`` was also moved into ``zope.i18n``. * The registration of IModifiableUserPreferredLanguages adapter was moved into ``zope.app.publisher``. * The IAttributeAnnotation implementation statement for HTTPRequest was moved into ``zope.publisher`` and will only apply if ``zope.annotation`` is available. * The IUserPreferredCharsets adapter registration was also moved into ``zope.publisher``. - Depend on zope.component >= 3.6 instead of zope.app.component as the ``queryNextUtility`` function was moved there. - Remove the old ``zope.app.i18n.metadirectives`` module as the directive was moved to ``zope.i18n`` ages ago. 3.5.0 (2009-02-01) ================== - Use zope.container instead of zope.app.container. 3.4.6 (2009-01-27) ================== - Fix a simple inconsistent MRO problem in tests - Substitute zope.app.zapi by direct calls to its wrapped apis. See bug 219302. 3.4.5 (unreleased) ================== - This was skipped over by accident. 3.4.4 (2007-10-23) ================== - Fix deprecation warning. 3.4.3 (2007-10-23) ================== - Fix imports in tests. - Clean up long lines. 3.4.2 (2007-9-26) ================= - Release to fix packaging issues with 3.4.1. 3.4.1 (2007-9-25) ================= - Added missing Changes.txt and README.txt files to egg 3.4.0 (2007-9-25) ================= - Initial documented release - Move ZopeMessageFactory to zope.i18nmessageid
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/CHANGES.rst
CHANGES.rst
=============== zope.app.i18n =============== .. image:: https://img.shields.io/pypi/v/zope.app.i18n.svg :target: https://pypi.org/project/zope.app.i18n/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/zope.app.i18n.svg :target: https://pypi.org/project/zope.app.i18n/ :alt: Supported Python versions .. image:: https://travis-ci.org/zopefoundation/zope.app.i18n.svg?branch=master :target: https://travis-ci.org/zopefoundation/zope.app.i18n .. image:: https://coveralls.io/repos/github/zopefoundation/zope.app.i18n/badge.svg?branch=master :target: https://coveralls.io/github/zopefoundation/zope.app.i18n?branch=master Summary ======= This package provides placeful persistent translation domains and message catalogs along with ZMI views for managing them. Caveats ======= Currently this integration does not support the feature of plural messages which is supported by the underlying ``zope.i18n`` library. In case you need this feature, please discuss this in the issue tracker in the repository.
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/README.rst
README.rst
import os import shutil import sys import tempfile from optparse import OptionParser __version__ = '2015-07-01' # See zc.buildout's changelog if this version is up to date. tmpeggs = tempfile.mkdtemp(prefix='bootstrap-') usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --find-links to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("--version", action="store_true", default=False, help=("Return bootstrap.py version.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", "--config-file", help=("Specify the path to the buildout configuration " "file to be used.")) parser.add_option("-f", "--find-links", help=("Specify a URL to search for buildout releases")) parser.add_option("--allow-site-packages", action="store_true", default=False, help=("Let bootstrap.py use existing site packages")) parser.add_option("--buildout-version", help="Use a specific zc.buildout version") parser.add_option("--setuptools-version", help="Use a specific setuptools version") parser.add_option("--setuptools-to-dir", help=("Allow for re-use of existing directory of " "setuptools versions")) options, args = parser.parse_args() if options.version: print("bootstrap.py version %s" % __version__) sys.exit(0) ###################################################################### # load/install setuptools try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen ez = {} if os.path.exists('ez_setup.py'): exec(open('ez_setup.py').read(), ez) else: exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) if not options.allow_site_packages: # ez_setup imports site, which adds site packages # this will remove them from the path to ensure that incompatible versions # of setuptools are not in the path import site # inside a virtualenv, there is no 'getsitepackages'. # We can't remove these reliably if hasattr(site, 'getsitepackages'): for sitepackage_path in site.getsitepackages(): # Strip all site-packages directories from sys.path that # are not sys.prefix; this is because on Windows # sys.prefix is a site-package directory. if sitepackage_path != sys.prefix: sys.path[:] = [x for x in sys.path if sitepackage_path not in x] setup_args = dict(to_dir=tmpeggs, download_delay=0) if options.setuptools_version is not None: setup_args['version'] = options.setuptools_version if options.setuptools_to_dir is not None: setup_args['to_dir'] = options.setuptools_to_dir ez['use_setuptools'](**setup_args) import setuptools import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) ###################################################################### # Install buildout ws = pkg_resources.working_set setuptools_path = ws.find( pkg_resources.Requirement.parse('setuptools')).location # Fix sys.path here as easy_install.pth added before PYTHONPATH cmd = [sys.executable, '-c', 'import sys; sys.path[0:0] = [%r]; ' % setuptools_path + 'from setuptools.command.easy_install import main; main()', '-mZqNxd', tmpeggs] find_links = os.environ.get( 'bootstrap-testing-find-links', options.find_links or ('http://downloads.buildout.org/' if options.accept_buildout_test_releases else None) ) if find_links: cmd.extend(['-f', find_links]) requirement = 'zc.buildout' version = options.buildout_version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): try: return not parsed_version.is_prerelease except AttributeError: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setuptools_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) import subprocess if subprocess.call(cmd) != 0: raise Exception( "Failed to execute command:\n%s" % repr(cmd)[1:-1]) ###################################################################### # Import and run buildout ws.add_entry(tmpeggs) ws.require(requirement) import zc.buildout.buildout if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/bootstrap.py
bootstrap.py
__docformat__ = 'restructuredtext' from zope.interface import provider, providedBy, implementer import time from BTrees.OOBTree import OOBTree from persistent import Persistent from zope.component.interfaces import IFactory from zope.app.i18n.interfaces import ILocalMessageCatalog from zope.app.i18n.interfaces import NotYetImplementedError @implementer(ILocalMessageCatalog) @provider(IFactory) class MessageCatalog(Persistent): def __init__(self, language, domain="default"): """Initialize the message catalog""" self.id = '' self.title = '' self.description = '' self.language = language self.domain = domain self._messages = OOBTree() def getMessage(self, id): 'See `IMessageCatalog`' return self._messages[id][0] def queryMessage(self, id, default=None): 'See `IMessageCatalog`' result = self._messages.get(id) if result is not None: result = result[0] else: result = default return result def getPluralMessage(self, singular, plural, n): 'See `IMessageCatalog`' raise NotYetImplementedError def queryPluralMessage(self, singular, plural, n, dft1=None, dft2=None): 'See `IMessageCatalog`' raise NotYetImplementedError def getIdentifier(self): 'See `IReadMessageCatalog`' return (self.language, self.domain) def getFullMessage(self, msgid): 'See `IWriteMessageCatalog`' message = self._messages[msgid] return {'domain' : self.domain, 'language' : self.language, 'msgid' : msgid, 'msgstr' : message[0], 'mod_time' : message[1]} def setMessage(self, msgid, message, mod_time=None): 'See `IWriteMessageCatalog`' if mod_time is None: mod_time = int(time.time()) self._messages[msgid] = (message, mod_time) def deleteMessage(self, msgid): 'See `IWriteMessageCatalog`' del self._messages[msgid] def getMessageIds(self): 'See IWriteMessageCatalog' return list(self._messages.keys()) def getMessages(self): 'See `IWriteMessageCatalog`' messages = [] for message in self._messages.items(): messages.append({'domain' : self.domain, 'language' : self.language, 'msgid' : message[0], 'msgstr' : message[1][0], 'mod_time' : message[1][1]}) return messages @classmethod def getInterfaces(cls): 'See `IFactory`' return tuple(providedBy(cls))
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/src/zope/app/i18n/messagecatalog.py
messagecatalog.py
__docformat__ = 'restructuredtext' import re from BTrees.OOBTree import OOBTree import zope.component from zope.interface import implementer from zope.i18n import interpolate from zope.i18n.interfaces import INegotiator, ITranslationDomain from zope.i18n.simpletranslationdomain import SimpleTranslationDomain from zope.container.btree import BTreeContainer from zope.container.contained import Contained from zope.app.i18n.interfaces import ILocalTranslationDomain from zope.app.i18n.interfaces import NotYetImplementedError try: unicode except NameError: unicode = str @implementer(ILocalTranslationDomain) class TranslationDomain(BTreeContainer, SimpleTranslationDomain, Contained): def __init__(self): super(TranslationDomain, self).__init__() self._catalogs = OOBTree() self.domain = '<domain not activated>' def _registerMessageCatalog(self, language, catalog_name): if language not in self._catalogs.keys(): self._catalogs[language] = [] mc = self._catalogs[language] mc.append(catalog_name) def _unregisterMessageCatalog(self, language, catalog_name): self._catalogs[language].remove(catalog_name) def __setitem__(self, name, object): 'See IWriteContainer' super(TranslationDomain, self).__setitem__(name, object) self._registerMessageCatalog(object.language, name) def __delitem__(self, name): 'See IWriteContainer' object = self[name] super(TranslationDomain, self).__delitem__(name) self._unregisterMessageCatalog(object.language, name) def translate(self, msgid, mapping=None, context=None, target_language=None, default=None, msgid_plural=None, default_plural=None, number=None): """See interface `ITranslationDomain`""" if any((default_plural, msgid_plural, number)): raise NotYetImplementedError if target_language is None and context is not None: avail_langs = self.getAvailableLanguages() # Let's negotiate the language to translate to. :) negotiator = zope.component.getUtility(INegotiator, context=self) target_language = negotiator.getLanguage(avail_langs, context) # Get the translation. Default is the source text itself. if target_language is not None: catalog_names = self._catalogs.get(target_language, []) else: catalog_names = [] for name in catalog_names: catalog = super(TranslationDomain, self).__getitem__(name) # TODO: handle msgid_plural text = catalog.queryMessage(msgid) if text is not None: break else: # If nothing found, delegate to a translation server higher up the # tree. domain = zope.component.queryNextUtility(self, ITranslationDomain, self.domain) if domain is not None: # TODO: handle msgid_plural return domain.translate(msgid, mapping, context, target_language, default=default) if default is None: default = unicode(msgid) # TODO: handle msgid_plural/default_plural text = default # Now we need to do the interpolation return interpolate(text, mapping) def getMessageIds(self, filter='%'): 'See `IWriteTranslationDomain`' filter = filter.replace('%', '.*') filter_re = re.compile(filter) msgids = {} for language in self.getAvailableLanguages(): for name in self._catalogs[language]: for msgid in self[name].getMessageIds(): if filter_re.match(msgid): msgids[msgid] = None return msgids.keys() def getMessages(self): 'See `IWriteTranslationDomain`' messages = [] languages = self.getAvailableLanguages() for language in languages: for name in self._catalogs[language]: messages += self[name].getMessages() return messages def getMessage(self, msgid, language): 'See `IWriteTranslationDomain`' for name in self._catalogs.get(language, []): try: return self[name].getFullMessage(msgid) except: pass return None def getAllLanguages(self): 'See `IWriteTranslationDomain`' return sorted(self._catalogs) def getAvailableLanguages(self): 'See `IWriteTranslationDomain`' return self.getAllLanguages() def addMessage(self, msgid, msg, language, mod_time=None): 'See `IWriteTranslationDomain`' if language not in self._catalogs: if language not in self.getAllLanguages(): self.addLanguage(language) catalog_name = self._catalogs[language][0] catalog = self[catalog_name] catalog.setMessage(msgid, msg, mod_time) def updateMessage(self, msgid, msg, language, mod_time=None): 'See `IWriteTranslationDomain`' catalog_name = self._catalogs[language][0] catalog = self[catalog_name] catalog.setMessage(msgid, msg, mod_time) def deleteMessage(self, msgid, language): 'See `IWriteTranslationDomain`' catalog_name = self._catalogs[language][0] catalog = self[catalog_name] catalog.deleteMessage(msgid) def addLanguage(self, language): 'See `IWriteTranslationDomain`' catalog = zope.component.createObject(u'zope.app.MessageCatalog', language) catalog.domain = self.domain self[language] = catalog def deleteLanguage(self, language): 'See `IWriteTranslationDomain`' # Delete all catalogs from the data storage for name in self._catalogs[language]: if self.has_key(name): del self[name] # Now delete the specifc catalog registry for this language del self._catalogs[language] def getMessagesMapping(self, languages, foreign_messages): 'See `ISyncTranslationDomain`' mapping = {} # Get all relevant local messages local_messages = [] for language in languages: for name in self._catalogs.get(language, []): local_messages += self[name].getMessages() for fmsg in foreign_messages: ident = (fmsg['msgid'], fmsg['language']) mapping[ident] = (fmsg, self.getMessage(*ident)) for lmsg in local_messages: ident = (lmsg['msgid'], lmsg['language']) if ident not in mapping.keys(): mapping[ident] = (None, lmsg) return mapping def synchronize(self, messages_mapping): 'See `ISyncTranslationDomain`' for value in messages_mapping.values(): fmsg = value[0] lmsg = value[1] if fmsg is None: self.deleteMessage(lmsg['msgid'], lmsg['language']) elif lmsg is None: self.addMessage(fmsg['msgid'], fmsg['msgstr'], fmsg['language'], fmsg['mod_time']) elif fmsg['mod_time'] > lmsg['mod_time']: self.updateMessage(fmsg['msgid'], fmsg['msgstr'], fmsg['language'], fmsg['mod_time']) def setDomainOnActivation(domain, event): """Set the permission id upon registration activation. Let's see how this notifier can be used. First we need to create an event using the permission instance and a registration stub: >>> class Registration: ... def __init__(self, obj, name): ... self.component = obj ... self.name = name >>> domain1 = TranslationDomain() >>> domain1.domain '<domain not activated>' >>> import zope.interface.interfaces >>> event = zope.interface.interfaces.Registered( ... Registration(domain1, 'domain1')) Now we pass the event into this function, and the id of the domain should be set to 'domain1'. >>> setDomainOnActivation(domain1, event) >>> domain1.domain 'domain1' """ domain.domain = event.object.name def unsetDomainOnDeactivation(domain, event): """Unset the permission id up registration deactivation. Let's see how this notifier can be used. First we need to create an event using the permission instance and a registration stub: >>> class Registration: ... def __init__(self, obj, name): ... self.component = obj ... self.name = name >>> domain1 = TranslationDomain() >>> domain1.domain = 'domain1' >>> import zope.interface.interfaces >>> event = zope.interface.interfaces.Unregistered( ... Registration(domain1, 'domain1')) Now we pass the event into this function, and the id of the role should be set to '<domain not activated>'. >>> unsetDomainOnDeactivation(domain1, event) >>> domain1.domain '<domain not activated>' """ domain.domain = '<domain not activated>'
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/src/zope/app/i18n/translationdomain.py
translationdomain.py
__docformat__ = 'restructuredtext' import time import re from zope.interface import implementer from zope.i18n.interfaces import IMessageExportFilter, IMessageImportFilter from zope.app.i18n.interfaces import ILocalTranslationDomain try: string_types = (basestring,) except NameError: string_types = (str,) class ParseError(Exception): def __init__(self, state, lineno, line=''): Exception.__init__(self, state, lineno, line) self.state = state self.lineno = lineno self.line = line def __str__(self): return "state %s, line num %s: '%s'" % (self.state, self.lineno, self.line) def _find_language(languages, kind): if isinstance(languages, string_types): languages = [languages] if len(languages) != 1: raise TypeError( 'Exactly one language at a time is supported for gettext %s.' % (kind,)) return languages[0] @implementer(IMessageExportFilter) class GettextExportFilter(object): __used_for__ = ILocalTranslationDomain def __init__(self, domain): self.domain = domain def exportMessages(self, languages): 'See IMessageExportFilter' domain = self.domain.domain language = _find_language(languages, 'export') dt = time.time() dt = time.localtime(dt) dt = time.strftime('%Y/%m/%d %H:%M', dt) if not isinstance(dt, bytes): dt = dt.encode('utf-8') output = _file_header % (dt, language.encode('UTF-8'), domain.encode('UTF-8')) for msgid in sorted(self.domain.getMessageIds()): msgstr = self.domain.translate(msgid, target_language=language) msgstr = msgstr.encode('UTF-8') msgid = msgid.encode('UTF-8') output += _msg_template % (msgid, msgstr) return output @implementer(IMessageImportFilter) class GettextImportFilter(object): __used_for__ = ILocalTranslationDomain def __init__(self, domain): self.domain = domain def importMessages(self, languages, data_file): 'See IMessageImportFilter' language = _find_language(languages, 'import') result = parseGetText(data_file.readlines())[3] headers = parserHeaders(b''.join(result[(b'',)][1])) del result[(b'',)] charset = extractCharset(headers[b'content-type']) for msg in result.items(): msgid = b''.join(msg[0]).decode(charset) msgid = msgid.replace('\\n', '\n') msgstr = b''.join(msg[1][1]).decode(charset) msgstr = msgstr.replace('\\n', '\n') self.domain.addMessage(msgid, msgstr, language) def extractCharset(header): charset = header.split(b'charset=')[-1] if not isinstance(charset, str): charset = charset.decode('utf-8') return charset.lower() def parserHeaders(headers_bytes): headers = {} for line in headers_bytes.split(b'\\n'): name = line.split(b':')[0] value = b''.join(line.split(b':')[1:]) headers[name.lower()] = value return headers def parseGetText(content): # The regular expressions com = re.compile(b'^#.*') msgid = re.compile(br'^ *msgid *"(.*?[^\\]*)"') msgstr = re.compile(br'^ *msgstr *"(.*?[^\\]*)"') re_str = re.compile(br'^ *"(.*?[^\\])"') blank = re.compile(br'^\s*$') trans = {} pointer = 0 state = 0 COM, MSGID, MSGSTR = [], [], [] while pointer < len(content): line = content[pointer] #print 'STATE:', state #print 'LINE:', line, content[pointer].strip() if state == 0: COM, MSGID, MSGSTR = [], [], [] if com.match(line): COM.append(line.strip()) state = 1 pointer = pointer + 1 elif msgid.match(line): MSGID.append(msgid.match(line).group(1)) state = 2 pointer = pointer + 1 elif blank.match(line): pointer = pointer + 1 else: raise ParseError(0, pointer + 1, line) elif state == 1: if com.match(line): COM.append(line.strip()) state = 1 pointer = pointer + 1 elif msgid.match(line): MSGID.append(msgid.match(line).group(1)) state = 2 pointer = pointer + 1 elif blank.match(line): pointer = pointer + 1 else: raise ParseError(1, pointer + 1, line) elif state == 2: if com.match(line): COM.append(line.strip()) state = 2 pointer = pointer + 1 elif re_str.match(line): MSGID.append(re_str.match(line).group(1)) state = 2 pointer = pointer + 1 elif msgstr.match(line): MSGSTR.append(msgstr.match(line).group(1)) state = 3 pointer = pointer + 1 elif blank.match(line): pointer = pointer + 1 else: raise ParseError(2, pointer + 1, line) elif state == 3: if com.match(line) or msgid.match(line): # print "\nEn", language, "detected", MSGID trans[tuple(MSGID)] = (COM, MSGSTR) state = 0 elif re_str.match(line): MSGSTR.append(re_str.match(line).group(1)) state = 3 pointer = pointer + 1 elif blank.match(line): pointer = pointer + 1 else: raise ParseError(3, pointer + 1, line) # the last also goes in if tuple(MSGID): trans[tuple(MSGID)] = (COM, MSGSTR) return COM, MSGID, MSGSTR, trans _file_header = b''' msgid "" msgstr "" "Project-Id-Version: Zope 3\\n" "PO-Revision-Date: %s\\n" "Last-Translator: Zope 3 Gettext Export Filter\\n" "Zope-Language: %s\\n" "Zope-Domain: %s\\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=UTF-8\\n" "Content-Transfer-Encoding: 8bit\\n" ''' _msg_template = b''' msgid "%s" msgstr "%s" '''
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/src/zope/app/i18n/filters.py
filters.py
"""Placeful internationalization of content objects. """ __docformat__ = 'restructuredtext' from zope.interface import Interface from zope.i18n.interfaces import ITranslationDomain, IMessageCatalog from zope.container.interfaces import IContainer class IWriteTranslationDomain(Interface): """This interface describes the methods that are necessary for an editable Translation Domain to work. For a translation domain to be editable its 'messages' have to support the following information: id, string, domain, language, date Most of the information will be natural, since they are required by the translation domain, but especially the date is not a necessary info (in fact, it is meta data) """ def getMessage(msgid, langauge): """Get the full message of a particular language.""" def getMessageIds(filter='%'): """Get all the message ids of this domain.""" def getMessages(): """Get all the messages of this domain.""" def getAllLanguages(): """Find all the languages that are available""" def getAvailableLanguages(): """Find all the languages that are available.""" def addMessage(msgid, msg, language, mod_time=None): """Add a message to the translation domain. If `mod_time` is ``None``, then the current time should be inserted. """ def updateMessage(msgid, msg, language, mod_time=None): """Update a message in the translation domain. If `mod_time` is ``None``, then the current time should be inserted. """ def deleteMessage(domain, msgid, language): """Delete a messahe in the translation domain.""" def addLanguage(language): """Add Language to Translation Domain""" def deleteLanguage(language): """Delete a Domain from the Translation Domain.""" class ISyncTranslationDomain(Interface): """This interface allows translation domains to be synchronized. The following four synchronization states can exist: 0 - uptodate: The two messages are in sync. Default Action: Do nothing. 1 - new: The message exists on the foreign TS, but is locally unknown. Default Action: Add the message to the local catalog. 2 - older: The local version of the message is older than the one on the server. Default Action: Update the local message. 3 - newer: The local version is newer than the foreign version. Default Action: Do nothing. 4 - deleted: The message does not exist in the foreign TS. Default Action: Delete local version of message. """ def getMessagesMapping(languages, foreign_messages): """Creates a mapping of the passed foreign messages and the local ones. Returns a status report in a dictionary with keys of the form (msgid, domain, language) and values being a tuple of: foreign_mod_date, local_mod_date """ def synchronize(messages_mapping): """Update the local message catalogs based on the foreign data. """ class ILocalTranslationDomain(ITranslationDomain, IWriteTranslationDomain, ISyncTranslationDomain, IContainer): """This is the common and full-features translation domain. Almost all translation domain implementations will use this interface. An exception to this is the `GlobalMessageCatalog` as it will be read-only. """ class ILocalMessageCatalog(IMessageCatalog): """If this interfaces is implemented by a message catalog, then we will be able to update our messages. Note that not all methods here require write access, but they should not be required for an `IReadMessageCatalog` and are used for editing only. Therefore this is the more suitable interface to put them. """ def getFullMessage(msgid): """Get the message data and meta data as a nice dictionary. More advanced implementation might choose to return an object with the data, but the object should then implement `IEnumerableMapping`. An exception is raised if the message id is not found. """ def setMessage(msgid, message, mod_time=None): """Set a message to the catalog. If `mod_time` is ``None`` use the current time instead as modification time.""" def deleteMessage(msgid): """Delete a message from the catalog.""" def getMessageIds(): """Get a list of all the message ids.""" def getMessages(): """Get a list of all the messages.""" # Plural messages are not supported yet. Please report an issue kn # github in case you want to implement this feature. NotYetImplementedError = NotImplementedError( 'Plural messages are not supported yet.' ' See https://github.com/zopefoundation/zope.app.i18n/issues/7' )
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/src/zope/app/i18n/interfaces.py
interfaces.py
__docformat__ = 'restructuredtext' from zope.app.i18n.browser import BaseView class Translate(BaseView): def getMessages(self): """Get messages""" filter = self.request.get('filter', '%') messages = [] for msg_id in self.context.getMessageIds(filter): messages.append((msg_id, len(messages))) return messages def getTranslation(self, msgid, target_lang): return self.context.translate(msgid, target_language=target_lang) def getEditLanguages(self): '''get the languages that are selected for editing''' languages = self.request.cookies.get('edit_languages', '') return filter(None, languages.split(',')) def editMessage(self): msg_id = self.request['msg_id'] for language in self.getEditLanguages(): msg = self.request['msg_lang_%s' % language] if msg != self.context.translate(msg_id, target_language=language): self.context.updateMessage(msg_id, msg, language) return self.request.response.redirect(self.request.URL[-1]) def editMessages(self): # Handle new Messages for count in range(5): msg_id = self.request.get('new-msg_id-%i' %count, '') if msg_id: for language in self.getEditLanguages(): msg = self.request.get('new-%s-%i' %(language, count), msg_id) self.context.addMessage(msg_id, msg, language) # Handle edited Messages keys = [k[len('edit-msg_id-'):] for k in self.request.keys() if k.startswith('edit-msg_id-')] for key in keys: msg_id = self.request['edit-msg_id-'+key] for language in self.getEditLanguages(): msg = self.request['edit-%s-%s' %(language, key)] if msg != self.context.translate(msg_id, target_language=language): self.context.updateMessage(msg_id, msg, language) return self.request.response.redirect(self.request.URL[-1]) def deleteMessages(self, message_ids): for id in message_ids: msgid = self.request.form['edit-msg_id-%s' %id] for language in self.context.getAvailableLanguages(): # Some we edit a language, but no translation exists... try: self.context.deleteMessage(msgid, language) except KeyError: pass return self.request.response.redirect(self.request.URL[-1]) def addLanguage(self, language): self.context.addLanguage(language) return self.request.response.redirect(self.request.URL[-1]) def changeEditLanguages(self, languages=()): self.request.response.setCookie('edit_languages', ','.join(languages)) return self.request.response.redirect(self.request.URL[-1]) def changeFilter(self): filter = self.request.get('filter', '%') self.request.response.setCookie('filter', filter) return self.request.response.redirect(self.request.URL[-1]) def deleteLanguages(self, languages): for language in languages: self.context.deleteLanguage(language) return self.request.response.redirect(self.request.URL[-1])
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/src/zope/app/i18n/browser/translate.py
translate.py
__docformat__ = 'restructuredtext' try: import httplib from xmlrpclib import Transport from xmlrpclib import Server from xmlrpclib import ProtocolError except ImportError: from xmlrpc.client import Transport from xmlrpc.client import ProtocolError from xmlrpc.client import ServerProxy as Server try: from urllib import unquote from urllib import quote from urlparse import urlparse from urlparse import urlunparse except ImportError: from urllib.parse import unquote from urllib.parse import quote from urllib.parse import urlparse from urllib.parse import urlunparse import zope.i18nmessageid from zope.security.proxy import removeSecurityProxy from zope.app.i18n.browser import BaseView _ = zope.i18nmessageid.MessageFactory("zope") DEFAULT = 'http://localhost:8080/++etc++site/default/zope' class Synchronize(BaseView): messageStatus = [_('Up to Date'), _('New Remote'), _('Out of Date'), _('Newer Local'), _('Does not exist')] def __init__(self, context, request): self.context = context self.request = request self.sync_url = self.request.cookies.get( 'sync_url', DEFAULT) self.sync_url = unquote(self.sync_url) self.sync_username = self.request.cookies.get('sync_username', 'admin') self.sync_password = self.request.cookies.get('sync_password', 'admin') self.sync_languages = filter(None, self.request.cookies.get( 'sync_languages', '').split(',')) self._connection = None def _make_sync_url(self): # make sure the URL contains the http:// prefix url = self.sync_url if not url.startswith(('http://', 'https://')): url = 'http://' + url # Add username and password to the url. parts = urlparse(url) if '@' not in parts.netloc: parts = list(parts) parts[1] = self.sync_username + ':' + self.sync_password + '@' + parts[1] url = urlunparse(parts) return url def _connect(self): '''Connect to the remote server via XML-RPC HTTP; return status''' # Now try to connect self._connection = Server(self._make_sync_url()) # check whether the connection was made and the Master Babel Tower # exists try: self._connection.getAllLanguages() return 1 # pragma: no cover except Exception: self._connection = None return 0 def _disconnect(self): '''Disconnect from the sever; return ``None``''' self._connection = None def _isConnected(self): '''Check whether we are currently connected to the server; return boolean''' return bool(self._connection is not None and self._connection.getAllLanguages()) def canConnect(self): '''Checks whether we can connect using this server and user data; return boolean''' if self._isConnected(): return True return self._connect() def getAllLanguages(self): connected = self._isConnected() if not connected: connected = self._connect() if connected: return self._connection.getAllLanguages() return [] def queryMessages(self): connected = self._isConnected() if not connected: connected = self._connect() fmsgs = [] if connected: fmsgs = self._connection.getMessagesFor(self.sync_languages) return self.context.getMessagesMapping(self.sync_languages, fmsgs) def queryMessageItems(self): items = self.queryMessages().items() items = removeSecurityProxy(items) return sorted(items, key=lambda x: x[0][0] + x[0][1]) def getStatus(self, fmsg, lmsg, verbose=1): state = 0 if fmsg is None: state = 4 elif lmsg is None: state = 1 elif fmsg['mod_time'] > lmsg['mod_time']: state = 2 elif fmsg['mod_time'] < lmsg['mod_time']: state = 3 elif fmsg['mod_time'] == lmsg['mod_time']: state = 0 return self.messageStatus[state] if verbose else state def saveSettings(self): self.sync_languages = self.request.form.get('sync_languages', []) self.request.response.setCookie('sync_languages', ','.join(self.sync_languages)) self.request.response.setCookie('sync_url', quote(self.request['sync_url']).strip()) self.request.response.setCookie('sync_username', self.request['sync_username']) self.request.response.setCookie('sync_password', self.request['sync_password']) return self.request.response.redirect(self.request.URL[-1] + '/@@synchronizeForm.html') def synchronize(self): mapping = self.queryMessages() self.context.synchronize(mapping) return self.request.response.redirect(self.request.URL[-1]+ '/@@synchronizeForm.html') def synchronizeMessages(self): idents = [] for id in self.request.form['message_ids']: msgid = self.request.form['update-msgid-'+id] language = self.request.form['update-language-'+id] idents.append((msgid, language)) mapping = self.queryMessages() new_mapping = {} for item in mapping.items(): if item[0] in idents: new_mapping[item[0]] = item[1] self.context.synchronize(new_mapping) return self.request.response.redirect(self.request.URL[-1]+ '/@@synchronizeForm.html')
zope.app.i18n
/zope.app.i18n-4.1.0.tar.gz/zope.app.i18n-4.1.0/src/zope/app/i18n/browser/synchronize.py
synchronize.py
__docformat__ = 'restructuredtext' from persistent import Persistent from zope.interface import implements from zope.app.file.file import File from interfaces import II18nFile class I18nFile(Persistent): """I18n aware file object. It contains a number of File objects -- one for each language. """ implements(II18nFile) def __init__(self, data='', contentType=None, defaultLanguage='en'): self._data = {} self.defaultLanguage = defaultLanguage self.setData(data, language=defaultLanguage) self.contentType = contentType or '' def _create(self, data): """Create a new subobject of the appropriate type. Should be overriden in subclasses. """ return File(data) def getObject(self, language=None): """See interface `II18nFile`""" file = self._data.get(language) if not file: file = self._data[self.defaultLanguage] return file def _get_or_add(self, language, data=''): """Helper function -- return a subobject for a given language, and if it does not exist, create and return a new subobject. """ if language is None: language = self.defaultLanguage file = self._data.get(language) if not file: self._data[language] = file = self._create(data) self._p_changed = 1 return file def getData(self, language=None): """See interface `II18nFile`""" return self.getObject(language).data def setData(self, data, language=None): """See interface `II18nFile`""" self._get_or_add(language).data = data # See IFile. data = property(getData, setData) def getSize(self, language=None): """See interface `II18nFile`""" return self.getObject(language).getSize() def getDefaultLanguage(self): """See `II18nAware`""" return self.defaultLanguage def setDefaultLanguage(self, language): """See `II18nAware`""" if language not in self._data: raise ValueError( 'cannot set nonexistent language (%s) as default' % language) self.defaultLanguage = language def getAvailableLanguages(self): """See `II18nAware`""" return self._data.keys() def removeLanguage(self, language): """See interface `II18nFile`""" if language == self.defaultLanguage: raise ValueError('cannot remove default language (%s)' % language) if language in self._data: del self._data[language] self._p_changed = True
zope.app.i18nfile
/zope.app.i18nfile-3.4.1.tar.gz/zope.app.i18nfile-3.4.1/src/zope/app/i18nfile/i18nfile.py
i18nfile.py
__docformat__ = 'restructuredtext' from urllib import quote from zope.i18n.negotiator import negotiator from zope.size import ISized from zope.i18nmessageid import ZopeMessageFactory as _ from zope.app.file.browser.image import ImageData class I18nImageEdit(object): name = 'editForm' title = _('Edit Form') description = _('This edit form allows you to make changes to the ' 'properties of this image.') def size(self): if self.request is not None: language = self.request.get("language") else: language = None sized = ISized(self.context.getObject(language)) return sized.sizeForDisplay() def action(self, contentType, data, language, defaultLanguage, selectLanguage=None, removeLanguage=None, addLanguage=None, newLanguage=None): if selectLanguage: pass elif removeLanguage: self.context.removeLanguage(language) language = self.context.getDefaultLanguage() else: if addLanguage: language = newLanguage self.context.setDefaultLanguage(defaultLanguage) self.context.setData(data, language) self.context.contentType = contentType return self.request.response.redirect(self.request.URL[-1] + "/upload.html?language=%s" % quote(language, '')) class I18nImageData(ImageData): def __call__(self): image = self.context language = None if self.request is not None: langs = self.context.getAvailableLanguages() language = negotiator.getLanguage(langs, self.request) self.request.response.setHeader('content-type', image.contentType) return image.getData(language) def tag(self, height=None, width=None, **args): """See `ImageData.tag.`""" language = None if self.request is not None and \ (width is None or height is None): langs = self.context.getAvailableLanguages() language = negotiator.getLanguage(langs, self.request) if width is None: width = self.context.getImageSize(language)[0] if height is None: height = self.context.getImageSize(language)[1] return ImageData.tag(self, width=width, height=height, **args)
zope.app.i18nfile
/zope.app.i18nfile-3.4.1.tar.gz/zope.app.i18nfile-3.4.1/src/zope/app/i18nfile/browser/i18nimage.py
i18nimage.py
import getopt import os import sys import time import tokenize def _(s): return s __version__ = '1.4' default_keywords = ['_'] DEFAULTKEYWORDS = ', '.join(default_keywords) EMPTYSTRING = b'' # The normal pot-file header. msgmerge and Emacs's po-mode work better if it's # there. pot_header = _('''\ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR ORGANIZATION # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR. # msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\\n" "POT-Creation-Date: %(time)s\\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n" "Language-Team: LANGUAGE <[email protected]>\\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=CHARSET\\n" "Content-Transfer-Encoding: ENCODING\\n" "Generated-By: pygettext.py %(version)s\\n" ''') def usage(code, msg=''): print(_(__doc__) % globals(), file=sys.stderr) if msg: print(msg, file=sys.stderr) sys.exit(code) escapes = [] def make_escapes(pass_iso8859): global escapes if pass_iso8859: # Allow iso-8859 characters to pass through. Otherwise we # escape any character outside the 32..126 range. mod = 128 else: mod = 256 for i in range(256): if 32 <= (i % mod) <= 126: escapes.append(chr(i).encode("utf-8")) else: escapes.append(("\\%03o" % i).encode('utf-8')) escapes[ord(b'\\')] = b'\\\\' escapes[ord(b'\t')] = b'\\t' escapes[ord(b'\r')] = b'\\r' escapes[ord(b'\n')] = b'\\n' escapes[ord(b'\"')] = b'\\"' def escape(s): if bytes is not str: # iterating bytes in python 3 generates ints (their # ord) already. s = [escapes[x] for x in s] else: s = [escapes[ord(x)] for x in s] return EMPTYSTRING.join(s) def safe_eval(s): # unwrap quotes, safely return eval(s, {'__builtins__': {}}, {}) def normalize(s): # This converts the various Python string types into a format that is # appropriate for .po files, namely much closer to C style. lines = s.split(b'\n') if len(lines) == 1: s = b'"' + escape(s) + b'"' else: if not lines[-1]: del lines[-1] lines[-1] = lines[-1] + b'\n' for i in range(len(lines)): lines[i] = escape(lines[i]) lineterm = b'\\n"\n"' s = b'""\n"' + lineterm.join(lines) + b'"' return s class TokenEater: def __init__(self, options): self.__options = options self.__messages = {} self.__state = self.__waiting self.__data = [] self.__lineno = -1 self.__freshmodule = 1 self.__curfile = None def __call__(self, ttype, tstring, stup, etup, line): # dispatch self.__state(ttype, tstring, stup[0]) def __waiting(self, ttype, tstring, lineno): opts = self.__options # Do docstring extractions, if enabled if opts.docstrings and not opts.nodocstrings.get(self.__curfile): # module docstring? if self.__freshmodule: if ttype == tokenize.STRING: self.__addentry(safe_eval(tstring), lineno, isdocstring=1) self.__freshmodule = 0 elif ttype not in (tokenize.COMMENT, tokenize.NL): self.__freshmodule = 0 return # class docstring? if ttype == tokenize.NAME and tstring in ('class', 'def'): self.__state = self.__suiteseen return if ttype == tokenize.NAME and tstring in opts.keywords: self.__state = self.__keywordseen def __suiteseen(self, ttype, tstring, lineno): # ignore anything until we see the colon if ttype == tokenize.OP and tstring == ':': self.__state = self.__suitedocstring def __suitedocstring(self, ttype, tstring, lineno): # ignore any intervening noise if ttype == tokenize.STRING: self.__addentry(safe_eval(tstring), lineno, isdocstring=1) self.__state = self.__waiting elif ttype not in (tokenize.NEWLINE, tokenize.INDENT, tokenize.COMMENT): # there was no class docstring self.__state = self.__waiting def __keywordseen(self, ttype, tstring, lineno): if ttype == tokenize.OP and tstring == '(': self.__data = [] self.__lineno = lineno self.__state = self.__openseen else: self.__state = self.__waiting def __openseen(self, ttype, tstring, lineno): if ttype == tokenize.OP and tstring == ')': # We've seen the last of the translatable strings. Record the # line number of the first line of the strings and update the list # of messages seen. Reset state for the next batch. If there # were no strings inside _(), then just ignore this entry. if self.__data: self.__addentry(EMPTYSTRING.join(self.__data)) self.__state = self.__waiting elif ttype == tokenize.STRING: self.__data.append(safe_eval(tstring)) # TBD: should we warn if we seen anything else? def __addentry(self, msg, lineno=None, isdocstring=0): if lineno is None: lineno = self.__lineno if msg not in self.__options.toexclude: entry = (self.__curfile, lineno) self.__messages.setdefault(msg, {})[entry] = isdocstring def set_filename(self, filename): self.__curfile = filename self.__freshmodule = 1 def write(self, fp): options = self.__options timestamp = time.ctime(time.time()) # The time stamp in the header doesn't have the same format as that # generated by xgettext... print( pot_header % {'time': timestamp, 'version': __version__}, file=fp) # Sort the entries. First sort each particular entry's keys, then # sort all the entries by their first item. reverse = {} for k, v in self.__messages.items(): keys = sorted(v.keys()) reverse.setdefault(tuple(keys), []).append((k, v)) rkeys = reverse.keys() for rkey in sorted(rkeys): rentries = reverse[rkey] rentries.sort() for k, v in rentries: isdocstring = 0 # If the entry was gleaned out of a docstring, then add a # comment stating so. This is to aid translators who may wish # to skip translating some unimportant docstrings. if sum(v.values()): isdocstring = 1 # k is the message string, v is a dictionary-set of (filename, # lineno) tuples. We want to sort the entries in v first by # file name and then by line number. v = sorted(v.keys()) if not options.writelocations: pass # location comments are different b/w Solaris and GNU: elif options.locationstyle == options.SOLARIS: for filename, lineno in v: d = {'filename': filename, 'lineno': lineno} print( _('# File: %(filename)s, line: %(lineno)d') % d, file=fp) elif options.locationstyle == options.GNU: # fit as many locations on one line, as long as the # resulting line length doesn't exceeds 'options.width' locline = '#:' for filename, lineno in v: d = {'filename': filename, 'lineno': lineno} s = _(' %(filename)s:%(lineno)d') % d if len(locline) + len(s) <= options.width: locline = locline + s else: print(locline, file=fp) locline = "#:" + s if len(locline) > 2: print(locline, file=fp) if isdocstring: print('#, docstring', file=fp) print('msgid', normalize(k.encode("utf-8")), file=fp) print('msgstr ""\n', file=fp) def main(argv=None): global default_keywords if argv is None: # pragma: no cover argv = sys.argv[1:] try: opts, args = getopt.getopt( argv, 'ad:DEhk:Kno:p:S:Vvw:x:X:', ['extract-all', 'default-domain=', 'escape', 'help', 'keyword=', 'no-default-keywords', 'add-location', 'no-location', 'output=', 'output-dir=', 'style=', 'verbose', 'version', 'width=', 'exclude-file=', 'docstrings', 'no-docstrings', ]) except getopt.error as msg: # pragma: no cover usage(1, msg) # for holding option values class Options: # constants GNU = 1 SOLARIS = 2 # defaults extractall = 0 # FIXME: currently this option has no effect at all. escape = 0 keywords = [] outpath = '' outfile = 'messages.pot' writelocations = 1 locationstyle = GNU verbose = 0 width = 78 excludefilename = '' docstrings = 0 nodocstrings = {} options = Options() locations = {'gnu': options.GNU, 'solaris': options.SOLARIS, } # parse options for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-a', '--extract-all'): options.extractall = 1 elif opt in ('-d', '--default-domain'): options.outfile = arg + '.pot' elif opt in ('-E', '--escape'): options.escape = 1 elif opt in ('-D', '--docstrings'): options.docstrings = 1 elif opt in ('-k', '--keyword'): options.keywords.append(arg) elif opt in ('-K', '--no-default-keywords'): default_keywords = [] elif opt in ('-n', '--add-location'): options.writelocations = 1 elif opt in ('--no-location',): options.writelocations = 0 elif opt in ('-S', '--style'): options.locationstyle = locations.get(arg.lower()) if options.locationstyle is None: usage(1, _('Invalid value for --style: %s') % arg) elif opt in ('-o', '--output'): options.outfile = arg elif opt in ('-p', '--output-dir'): options.outpath = arg elif opt in ('-v', '--verbose'): options.verbose = 1 elif opt in ('-V', '--version'): print(_('pygettext.py (xgettext for Python) %s') % __version__) sys.exit(0) elif opt in ('-w', '--width'): try: options.width = int(arg) except ValueError: usage(1, _('--width argument must be an integer: %s') % arg) elif opt in ('-x', '--exclude-file'): options.excludefilename = arg elif opt in ('-X', '--no-docstrings'): with open(arg) as fp: while 1: line = fp.readline() if not line: break options.nodocstrings[line[:-1]] = 1 # calculate escapes make_escapes(options.escape) # calculate all keywords options.keywords.extend(default_keywords) # initialize list of strings to exclude if options.excludefilename: try: with open(options.excludefilename) as fp: options.toexclude = fp.readlines() except OSError: print(_( "Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr) sys.exit(1) else: options.toexclude = [] # slurp through all the files eater = TokenEater(options) for filename in args: if filename == '-': if options.verbose: print(_('Reading standard input')) fp = sys.stdin closep = 0 else: if options.verbose: print(_('Working on %s') % filename) fp = open(filename, 'rb') closep = 1 try: eater.set_filename(filename) try: for t in tokenize.tokenize(fp.readline): eater(*t) except tokenize.TokenError as e: # pragma: no cover print('%s: %s, line %d, column %d' % ( e[0], filename, e[1][0], e[1][1]), file=sys.stderr) finally: if closep: fp.close() # write the output if options.outfile == '-': fp = sys.stdout closep = 0 else: if options.outpath: options.outfile = os.path.join(options.outpath, options.outfile) fp = open(options.outfile, 'w') closep = 1 try: eater.write(fp) finally: if closep: fp.close() if __name__ == '__main__': main() # some more test strings _('a unicode string')
zope.app.locales
/zope.app.locales-5.0-py3-none-any.whl/zope/app/locales/pygettext.py
pygettext.py
import fnmatch import functools import getopt import os import sys import time import tokenize import traceback from collections import defaultdict import zope.cachedescriptors.property from zope.i18nmessageid import Message from zope.interface import implementer from zope.app.locales.interfaces import IPOTEntry from zope.app.locales.interfaces import IPOTMaker from zope.app.locales.interfaces import ITokenEater from zope.app.locales.pygettext import make_escapes from zope.app.locales.pygettext import normalize from zope.app.locales.pygettext import safe_eval DEFAULT_CHARSET = 'UTF-8' DEFAULT_ENCODING = '8bit' _import_chickens = {}, {}, ("*",) # dead chickens needed by __import__ DEFAULT_POT_HEADER = pot_header = '''\ ############################################################################## # # Copyright (c) 2003-2019 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## msgid "" msgstr "" "Project-Id-Version: %(version)s\\n" "POT-Creation-Date: %(time)s\\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n" "Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n" "Language-Team: Zope 3 Developers <[email protected]>\\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=%(charset)s\\n" "Content-Transfer-Encoding: %(encoding)s\\n" "Generated-By: zope/app/locales/extract.py\\n" ''' @implementer(IPOTEntry) @functools.total_ordering class POTEntry: r"""This class represents a single message entry in the POT file. >>> make_escapes(0) >>> class FakeFile(object): ... def write(self, data): ... assert isinstance(data, bytes), data ... print(data.decode('utf-8')) Let's create a message entry: >>> entry = POTEntry(Message("test", default="default")) >>> entry.addComment("# Some comment") >>> entry.addLocationComment(os.path.join("path", "file"), 10) Then we feed it a fake file: >>> entry.write(FakeFile()) # Some comment #: path/file:10 #. Default: "default" msgid "test" msgstr "" <BLANKLINE> Multiline default values generate correct comments: >>> entry = POTEntry(Message("test", default="\nline1\n\tline2")) >>> entry.write(FakeFile()) #. Default: "" #. "line1\n" #. "\tline2" msgid "test" msgstr "" <BLANKLINE> Unicode can be used in msgids and default values: >>> entry = POTEntry(Message(u"\u263B", default=u"\u253A")) >>> entry.write(FakeFile()) #. Default: "\342\224\272" msgid "\342\230\273" msgstr "" <BLANKLINE> But msgid might be an ascii encoded string and `default` might be a (byte) string with the DEFAULT_ENCODING, too: >>> entry = POTEntry(Message("Oe", default=b"\xd6")) >>> entry.write(FakeFile()) #. Default: "\326" msgid "Oe" msgstr "" <BLANKLINE> Entries are fully ordered by msgid and then locations; comments are ignored: >>> entry = POTEntry('aaa') >>> entry_w_comment = POTEntry('aaa') >>> entry_w_comment.addComment('comment') >>> entry == entry_w_comment True >>> entry_w_comment.addLocationComment('zzz', 123) >>> entry == entry_w_comment False >>> entry < entry_w_comment True Each location is only stored once: >>> entry = POTEntry('aaa') >>> entry.addLocationComment('zzz', 123) >>> entry.addLocationComment('zzz', 123) >>> entry.locations (('zzz', 123),) The cache is cleared on a new entry: >>> entry = POTEntry('aaa') >>> entry.addLocationComment('zzz', 123) >>> entry.addLocationComment('yyy', 456) >>> entry.locations (('yyy', 456), ('zzz', 123)) """ def __init__(self, msgid, comments=None): self.msgid = msgid self.comments = comments or '' self._locations = set() @zope.cachedescriptors.property.Lazy def locations(self): return tuple(sorted(self._locations)) def addComment(self, comment): self.comments += comment + '\n' def addLocationComment(self, filename, line): filename = filename.replace(os.sep, '/') self._locations.add((filename, line)) try: # purge the cache. del self.locations except AttributeError: pass def write(self, file): if self.comments: file.write(self.comments.encode(DEFAULT_CHARSET) if not isinstance(self.comments, bytes) else self.comments) for filename, line in self.locations: file.write(b'#: %s:%d\n' % (filename.encode(DEFAULT_CHARSET), line)) if (isinstance(self.msgid, Message) and self.msgid.default is not None): default = self.msgid.default.strip() if not isinstance(default, bytes): default = default.encode(DEFAULT_CHARSET) lines = normalize(default).split(b"\n") lines[0] = b"#. Default: %s\n" % lines[0] for i in range(1, len(lines)): lines[i] = b"#. %s\n" % lines[i] file.write(b"".join(lines)) msgid = self.msgid.encode(DEFAULT_CHARSET) file.write(b'msgid %s\n' % normalize(msgid)) file.write(b'msgstr ""\n') file.write(b'\n') def __eq__(self, other): if not isinstance(other, POTEntry): return NotImplemented # pragma: no cover return self.locations == other.locations and self.msgid == other.msgid def __lt__(self, other): if not isinstance(other, POTEntry): return NotImplemented # pragma: no cover return ((self.locations, self.msgid) < (other.locations, other.msgid)) def __repr__(self): return '<POTEntry: %r>' % self.msgid @implementer(IPOTMaker) class POTMaker: """This class inserts sets of strings into a POT file.""" def __init__(self, output_fn, path, header_template=None): self._output_filename = output_fn self.path = path if header_template is not None: if os.path.exists(header_template): with open(header_template) as file: self._pot_header = file.read() else: raise ValueError( "Path {!r} derived from {!r} does not exist.".format( os.path.abspath(header_template), header_template)) else: self._pot_header = DEFAULT_POT_HEADER self.catalog = {} def add(self, strings, base_dir=None): for msgid, locations in strings.items(): if msgid == '': continue if msgid not in self.catalog: self.catalog[msgid] = POTEntry(msgid) for filename, lineno in locations: if base_dir: filename = strip_base_dir(filename, base_dir) self.catalog[msgid].addLocationComment(filename, lineno) def _getProductVersion(self): # First, try to get the product version fn = os.path.join(self.path, 'version.txt') if os.path.exists(fn): with open(fn) as f: return f.read().strip() return "Unknown" def write(self): with open(self._output_filename, 'wb') as file: formatted_header = self._pot_header % { 'time': time.ctime(), 'version': self._getProductVersion(), 'charset': DEFAULT_CHARSET, 'encoding': DEFAULT_ENCODING} file.write(formatted_header.encode(DEFAULT_CHARSET)) # Sort the catalog entries by filename catalog = self.catalog.values() # Write each entry to the file for entry in sorted(catalog): entry.write(file) @implementer(ITokenEater) class TokenEater: """This is almost 100% taken from `pygettext.py`, except that I removed all option handling and output a dictionary. >>> eater = TokenEater() >>> make_escapes(0) TokenEater eats tokens generated by the standard python module `tokenize`. >>> from io import BytesIO We feed it a (fake) file: >>> file = BytesIO( ... b"_(u'hello ${name}', u'buenos dias', {'name': 'Bob'}); " ... b"_(u'hi ${name}', mapping={'name': 'Bob'}); " ... b"_('k, bye', ''); " ... b"_('kthxbye')" ... ) >>> for t in tokenize.tokenize(file.readline): ... eater(*t) The catalog of collected message ids contains our example >>> catalog = eater.getCatalog() >>> items = sorted(catalog.items()) >>> items [(u'hello ${name}', [(None, 1)]), (u'hi ${name}', [(None, 1)]), (u'k, bye', [(None, 1)]), (u'kthxbye', [(None, 1)])] The key in the catalog is not a unicode string, it's a real message id with a default value: >>> msgid = items.pop(0)[0] >>> msgid u'hello ${name}' >>> msgid.default u'buenos dias' >>> msgid = items.pop(0)[0] >>> msgid u'hi ${name}' >>> msgid.default >>> msgid = items.pop(0)[0] >>> msgid u'k, bye' >>> msgid.default u'' >>> msgid = items.pop(0)[0] >>> msgid u'kthxbye' >>> msgid.default Note that everything gets converted to unicode. """ def __init__(self): self.__messages = {} self.__state = self.__waiting self.__data = [] self.__lineno = -1 self.__freshmodule = 1 self.__curfile = None def __call__(self, ttype, tstring, stup, etup, line): self.__state(ttype, tstring, stup[0]) def __waiting(self, ttype, tstring, lineno): if ttype == tokenize.NAME and tstring in ('_',): self.__state = self.__keywordseen def __keywordseen(self, ttype, tstring, lineno): if ttype == tokenize.OP and tstring == '(': self.__data = [] self.__msgid = '' self.__default = None self.__lineno = lineno self.__state = self.__openseen else: self.__state = self.__waiting def __openseen(self, ttype, tstring, lineno): if ((ttype == tokenize.OP and tstring == ')') or (ttype == tokenize.NAME and tstring == 'mapping')): # We've seen the last of the translatable strings. Record the # line number of the first line of the strings and update the list # of messages seen. Reset state for the next batch. If there # were no strings inside _(), then just ignore this entry. if self.__data or self.__msgid: if self.__default: msgid = self.__msgid default = self.__default elif self.__msgid: msgid = self.__msgid if self.__data: default = ''.join(self.__data) else: default = None else: msgid = ''.join(self.__data) default = None self.__addentry(msgid, default) self.__state = self.__waiting elif ttype == tokenize.OP and tstring == ',': if not self.__msgid: self.__msgid = ''.join(self.__data) elif not self.__default and self.__data: self.__default = ''.join(self.__data) self.__data = [] elif ttype == tokenize.STRING: self.__data.append(safe_eval(tstring)) def __addentry(self, msg, default=None, lineno=None, isdocstring=0): if lineno is None: lineno = self.__lineno if default is not None and not isinstance(default, str): default = default.decode(DEFAULT_CHARSET) msg = Message(msg, default=default) entry = (self.__curfile, lineno) self.__messages.setdefault(msg, {})[entry] = isdocstring def set_filename(self, filename): self.__curfile = filename self.__freshmodule = 1 def getCatalog(self): catalog = {} # Sort the entries. First sort each particular entry's keys, then # sort all the entries by their first item. reverse = defaultdict(list) for k, v in self.__messages.items(): reverse[tuple(sorted(v.keys()))].append((k, v)) rkeys = reverse.keys() for rkey in sorted(rkeys): rentries = reverse[rkey] rentries.sort() for msgid, locations in rentries: catalog[msgid] = [] locations = locations.keys() for filename, lineno in sorted(locations): catalog[msgid].append((filename, lineno)) return catalog def find_files(dir, pattern, exclude=()): files = [] for dirpath, _dirnames, filenames in os.walk(dir): files.extend( [os.path.join(dirpath, name) for name in fnmatch.filter(filenames, pattern) if name not in exclude]) return files def relative_path_from_filename(filename, sys_path=None): """Translate a filename into a relative path. We are using the python path to determine what the shortest relative path should be: >>> sys_path = ["/src/project/Zope3/src/", ... "/src/project/src/schooltool", ... "/python2.4/site-packages"] >>> relative_path_from_filename( ... "/src/project/src/schooltool/module/__init__.py", ... sys_path=sys_path) 'module/__init__.py' >>> relative_path_from_filename( ... "/src/project/src/schooltool/module/file.py", ... sys_path=sys_path) 'module/file.py' >>> relative_path_from_filename( ... "/src/project/Zope3/src/zope/app/locales/extract.py", ... sys_path=sys_path) 'zope/app/locales/extract.py' """ if sys_path is None: sys_path = sys.path filename = os.path.abspath(filename) common_path_lengths = [ len(os.path.commonprefix([filename, os.path.abspath(path)])) for path in sys_path] s = max(common_path_lengths) + 1 # a path in sys.path ends with a separator if filename[s - 2] == os.path.sep: s -= 1 return filename[s:] def module_from_filename(filename, sys_path=None): """Translate a filename into a name of a module. We are using the python path to determine what the shortest module name should be: >>> sys_path = ["/src/project/Zope3/src/", ... "/src/project/src/schooltool", ... "/python2.4/site-packages"] >>> module_from_filename( ... "/src/project/src/schooltool/module/__init__.py", ... sys_path=sys_path) 'module' >>> module_from_filename( ... "/src/project/src/schooltool/module/file.py", ... sys_path=sys_path) 'module.file' >>> module_from_filename( ... "/src/project/Zope3/src/zope/app/locales/extract.py", ... sys_path=sys_path) 'zope.app.locales.extract' """ filename = relative_path_from_filename(filename, sys_path) # remove .py ending from filenames # replace all path separators with a dot # remove the __init__ from the import path return filename[:-3].replace(os.path.sep, ".").replace(".__init__", "") def py_strings(dir, domain="zope", exclude=(), verify_domain=False): """Retrieve all Python messages from `dir` that are in the `domain`. Retrieves all the messages in all the domains if verify_domain is False. """ eater = TokenEater() make_escapes(0) filenames = find_files( dir, '*.py', exclude=('extract.py', 'pygettext.py') + tuple(exclude) ) for filename in filenames: if verify_domain: module_name = module_from_filename(filename) try: module = __import__(module_name, *_import_chickens) except ImportError: # pragma: no cover # XXX if we can't import it - we assume that the domain is # the right one print("Could not import %s, " "assuming i18n domain OK" % module_name, file=sys.stderr) else: mf = getattr(module, '_', None) # XXX if _ is has no _domain set we assume that the domain # is the right one, so if you are using something non # MessageFactory you should set it's _domain attribute. if hasattr(mf, '_domain'): if mf._domain != domain: # domain mismatch - skip this file continue elif mf: print("Could not figure out the i18n domain" " for module %s, assuming it is OK" % module_name, file=sys.stderr) with open(filename, 'rb') as fp: eater.set_filename(filename) try: for t in tokenize.tokenize(fp.readline): eater(*t) except tokenize.TokenError as e: # pragma: no cover print('%s: %s, line %d, column %d' % ( e[0], filename, e[1][0], e[1][1]), file=sys.stderr) return eater.getCatalog() def _relative_locations(locations): """Return `locations` with relative paths. locations: list of tuples(path, lineno) """ return [(relative_path_from_filename(path), lineno) for path, lineno in locations] def zcml_strings(dir, domain="zope", site_zcml=None): """Retrieve all ZCML messages from `dir` that are in the `domain`.""" from zope.configuration import config from zope.configuration import xmlconfig # Load server-independent site config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context.provideFeature("devmode") context = xmlconfig.file(site_zcml, context=context, execute=False) strings = context.i18n_strings.get(domain, {}) strings = {key: _relative_locations(value) for key, value in strings.items()} return strings def tal_strings(dir, domain="zope", include_default_domain=False, exclude=(), filePattern='*.pt'): """Retrieve all TAL messages from `dir` that are in the `domain`. >>> from zope.app.locales import extract >>> import tempfile >>> dir = tempfile.mkdtemp() Let's create a page template in the i18n domain ``test``: >>> with open(os.path.join(dir, 'test.pt'), 'w') as testpt: ... _ = testpt.write( ... '<tal:block i18n:domain="test"' ... ' i18n:translate="">test</tal:block>') And now one in no domain: >>> with open(os.path.join(dir, 'no.pt'), 'w') as nopt: ... _ = nopt.write( ... '<tal:block i18n:translate="">no domain</tal:block>') Now let's find the strings for the domain ``test``: >>> strs = extract.tal_strings( ... dir, domain='test', include_default_domain=True) >>> len(strs) 2 >>> strs[u'test'] [('...test.pt', 1)] >>> strs[u'no domain'] [('...no.pt', 1)] And now an xml file >>> with open(os.path.join(dir, 'xml.pt'), 'w') as xml: ... _ = xml.write('''<?xml version="1.0" encoding="utf-8"?> ... <rss version="2.0" ... i18n:domain="xml" ... xmlns:i18n="http://xml.zope.org/namespaces/i18n" ... xmlns:tal="http://xml.zope.org/namespaces/tal" ... xmlns="http://purl.org/rss/1.0/modules/content/"> ... <channel> ... <link i18n:translate="">Link Content</link> ... </channel> ... </rss> ... ''') >>> extract.tal_strings(dir, domain='xml') {u'Link Content': [('...xml.pt', 8)]} We also provide a file with a different file ending: >>> with open(os.path.join(dir, 'test.html'), 'w') as testpt: ... _ = testpt.write( ... '<tal:block i18n:domain="html"' ... ' i18n:translate="">html</tal:block>') >>> extract.tal_strings(dir, domain='html', include_default_domain=True, ... filePattern='*.html') {u'html': [('...test.html', 1)]} Cleanup >>> import shutil >>> shutil.rmtree(dir) """ # We import zope.tal.talgettext here because we can't rely on the # right sys path until app_dir has run from zope.tal.htmltalparser import HTMLTALParser from zope.tal.talgettext import POEngine from zope.tal.talgettext import POTALInterpreter from zope.tal.talparser import TALParser engine = POEngine() class Devnull: def write(self, s): pass for filename in find_files(dir, filePattern, exclude=tuple(exclude)): with open(filename, 'rb') as f: start = f.read(6) if start.startswith(b'<?xml'): parserFactory = TALParser else: parserFactory = HTMLTALParser try: engine.file = filename p = parserFactory() p.parseFile(filename) program, macros = p.getCode() POTALInterpreter(program, macros, engine, stream=Devnull(), metal=False)() except Exception: # pragma: no cover print('There was an error processing', filename) traceback.print_exc() # See whether anything in the domain was found if domain not in engine.catalog: return {} # We do not want column numbers. catalog = engine.catalog[domain].copy() # When the Domain is 'default', then this means that none was found; # Include these strings; yes or no? if include_default_domain: defaultCatalog = engine.catalog.get('default') if defaultCatalog is None: engine.catalog['default'] = {} catalog.update(engine.catalog['default']) for msgid, locations in list(catalog.items()): catalog[msgid] = [(loc[0], loc[1][0]) for loc in locations] return catalog USAGE = """Program to extract internationalization markup from Python Code, Page Templates and ZCML. This tool will extract all findable message strings from all internationalizable files in your Zope code. It only extracts message IDs of the specified domain, except in Python code where it extracts *all* message strings (because it can't detect which domain they are created with). Usage: i18nextract -p PATH -s .../site.zcml [options] Options: -p / --path <path> Specifies the directory that is supposed to be searched for modules (i.e. 'src'). This argument is mandatory. -s / --site_zcml <path> Specify the location of the root ZCML file to parse (typically 'site.zcml'). This argument is mandatory -d / --domain <domain> Specifies the domain that is supposed to be extracted (defaut: 'zope') -e / --exclude-default-domain Exclude all messages found as part of the default domain. Messages are in this domain, if their domain could not be determined. This usually happens in page template snippets. -o dir Specifies a directory, relative to the package in which to put the output translation template. -x dir Specifies a directory, relative to the package, to exclude. May be used more than once. --python-only Only extract message ids from Python -h / --help Print this message and exit. """ def usage(code, msg=''): if not msg: msg = USAGE print(msg, file=sys.stderr) sys.exit(code) def normalize_path(path): """Normalize a possibly relative path or symlink""" if path == os.path.abspath(path): return path # This is for symlinks. Thanks to Fred for this trick. cwd = os.getcwd() if 'PWD' in os.environ: cwd = os.environ['PWD'] return os.path.normpath(os.path.join(cwd, path)) def strip_base_dir(filename, base_dir): """Strip base directory from filename if it starts there. >>> strip_base_dir('/path/to/base/relpath/to/file', ... '/path/to/base/') 'relpath/to/file' >>> strip_base_dir('/path/to/somewhere/else/relpath/to/file', ... '/path/to/base/') '/path/to/somewhere/else/relpath/to/file' """ if filename.startswith(base_dir): filename = filename[len(base_dir):] return filename def main(argv=None): if argv is None: # pragma: no cover argv = sys.argv[1:] try: opts, args = getopt.getopt( argv, 'hd:s:i:p:o:x:', ['help', 'domain=', 'site_zcml=', 'path=', 'python-only']) except getopt.error as msg: # pragma: no cover usage(1, msg) domain = 'zope' path = None include_default_domain = True output_dir = None exclude_dirs = [] python_only = False site_zcml = None for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-d', '--domain'): domain = arg elif opt in ('-s', '--site_zcml'): if not os.path.exists(arg): usage(1, 'The specified location for site.zcml does not exist') site_zcml = normalize_path(arg) elif opt in ('-e', '--exclude-default-domain'): include_default_domain = False elif opt in ('-o', ): output_dir = arg elif opt in ('-x', ): exclude_dirs.append(arg) elif opt in ('--python-only',): python_only = True elif opt in ('-p', '--path'): if not os.path.exists(arg): usage(1, 'The specified path does not exist.') path = normalize_path(arg) if path is None: usage(1, 'You need to provide the module search path with -p PATH.') sys.path.insert(0, path) if site_zcml is None: usage(1, "You need to provide the location of the root ZCML file \n" "(typically 'site.zcml') with -s .../site.zcml.") # When generating the comments, we will not need the base directory info, # since it is specific to everyone's installation src_start = path.rfind('src') base_dir = path[:src_start] output_file = domain + '.pot' if output_dir: output_dir = os.path.join(path, output_dir) if not os.path.exists(output_dir): os.mkdir(output_dir) output_file = os.path.join(output_dir, output_file) print("base path: %r\n" "search path: %s\n" "'site.zcml' location: %s\n" "exclude dirs: %r\n" "domain: %r\n" "include default domain: %r\n" "output file: %r\n" "Python only: %r" % (base_dir, path, site_zcml, exclude_dirs, domain, include_default_domain, output_file, python_only)) maker = POTMaker(output_file, path) maker.add(py_strings(path, domain, exclude=exclude_dirs), base_dir) if not python_only: maker.add(zcml_strings(path, domain, site_zcml), base_dir) maker.add(tal_strings(path, domain, include_default_domain, exclude=exclude_dirs), base_dir) maker.write()
zope.app.locales
/zope.app.locales-5.0-py3-none-any.whl/zope/app/locales/extract.py
extract.py
=================================================== Internationalization (I18n) and Localization (L10n) =================================================== This document assumes that you have a Zope 3 checkout and the gettext utilities installed. Creating/Updating Message Catalog Template (POT) Files ------------------------------------------------------ Whenever you've made a change to Zope that affects the i18n messages, you need to re-extract i18n messages from the code. To do that, execute ``i18nextract.py`` from the ``utilities`` directory of your Zope 3 checkout: $ python utilities/i18nextract.py -d zope -p src/zope -o app/locales This will update the ``zope.pot`` file. Make sure that the checkout's ``src`` directory is part of your ``PYTHONPATH`` environment variable. After that, you need to merge those changes to all existing translations. You can do that by executing the ``i18nmergeall.py`` script from the ``utilities`` directory of your Zope 3 checkout: $ python utilities/i18nmergeall.py -l src/zope/app/locales Translating ----------- To translate messages you need to do the following steps: 1. If a translation for your language is already present and you just want to update, skip ahead to step 2. If you want to start translation on a new language, you need to a) create a directory src/zope/app/locales/<lang_code>/LC_MESSAGES with the appropriate code for your language as <lang_code>. Note that the two letters specifying the language should always be lower case (e.g. 'pt'); if you additionally specify a region, those letters should be upper case (e.g. 'pt_BR'). b) copy the ``zope.pot`` template file to ``<lang_code>/LC_MESSAGES/zope.po``. c) edit the PO header of the newly created ``zope.po`` file and fill in all the necessary information. 2. Translate messages within the PO file. Make sure the gettext syntax stays intact. Tools like poEdit and KBabel can help you. 3. Finally, when you're done translating, compile the PO file to its binary equivalent using the ``msgfmt`` tool: $ cd <lang_code>/LC_MESSAGES $ msgfmt -o zope.mo zope.po
zope.app.locales
/zope.app.locales-5.0-py3-none-any.whl/zope/app/locales/TRANSLATE.rst
TRANSLATE.rst
========= CHANGES ========= 5.0 (2023-02-08) ================ - Drop support for Python 2.7, 3.4, 3.5, 3.6. - Add support for Python 3.8, 3.9, 3.10, 3.11. 4.1.0 (2018-10-19) ================== - Add support for Python 3.7. 4.0.0 (2017-04-23) ================== - Add support for PyPy. - Add support for Python 3.4, 3.5, and 3.6. - Remove dependency on ZODB3. Instead, depend on the separate ``persistent`` package. 3.7.2 (2010-03-21) ================== - Added missing i18n domain to ``browser.zcml``. 3.7.1 (2010-02-22) ================== - The zope.app namespace wasn't declared correctly. 3.7.0 (2009-03-14) ================== Initial release. This package was extracted from zope.app.security to separate the functionality without additional dependencies.
zope.app.localpermission
/zope.app.localpermission-5.0.tar.gz/zope.app.localpermission-5.0/CHANGES.rst
CHANGES.rst
"""Persistent Local Permissions """ __docformat__ = 'restructuredtext' from persistent import Persistent from zope.component import adapter from zope.i18nmessageid import MessageFactory from zope.interface import implementer from zope.interface.interfaces import IRegistered from zope.interface.interfaces import IUnregistered from zope.location import Location from zope.security.interfaces import IPermission _ = MessageFactory('zope') NULL_ID = _('<permission not activated>') @implementer(IPermission) class LocalPermission(Persistent, Location): def __init__(self, title='', description=''): self.id = NULL_ID self.title = title self.description = description @adapter(IPermission, IRegistered) def setIdOnActivation(permission, event): """Set the permission id upon registration activation. Let's see how this notifier can be used. First we need to create an event using the permission instance and a registration stub: >>> class Registration(object): ... def __init__(self, obj, name): ... self.component = obj ... self.name = name >>> perm1 = LocalPermission('Permission 1', 'A first permission') >>> print(perm1.id) <permission not activated> >>> import zope.interface.interfaces >>> event = zope.interface.interfaces.Registered( ... Registration(perm1, 'perm1')) Now we pass the event into this function, and the id of the permission should be set to 'perm1'. >>> setIdOnActivation(perm1, event) >>> perm1.id 'perm1' """ permission.id = event.object.name @adapter(IPermission, IUnregistered) def unsetIdOnDeactivation(permission, event): """Unset the permission id up registration deactivation. Let's see how this notifier can be used. First we need to create an event using the permission instance and a registration stub: >>> class Registration(object): ... def __init__(self, obj, name): ... self.component = obj ... self.name = name >>> perm1 = LocalPermission('Permission 1', 'A first permission') >>> perm1.id = 'perm1' >>> import zope.interface.interfaces >>> event = zope.interface.interfaces.Unregistered( ... Registration(perm1, 'perm1')) Now we pass the event into this function, and the id of the permission should be set to NULL_ID. >>> unsetIdOnDeactivation(perm1, event) >>> print(perm1.id) <permission not activated> """ permission.id = NULL_ID
zope.app.localpermission
/zope.app.localpermission-5.0.tar.gz/zope.app.localpermission-5.0/src/zope/app/localpermission/permission.py
permission.py
from zope import interface, schema from zope.component.interfaces import ObjectEvent, IObjectEvent from zope.interface.common.mapping import IMapping from zope.i18nmessageid import ZopeMessageFactory as _ class ILockable(interface.Interface): """ The ILockable interface defines the locking operations that are supported for lockable objects. """ def lock(principal=None, timeout=None): """ Lock the object in the name of the current principal. This method raises a LockingError if the object cannot be locked by the current principal. """ def unlock(): """ Unlock the object. If the current principal does not hold a lock on the object, this method raises a LockingError. """ def breaklock(): """ Break the lock on the object, regardless of whether the current principal created the lock. Raises a LockingError if there is not a lock on the object """ def locked(): """ Returns true if the object is locked. """ def locker(): """ Return the principal id of the principal that owns the lock on the object, or None if the object is not locked. """ def getLockInfo(): """ Return an ILockInfo describing the current lock or None. """ def ownLock(): """ Returns true if the object is locked by the current principal. """ def isLockedOut(): """ Returns true if the object is locked by a principal other than the current principal. """ class ILockTracker(interface.Interface): """ An ILockTracker implementation is responsible for tracking what objects are locked within its scope. """ def getLocksForPrincipal(principal_id): """ Return a sequence of all locks held by the given principal. """ def getAllLocks(): """ Return a sequence of all currently held locks. """ class ILockInfo(IMapping): """ An ILockInfo implementation is responsible for """ target = interface.Attribute("""the actual locked object.""") principal_id = schema.TextLine( description=_("id of the principal owning the lock") ) created = schema.Float( description=_("time value indicating the creation time"), required=False ) timeout = schema.Float( description=_("time value indicating the lock timeout from creation"), required=False ) class ILockStorage(interface.Interface): """ A lock storage lets you store information about locks in a central place """ def getLock(object): """ Get the current lock for an object. """ def setLock(object, lock): """ Set the current lock for an object. """ def delLock(object): """ Delete the current lock for an object. """ def cleanup(): """We occasionally want to clean up expired locks to keep them from accumulating over time and slowing things down. """ # event interfaces class ILockedEvent(IObjectEvent): """An object has been locked""" lock = interface.Attribute("The lock set on the object") class IUnlockedEvent(IObjectEvent): """An object has been unlocked""" class IBreakLockEvent(IUnlockedEvent): """Lock has been broken on an object""" # events class EventBase(ObjectEvent): def __repr__(self): return '%s for %s' % (self.__class__.__name__, `self.object`) class LockedEvent(EventBase): interface.implements(ILockedEvent) def __init__(self, object, lock): self.object = object self.lock = lock class UnlockedEvent(EventBase): interface.implements(IUnlockedEvent) class BreakLockEvent(UnlockedEvent): interface.implements(IBreakLockEvent) # exceptions class LockingError(Exception): """ The exception raised for locking errors. """
zope.app.locking
/zope.app.locking-3.5.0.tar.gz/zope.app.locking-3.5.0/src/zope/app/locking/interfaces.py
interfaces.py
============== Object Locking ============== This package provides a framework for object locking. The implementation is intended to provide a simple general-purpose locking architecture upon which other locking applications can be built (WebDAV locking, for example). The locking system is purely *advisory* - it provides a way to associate a lock with an object, but it does not enforce locking in any way. It is up to application-level code to ensure that locked objects are restricted in a way appropriate to the application. The Zope 3 locking model defines interfaces and a default implementation that: - allows for a single lock on an object, owned by a specific principal - does not necessarily impose inherent semantic meaning (exclusive vs. non-exclusive, write vs. read) on locks, though it will provide fields that higher-level application components can use to implement and enforce such semantics - can potentially be used to build more ambitious locking mechanisms (such as WebDAV locking equivalent to Zope 2) - supports common use cases that have been uncovered in several years of development of real-world applications (such as reporting all of the objects locked by a given user) The Zope3 locking architecture defines an `ILockable` interface and provides a default adapter implementation that requires only that an object be adaptable to `IKeyReference`. All persistent objects can be adapted to this interface by default in Zope 3, so in practice all persistent objects are lockable. The default `ILockable` adapter implementation provides support for: - locking and unlocking an object - breaking an existing lock on an object - obtaining the lock information for an object Locking operations (lock, unlock, break lock) fire events that may be handled by applications or other components to interact with the locking system in a loosely-coupled way. Lock information is accessible through an object that supports the `ILockInfo` interface. The `ILockInfo` interface implies `IAnnotatable`, so that other locking implementations (superseding or complementing the default implementation) can store more information if needed to support extended locking semantics. The locking architecture also supports an efficient method of lock tracking that allows you to determine what locks are held on objects. The default implementation provides an `ILockTracker` utility that can be used by applications to quickly find all objects locked by a particular principal. Locking essentials ------------------ Normally, locking is provided by the default locking implementation. In this example, we'll create a simple content class. The content class is persistent, which allows us to use the default locking adapters and utilities. >>> import persistent >>> class Content(persistent.Persistent): ... """A sample content object""" ... ... def __init__(self, value): ... self.value = value ... ... def __call__(self): ... return self ... ... def __hash__(self): ... return self.value ... ... def __cmp__(self, other): ... return cmp(self.value, other.value) Now we will create a few sample objects to work with: >>> item1 = Content("item1") >>> item1.__name__ = "item1" >>> item2 = Content("item2") >>> item2.__name__ = "item2" >>> item3 = Content("item3") >>> item3.__name__ = "item3" It is possible to test whether an object supports locking by attempting to adapt it to the ILockable interface: >>> from zope.app.locking.interfaces import ILockable >>> from zope.app.locking.interfaces import ILockInfo >>> ILockable(item1, None) <Locking adapter for... >>> ILockable(42, None) There must be an active interaction to use locking, to allow the framework to determine the principal performing locking operations. This example sets up some sample principals and a helper to switch principals for further examples: >>> class FauxPrincipal: ... def __init__(self, id): ... self.id = id >>> britney = FauxPrincipal('britney') >>> tim = FauxPrincipal('tim') >>> class FauxParticipation: ... interaction = None ... def __init__(self, principal): ... self.principal = principal >>> import zope.security.management >>> def set_principal(principal): ... if zope.security.management.queryInteraction(): ... zope.security.management.endInteraction() ... participation = FauxParticipation(principal) ... zope.security.management.newInteraction(participation) >>> set_principal(britney) Now, let's look at basic locking. To perform locking operations, we first have to adapt an object to `ILockable`: >>> obj = ILockable(item1) >>> from zope.interface.verify import verifyObject >>> verifyObject(ILockable, obj) True We can ask if the object is locked: >>> obj.locked() False If it were locked, we could get the id of the principal that owns the lock. Since it is not locked, this will return `None`: >>> obj.locker() Now let's lock the object. Note that the lock method return an instance of an object that implements `ILockInfo` on success: >>> info = obj.lock() >>> verifyObject(ILockInfo, info) True >>> obj.locked() True >>> obj.locker() 'britney' Methods are provided to check whether the current principal already has the lock on an object and whether the lock is already owned by a different principal: >>> obj.ownLock() True >>> obj.isLockedOut() False If we switch principals, we see that the answers reflect the current principal: >>> set_principal(tim) >>> obj.ownLock() False >>> obj.isLockedOut() True A principal can only release his or her own locks: >>> obj.unlock() Traceback (most recent call last): ... LockingError: Principal is not lock owner If we switch back to the original principal, we see that the original principal can unlock the object: >>> set_principal(britney) >>> obj.unlock() There is a mechanism for breaking locks that does not take the current principal into account. This will break any existing lock on an object: >>> obj.lock() <...LockInfo...> >>> set_principal(tim) >>> obj.locked() True >>> obj.breaklock() >>> obj.locked() False Locks can be created with an optional timeout. If a timeout is provided, it should be an integer number of seconds from the time the lock is created. >>> # fake time function to avoid a time.sleep in tests! >>> import time >>> def faketime(): ... return time.time() + 3600.0 >>> obj.lock(timeout=10) <...LockInfo...> >>> obj.locked() True >>> import zope.app.locking.storage >>> zope.app.locking.storage.timefunc = faketime >>> obj.locked() False (Note that we undo our time hack in the tearDown of this module.) Finally, it is possible to explicitly get an `ILockInfo` object that contains the lock information for the object. Note that locks that do not have a timeout set have a timeout value of `None`. >>> obj = ILockable(item2) >>> obj.lock() <...LockInfo...> >>> info = obj.getLockInfo() >>> info.principal_id 'tim' >>> info.timeout It is possible to get the object associated with a lock directly from an `ILockInfo` instance: >>> target = info.target >>> target.__name__ == 'item2' True The `ILockInfo` interface extends the IMapping interface, so application code can store extra information on locks if necessary. It is recommended that keys for extra data use qualified names following the convention that is commonly used for annotations: >>> info['my.namespace.extra'] = 'spam' >>> info['my.namespace.extra'] 'spam' >>> obj.unlock() >>> obj.locked() False Lock tracking ------------- It is often desirable to be able to report on the currently held locks in a system (particularly on a per-user basis), without requiring an expensive brute-force search. An `ILockTracker` utility allows an application to get the current locks for a principal, or all current locks: >>> set_principal(tim) >>> obj = ILockable(item2) >>> obj.lock() <...LockInfo...> >>> set_principal(britney) >>> obj = ILockable(item3) >>> obj.lock() <...LockInfo...> >>> from zope.app.locking.interfaces import ILockTracker >>> from zope.component import getUtility >>> util = getUtility(ILockTracker) >>> verifyObject(ILockTracker, util) True >>> items = util.getLocksForPrincipal('britney') >>> len(items) == 1 True >>> items = util.getAllLocks() >>> len(items) >= 2 True These methods allow an application to create forms and other code that performs unlocking or breaking of locks on sets of objects: >>> items = util.getAllLocks() >>> for item in items: ... obj = ILockable(item.target) ... obj.breaklock() >>> items = util.getAllLocks() >>> len(items) 0 The lock storage utility provides further capabilities, and is a part of the standard lock adapter implementation, but the ILockable interface does not depend on ILockStorage. Other implementations of ILockable may not use ILockStorage. However, if used by the adapter, it provides useful capabilties. >>> from zope.app.locking.interfaces import ILockStorage >>> util = getUtility(ILockStorage) >>> verifyObject(ILockStorage, util) True Locking events -------------- Locking operations (lock, unlock, break lock) fire events that can be used by applications. Note that expiration of a lock *does not* fire an event (because the current implementation uses a lazy expiration approach). >>> import zope.event >>> def log_event(event): ... print event >>> zope.event.subscribers.append(log_event) >>> obj = ILockable(item2) >>> obj.lock() LockedEvent ... >>> obj.unlock() UnlockedEvent ... >>> obj.lock() LockedEvent ... >>> obj.breaklock() BreakLockEvent ... TALES conditions based on locking --------------------------------- TALES expressions can use a named path adapter to get information about the lock status for an object, including whether or not the object can be locked. The default registration for this adapter uses the name "locking", so a condition might be expressed like "context/locking:ownLock", for example. For objects that aren't lockable, the adapter provides information that makes sense:: >>> from zope.component import getAdapter >>> from zope.traversing.interfaces import IPathAdapter >>> ns = getAdapter(42, IPathAdapter, "locking") >>> ns.lockable False >>> ns.locked False >>> ns.lockedOut False >>> ns.ownLock False Using an object that's lockable, but unlocked, also gives the expected results:: >>> ns = getAdapter(item1, IPathAdapter, "locking") >>> ns.lockable True >>> ns.locked False >>> ns.lockedOut False >>> ns.ownLock False If we lock the object, the adapter indicates that the object is locked and that we own it:: >>> ob = ILockable(item1) >>> ob.lock() LockedEvent for ... >>> ns.lockable True >>> ns.locked True >>> ns.lockedOut False >>> ns.ownLock True
zope.app.locking
/zope.app.locking-3.5.0.tar.gz/zope.app.locking-3.5.0/src/zope/app/locking/README.txt
README.txt
from zope import interface, component, event import zope.security.management from zope.app.keyreference.interfaces import IKeyReference from zope.i18nmessageid import ZopeMessageFactory as _ from zope.app.locking.lockinfo import LockInfo from zope.app.locking import interfaces @component.adapter(interface.Interface) @interface.implementer(interfaces.ILockable) def LockingAdapterFactory(target): """ Return target adapted to ILockable, or None. This should be registered against zope.interface.Interface to provide adaptation to ILockable. """ if IKeyReference(target, None) is None: return None return LockingAdapter(target) class LockingAdapter(object): """ Default ILockable adapter implementation. """ # this MUST be a trusted adapter!! interface.implements(interfaces.ILockable) def __init__(self, context): self.storage = component.getUtility(interfaces.ILockStorage) self.context = context self.__parent__ = context def _findPrincipal(self): # Find the current principal. Note that it is possible for there # to be more than one principal - in this case we throw an error. interaction = zope.security.management.getInteraction() principal = None for p in interaction.participations: if principal is None: principal = p.principal else: raise interfaces.LockingError(_("Multiple principals found")) if principal is None: raise interfaces.LockingError(_("No principal found")) return principal def lock(self, timeout=None, principal=None): if principal is None: principal = self._findPrincipal() principal_id = principal.id lock = self.storage.getLock(self.context) if lock is not None: raise interfaces.LockingError(_("Object is already locked")) lock = LockInfo(self.context, principal_id, timeout) self.storage.setLock(self.context, lock) event.notify(interfaces.LockedEvent(self.context, lock)) return lock def unlock(self): lock = self.storage.getLock(self.context) if lock is None: raise interfaces.LockingError(_("Object is not locked")) principal = self._findPrincipal() if lock.principal_id != principal.id: raise interfaces.LockingError(_("Principal is not lock owner")) self.storage.delLock(self.context) event.notify(interfaces.UnlockedEvent(self.context)) def breaklock(self): lock = self.storage.getLock(self.context) if lock is None: raise interfaces.LockingError(_("Object is not locked")) self.storage.delLock(self.context) event.notify(interfaces.BreakLockEvent(self.context)) def locked(self): lock = self.storage.getLock(self.context) return lock is not None def locker(self): lock = self.storage.getLock(self.context) if lock is not None: return lock.principal_id return None def getLockInfo(self): return self.storage.getLock(self.context) def ownLock(self): lock = self.storage.getLock(self.context) if lock is not None: principal = self._findPrincipal() return lock.principal_id == principal.id return False def isLockedOut(self): lock = self.storage.getLock(self.context) if lock is not None: principal = self._findPrincipal() return lock.principal_id != principal.id return False def __repr__(self): return '<Locking adapter for %s>' % repr(self.context) class LockingPathAdapter(object): interface.implements(zope.traversing.interfaces.IPathAdapter) def __init__(self, target): self._locking = LockingAdapterFactory(target) self.lockable = self._locking is not None @property def lockedOut(self): return (self._locking is not None) and self._locking.isLockedOut() @property def locked(self): return (self._locking is not None) and self._locking.locked() @property def ownLock(self): return (self._locking is not None) and self._locking.ownLock()
zope.app.locking
/zope.app.locking-3.5.0.tar.gz/zope.app.locking-3.5.0/src/zope/app/locking/adapter.py
adapter.py
import time import persistent from BTrees.OOBTree import OOBTree from BTrees.IOBTree import IOBTree from zope import component, interface from zope.size.interfaces import ISized from zope.app.keyreference.interfaces import IKeyReference from zope.app.locking import interfaces # for backwards compatibility: from zope.app.locking.interfaces import ILockStorage from zope.i18nmessageid import ZopeMessageFactory as _ timefunc = time.time class LockStorage(object): # WARNING: This is not persistent. Use PersistentLockStorage instead. # This class must remain so that existing instances can be unpickled # from the database. New instances cannot be created without subclassing. # # The persistent.Persistent base class cannot be added to this # without causing the containers to fail to unpickle properly # since the pickle for a LockStorage is embedded in the pickle of # the containing object. For this reason, applications must # replace existing LockStorage instances with some new class. The # LockStorage instances don't need to be removed, but an alternate # class needs to be used instead. """Peristent storage for locks. This class implements both the ILockTracker utility as well as the internal ILockStorage utility which is used by the ILockable adapter implementation. It acts as the persistent storage for locks. """ interface.implements(interfaces.ILockStorage, interfaces.ILockTracker) def __init__(self): self.timeouts = IOBTree() self.locks = OOBTree() if self.__class__ is LockStorage: raise TypeError( "%s.LockStorage is insane; use a persistent subclass instead" " (%s.PersistentLockStorage should do nicely)" % (__name__, __name__)) # ILockTracker implementation def getLocksForPrincipal(self, principal_id): return self._currentLocks(principal_id) def getAllLocks(self): return self._currentLocks() def _currentLocks(self, principal_id=None): """ Helper method for getAllLocks and getLocksForPrincipal. Return the currently active locks, possibly filtered by principal. """ result = [] for lock in self.locks.values(): if principal_id is None or principal_id == lock.principal_id: if (lock.timeout is None or (lock.created + lock.timeout > timefunc()) ): result.append(lock) return result # ILockStorage implementation def getLock(self, object): """ Get the current lock for an object. """ keyref = IKeyReference(object) lock = self.locks.get(keyref, None) if lock is not None and lock.timeout is not None: if lock.created + lock.timeout < timefunc(): return None return lock def setLock(self, object, lock): """ Set the current lock for an object. """ ## call cleanup first so that if there is already a lock that ## has timed out for the object then we don't delete it. self.cleanup() keyref = IKeyReference(object) self.locks[keyref] = lock pid = lock.principal_id if lock.timeout: ts = int(lock.created + lock.timeout) value = self.timeouts.get(ts, []) value.append(keyref) self.timeouts[ts] = value def delLock(self, object): """ Delete the current lock for an object. """ keyref = IKeyReference(object) del self.locks[keyref] def cleanup(self): # We occasionally want to clean up expired locks to keep them # from accumulating over time and slowing things down. for key in self.timeouts.keys(max=int(timefunc())): for keyref in self.timeouts[key]: if self.locks.get(keyref, None) is not None: del self.locks[keyref] del self.timeouts[key] class Sized(object): interface.implements(ISized) component.adapts(interfaces.ILockStorage) def __init__(self, context): self.context = context def sizeForSorting(self): return ('item', self._get_size()) def sizeForDisplay(self): num_items = self._get_size() if num_items == 1: return _('1 item') return _('${items} items', mapping={'items': str(num_items)}) def _get_size(self): # We only want to include active locks, so we'd like to simply # call `cleanup()`, but we also don't want to cause the # transaction to write, so we adjust the count instead. nlocks = len(self.context.locks) for key in self.context.timeouts.keys(max=int(timefunc())): for keyref in self.context.timeouts[key]: if self.context.locks.get(keyref, None) is not None: nlocks -= 1 return nlocks class PersistentLockStorage(persistent.Persistent, LockStorage): """LockStorage that isn't fickle.""" # This is the class that should generally be used with Zope 3. # Alternate subclasses can be used, but LockStorage can't be used # directly. Subclasses are responsible for providing persistence.
zope.app.locking
/zope.app.locking-3.5.0.tar.gz/zope.app.locking-3.5.0/src/zope/app/locking/storage.py
storage.py
========================= Persistent Python Modules ========================= Persistent Python modules allow us to develop and store Python modules in the ZODB in contrast to storing them on the filesystem. You might want to look at the `zodbcode` package for the details of the implementation. In Zope 3 we implemented persistent modules as utilities. These utilities are known as module managers that manage the source code, compiled module and name of the module. We then provide a special module registry that looks up the utilities to find modules. The Module Manager ------------------ One can simply create a new module manager by instantiating it: >>> from zope.app.module.manager import ModuleManager >>> manager = ModuleManager() If I create the manager without an argument, there is no source code: >>> manager.source '' When we add some code >>> manager.source = """\n ... foo = 1 ... def bar(): return foo ... class Blah(object): ... def __init__(self, id): self.id = id ... def __repr__(self): return 'Blah(id=%s)' % self.id ... """ we can get the compiled module and use the created objects: >>> module = manager.getModule() >>> module.foo 1 >>> module.bar() 1 >>> module.Blah('blah') Blah(id=blah) We can also ask for the name of the module: >>> manager.name >>> module.__name__ But why is it `None`? Because we have no registered it yet. Once we register and activate the registration a name will be set: >>> from zope.app.testing import setup >>> root = setup.buildSampleFolderTree() >>> root_sm = setup.createSiteManager(root) >>> from zope.app.module import interfaces >>> manager = setup.addUtility(root_sm, 'mymodule', ... interfaces.IModuleManager, manager) >>> manager.name 'mymodule' >>> manager.getModule().__name__ 'mymodule' Next, let's ensure that the module's persistence works correctly. To do that let's create a database and add the root folder to it: >>> from ZODB.tests.util import DB >>> db = DB() >>> conn = db.open() >>> conn.root()['Application'] = root >>> import transaction >>> transaction.commit() Let's now reopen the database to test that the module can be seen from a different connection. >>> conn2 = db.open() >>> root2 = conn2.root()['Application'] >>> module2 = root2.getSiteManager().queryUtility( ... interfaces.IModuleManager, 'mymodule').getModule() >>> module2.foo 1 >>> module2.bar() 1 >>> module2.Blah('blah') Blah(id=blah) Module Lookup API ----------------- The way the persistent module framework hooks into Python is via module registires that behave pretty much like `sys.modules`. Zope 3 provides its own module registry that uses the registered utilities to look up modules: >>> from zope.app.module import ZopeModuleRegistry >>> ZopeModuleRegistry.findModule('mymodule') But why did we not get the module back? Because we have not set the site yet: >>> from zope.app.component import hooks >>> hooks.setSite(root) Now it will find the module and we can retrieve a list of all persistent module names: >>> ZopeModuleRegistry.findModule('mymodule') is module True >>> ZopeModuleRegistry.modules() [u'mymodule'] Additionally, the package provides two API functions that look up a module in the registry and then in `sys.modules`: >>> import zope.app.module >>> zope.app.module.findModule('mymodule') is module True >>> zope.app.module.findModule('zope.app.module') is zope.app.module True The second function can be used to lookup objects inside any module: >>> zope.app.module.resolve('mymodule.foo') 1 >>> zope.app.module.resolve('zope.app.module.foo.resolve') In order to use this framework in real Python code import statements, we need to install the importer hook, which is commonly done with an event subscriber: >>> import __builtin__ >>> event = object() >>> zope.app.module.installPersistentModuleImporter(event) >>> __builtin__.__import__ # doctest: +ELLIPSIS <bound method ZopePersistentModuleImporter.__import__ of ...> Now we can simply import the persistent module: >>> import mymodule >>> mymodule.Blah('my id') Blah(id=my id) Finally, we unregister the hook again: >>> zope.app.module.uninstallPersistentModuleImporter(event) >>> __builtin__.__import__ <built-in function __import__>
zope.app.module
/zope.app.module-3.5.0.tar.gz/zope.app.module-3.5.0/src/zope/app/module/README.txt
README.txt
__docformat__ = "reStructuredText" import persistent import zodbcode.module import zope.interface import zope.component from zope.filerepresentation.interfaces import IFileFactory from zope.container.contained import Contained from zope.app.module.interfaces import IModuleManager from zope.app.module import ZopeModuleRegistry class ModuleManager(persistent.Persistent, Contained): zope.interface.implements(IModuleManager) def __init__(self, source=''): # The name is set, once the registration is activated. self.name = None self._source = None self.source = source def execute(self): """See zope.app.module.interfaces.IModuleManager""" try: mod = self._module except AttributeError: mod = self._module = zodbcode.module.PersistentModule(self.name) zodbcode.module.compileModule(mod, ZopeModuleRegistry, self.source) self._module.__name__ = self.name self._recompile = False def getModule(self): """See zope.app.module.interfaces.IModuleManager""" if self._recompile: self.execute() return self._module def _getSource(self): return self._source def _setSource(self, source): if self._source != source: self._source = source self._recompile = True # See zope.app.module.interfaces.IModuleManager source = property(_getSource, _setSource) def _setName(self, name): self.__dict__['name'] = name self._recompile = True name = property(lambda self: self.__dict__['name'], _setName) class ModuleFactory(object): """Special factory for creating module managers in site managment folders.""" zope.interface.implements(IFileFactory) def __init__(self, context): self.context = context def __call__(self, name, content_type, data): assert name.endswith(".py") name = name[:-3] m = ModuleManager(name, data) m.__parent__ = self.context m.execute() return m @zope.component.adapter(IModuleManager, zope.component.interfaces.IRegistered) def setNameOnActivation(manager, event): """Set the module name upon registration activation.""" name = event.object.name if not isinstance(event.object.name, str): # Convert the name to an ascii string to avoid problems with # unicode module names name = name.encode('ascii', 'ignore') manager.name = name @zope.component.adapter(IModuleManager, zope.component.interfaces.IUnregistered) def unsetNameOnDeactivation(manager, event): """Unset the permission id up registration deactivation.""" manager.name = None
zope.app.module
/zope.app.module-3.5.0.tar.gz/zope.app.module-3.5.0/src/zope/app/module/manager.py
manager.py
__docformat__ = 'restructuredtext' import sys import zodbcode.interfaces import zodbcode.module from zope.interface import implements import zope.component from zope.app.module.interfaces import IModuleManager class ZopeModuleRegistry(object): """Zope-specific registry of persistent modules. This registry is used to lookup local module managers and then get the module from them. """ implements(zodbcode.interfaces.IPersistentModuleImportRegistry) def findModule(self, name): """See zodbcode.interfaces.IPersistentModuleImportRegistry""" manager = zope.component.queryUtility(IModuleManager, name=name) return manager and manager.getModule() or manager def modules(self): """See zodbcode.interfaces.IPersistentModuleImportRegistry""" return [name for name, modulemgr in zope.component.getUtilitiesFor(IModuleManager)] # Make Zope Module Registry a singelton ZopeModuleRegistry = ZopeModuleRegistry() def findModule(name, context=None): """Find the module matching the provided name.""" module = ZopeModuleRegistry.findModule(name) return module or sys.modules.get(name) def resolve(name, context=None): """Resolve a dotted name to a Python object.""" pos = name.rfind('.') mod = findModule(name[:pos], context) return getattr(mod, name[pos+1:], None) class ZopePersistentModuleImporter(zodbcode.module.PersistentModuleImporter): def __init__(self, registry): self._registry = registry def __import__(self, name, globals={}, locals={}, fromlist=[]): mod = self._import(self._registry, name, self._get_parent(globals), fromlist) if mod is not None: return mod return self._saved_import(name, globals, locals, fromlist) # Installer function that can be called from ZCML. # This installs an import hook necessary to support persistent modules. importer = ZopePersistentModuleImporter(ZopeModuleRegistry) def installPersistentModuleImporter(event): importer.install() def uninstallPersistentModuleImporter(event): importer.uninstall()
zope.app.module
/zope.app.module-3.5.0.tar.gz/zope.app.module-3.5.0/src/zope/app/module/__init__.py
__init__.py
__docformat__ = 'restructuredtext' import zope.i18nmessageid from zope.app.file.interfaces import IFile from zope.app.publication.interfaces import IFileContent from zope.configuration.fields import GlobalInterface from zope.container.interfaces import IContainer from zope.schema import Choice from zope.schema import SourceText from zope.schema import TextLine _ = zope.i18nmessageid.MessageFactory("zope") class IOnlineHelpTopic(IContainer): """A Topic is a single help page that you can view. Topics are able to contain other Topics and so on. You can also associate a Topic with a particular view. The Topic's content can be in the following four formats: - Plain Text, - HTML, - Structured Text (STX) and - Restructured Text (ReST). The Content is stored in a file and not the Topic itself. The file is only read when required. Note that all the Sub-Topic management is done via the utility service. The topic itself is stored in the IContainer implementation after add the right parent topic of a child. This mechanism ensures that we don't have to take care on the registration order. The topic resources are stored in the :class:`zope.container.interfaces.IContainer` implementation of the topic, too. """ id = TextLine( title=_("Id"), description=_("The Id of this Help Topic"), default="", required=True) parentPath = TextLine( title=_("Parent Path"), description=_("The Path to the Parent of this Help Topic"), default="", required=False) title = TextLine( title=_("Help Topic Title"), description=_("The Title of a Help Topic"), default=_("Help Topic"), required=True) path = TextLine( title=_("Path to the Topic"), description=_("The Path to the Definition of a Help Topic"), default="./README.TXT", required=True) interface = GlobalInterface( title=_("Object Interface"), description=_("Interface for which this Help Topic is registered."), default=None, required=False) view = TextLine( title=_("View Name"), description=_("The View Name for which this Help Topic" " is registered"), default=_(""), required=True) def addResources(resources): """Add resources to this Help Topic. The resources must be located in the same directory as the Help Topic itself. """ def getTopicPath(): """Return the presumed path to the topic, even the topic is not traversable from the onlinehelp.""" def getSubTopics(): """Returns IOnlineHelpTopic provided childs.""" class ISourceTextOnlineHelpTopic(IOnlineHelpTopic): """REstructed text based online help topic.""" source = SourceText( title=_("Source Text"), description=_("Renderable source text of the topic."), default="", required=True, readonly=True) type = Choice( title=_("Source Type"), description=_("Type of the source text, e.g. structured text"), default="zope.source.rest", required=True, vocabulary="SourceTypes") class IRESTOnlineHelpTopic(ISourceTextOnlineHelpTopic): """REstructed text based online help topic.""" class ISTXOnlineHelpTopic(ISourceTextOnlineHelpTopic): """Structed text based online help topic.""" class IZPTOnlineHelpTopic(IOnlineHelpTopic): """Page template based online help topic.""" class IOnlineHelp(ISourceTextOnlineHelpTopic): """The root of an onlinehelp hierarchy. Manages the registration of new topics. """ def registerHelpTopic(parent_path, id, title, doc_path, interface=None, view=None, resources=None): """This method registers a topic at the correct place. :param parent_path: Location of this topic's parent in the OnlineHelp tree. Need not to exist at time of creation. :param id: Specifies the id of the topic :param title: Specifies title of the topic. This title will be used in the tree as Identification. :param doc_path: -- Specifies where the file that contains the topic content is located. :keyword interface: Name of the interface for which the help topic is being registered. This can be optional, since not all topics must be bound to a particular interface. :keyword view: This attribute specifies the name of the view for which this topic is registered. Note that this attribute is also optional. :keyword resources: Specifies a list of resources for the topic, for example images that are included by the rendered topic content. Optional. """ class IOnlineHelpResource(IFile, IFileContent): """A resource, which can be used in a help topic """ path = TextLine( title=_("Path to the Resource"), description=_("The Path to the Resource, assumed to be " "in the same directory as the Help Topic"), default="", required=True)
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/interfaces.py
interfaces.py
"""Schemas for the ``help`` ZCML namespace """ __docformat__ = 'restructuredtext' 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.configuration.fields import Tokens from zope.interface import Interface from zope.schema import NativeStringLine from zope.schema import TextLine class IOnlineHelpTopicDirective(Interface): """Register an online topic. Optionally you can register a topic for a component and view. """ id = NativeStringLine( title="Topic Id", description="Id of the topic as it will appear in the URL.", required=True) title = MessageID( title="Title", description="Provides a title for the online Help Topic.", required=True) parent = NativeStringLine( title="Parent Topic", description="Id of the parent topic.", default="", required=False) for_ = GlobalInterface( title="Object Interface", description="Interface for which this Help Topic is registered.", default=None, required=False) view = NativeStringLine( title="View Name", description="The view name for which this Help Topic is registered.", default="", required=False) doc_path = Path( title="Path to File", description="Path to the file that contains the Help Topic content.", required=True) class_ = GlobalObject( title="Factory", description=""" The factory is the topic class used for initializeing the topic""", required=False, ) resources = Tokens( title="A list of resources.", description=""" A list of resources which shall be used for the Help Topic. The resources must be located in the same directory as the Help Topic definition. """, value_type=TextLine(), required=False )
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/metadirectives.py
metadirectives.py
__docformat__ = 'restructuredtext' import os from zope.component import getGlobalSiteManager from zope.component import getUtilitiesFor from zope.configuration.exceptions import ConfigurationError from zope.interface import implementer from zope.traversing.api import traverse from zope.traversing.interfaces import IContainmentRoot from zope.app.onlinehelp.interfaces import IOnlineHelp from zope.app.onlinehelp.interfaces import IOnlineHelpTopic from zope.app.onlinehelp.onlinehelptopic import OnlineHelpTopic @implementer(IOnlineHelp, IContainmentRoot) class OnlineHelp(OnlineHelpTopic): """ Implementation of :class:`~.IOnlineHelp`. >>> import os >>> from zope import component >>> from zope.component.interfaces import IFactory >>> from zope.component.factory import Factory >>> from zope.app.onlinehelp.tests.test_onlinehelp import testdir >>> from zope.app.onlinehelp.tests.test_onlinehelp import I1 >>> path = os.path.join(testdir(), 'help.txt') Create an `OnlineHelp` instance >>> onlinehelp = OnlineHelp('Help', path) First do the interface verifying tests. >>> from zope.interface.verify import verifyObject >>> from zope.traversing.interfaces import IContainmentRoot >>> verifyObject(IOnlineHelp, onlinehelp) True >>> verifyObject(IContainmentRoot, onlinehelp) True Register a new subtopic for interface 'I1' and view 'view.html' >>> from zope.app.onlinehelp.onlinehelptopic import OnlineHelpTopic >>> from zope.app.onlinehelp.onlinehelptopic import RESTOnlineHelpTopic >>> from zope.app.onlinehelp.onlinehelptopic import STXOnlineHelpTopic >>> from zope.app.onlinehelp.onlinehelptopic import ZPTOnlineHelpTopic >>> default = Factory(OnlineHelpTopic) >>> rest = Factory(RESTOnlineHelpTopic) >>> stx = Factory(STXOnlineHelpTopic) >>> zpt = Factory(ZPTOnlineHelpTopic) >>> component.provideUtility(default, IFactory, 'onlinehelp.topic.default') >>> component.provideUtility(rest, IFactory, 'onlinehelp.topic.rest') >>> component.provideUtility(stx, IFactory, 'onlinehelp.topic.stx') >>> component.provideUtility(zpt, IFactory, 'onlinehelp.topic.zpt') >>> path = os.path.join(testdir(), 'help2.txt') >>> onlinehelp.registerHelpTopic('', 'help2', 'Help 2', ... path, I1, 'view.html') Test if the subtopic is set correctly >>> onlinehelp['help2'].title 'Help 2' Additionally it should appear as a utility >>> topic = component.getUtility(IOnlineHelpTopic,'help2') >>> topic.title 'Help 2' add another topic without parent >>> onlinehelp.registerHelpTopic('missing', 'help3', 'Help 3', ... path, I1, 'view.html') The new topic should not be a child of the onlinehelp instance >>> 'help3' in onlinehelp.keys() False But it is available as a utility >>> topic = component.getUtility(IOnlineHelpTopic,'missing/help3') >>> topic.title 'Help 3' now register the missing parent >>> onlinehelp.registerHelpTopic('', 'missing', 'Missing', ... path, I1, 'view.html') This is a child on the onlinehelp >>> 'missing' in onlinehelp.keys() True >>> missing = onlinehelp['missing'] This topic should now have 'help3' as a child >>> 'help3' in missing.keys() True """ def __init__(self, title, path): super().__init__('', title, path, None) def registerHelpTopic(self, parent_path, id, title, doc_path, interface=None, view=None, class_=None, resources=None): "See zope.app.onlineHelp.interfaces.IOnlineHelp" if not os.path.exists(doc_path): if (doc_path.endswith('.txt') and os.path.exists(doc_path[:-4] + '.rst')): doc_path = doc_path[:-4] + '.rst' if not os.path.exists(doc_path): raise ConfigurationError( "Help Topic definition %s does not exist" % doc_path ) if class_ is None: class_ = OnlineHelpTopic # Create topic base on the custom class or OnlinHelpTopic topic = class_(id, title, doc_path, parent_path, interface, view) # add resources to topic if resources is not None: topic.addResources(resources) # add topic to onlinehelp hierarchy parent = None try: parent = traverse(self, parent_path) parent[id] = topic except KeyError: pass for t in getUtilitiesFor(IOnlineHelpTopic): if parent is None: if t[1].getTopicPath() == parent_path: t[1][id] = topic if topic.getTopicPath() == t[1].parentPath: topic[t[1].id] = t[1] getGlobalSiteManager().registerUtility( topic, IOnlineHelpTopic, topic.getTopicPath())
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/onlinehelp.py
onlinehelp.py
__docformat__ = 'restructuredtext' import os from persistent import Persistent from zope.app.file.image import getImageInfo from zope.configuration.exceptions import ConfigurationError from zope.container.sample import SampleContainer from zope.contenttype import guess_content_type from zope.interface import implementer from zope.app.onlinehelp.interfaces import IOnlineHelpResource from zope.app.onlinehelp.interfaces import IOnlineHelpTopic from zope.app.onlinehelp.interfaces import IRESTOnlineHelpTopic from zope.app.onlinehelp.interfaces import ISourceTextOnlineHelpTopic from zope.app.onlinehelp.interfaces import ISTXOnlineHelpTopic from zope.app.onlinehelp.interfaces import IZPTOnlineHelpTopic DEFAULT_ENCODING = "utf-8" try: text_type = unicode except NameError: text_type = str @implementer(IOnlineHelpResource) class OnlineHelpResource(Persistent): r""" Represents a resource that is used inside the rendered Help Topic - for example a screenshot. Implements :class:`~zope.app.onlinehelp.interfaces.IOnlineHelpResource`. >>> from zope.app.onlinehelp.tests.test_onlinehelp import testdir >>> path = os.path.join(testdir(), 'test1.png') >>> resource = OnlineHelpResource(path) >>> resource.contentType 'image/png' >>> resource._fileMode 'rb' >>> path = os.path.join(testdir(), 'help2.txt') >>> resource = OnlineHelpResource(path) >>> resource.contentType 'text/plain' >>> resource._fileMode 'r' >>> resource.data.splitlines()[0] u'This is another help!' >>> u'\u0444\u0430\u0439\u043b' in resource.data True """ def __init__(self, path='', contentType=''): self.path = path with open(os.path.normpath(self.path), 'rb') as f: _data = f.read() self._size = len(_data) self._fileMode = 'rb' encoding = None if contentType == '': content_type, encoding = guess_content_type(self.path, _data, '') if content_type.startswith('image/'): self.contentType, _width, _height = getImageInfo(_data) else: self.contentType = content_type self._encoding = encoding or DEFAULT_ENCODING if self.contentType.startswith('text/'): self._fileMode = 'r' @property def data(self): with open(os.path.normpath(self.path), self._fileMode) as f: data = f.read() if (self.contentType.startswith('text/') and not isinstance(data, text_type)): data = data.decode(self._encoding) return data def getSize(self): '''See IFile''' return self._size class BaseOnlineHelpTopic(SampleContainer): """Base class for custom Help Topic implementations. >>> from zope.app.onlinehelp.tests.test_onlinehelp import testdir >>> path = os.path.join(testdir(), 'help.txt') Create a Help Topic from a file >>> topic = BaseOnlineHelpTopic('help','Help',path,'') Test the title >>> topic.title 'Help' Test the topic path >>> topic.getTopicPath() 'help' >>> topic.parentPath = 'parent' >>> topic.getTopicPath() 'parent/help' Resources can be added to an online help topic. >>> topic.addResources(['test1.png', 'test2.png']) >>> topic['test1.png'].contentType 'image/png' >>> topic['test2.png'].contentType 'image/png' """ id = "" title = "" path = "" parentPath = "" interface = None view = None def __init__(self, id, title, path, parentPath, interface=None, view=None): """Initialize object.""" self.id = id self.parentPath = parentPath self.title = title self.path = path self.interface = interface self.view = view if not os.path.exists(self.path): raise ConfigurationError( "Help Topic definition %s does not exist" % self.path ) super().__init__() def _newContainerData(self): # Ensure consistent iteration order for tests. from collections import OrderedDict return OrderedDict() def addResources(self, resources): """ see IOnlineHelpTopic """ dirname = os.path.dirname(self.path) for resource in resources: resource_path = dirname + '/' + resource if os.path.exists(resource_path): self[resource] = OnlineHelpResource(resource_path) def getTopicPath(self): """See IOnlineHelpTopic""" if self.parentPath: return self.parentPath + '/' + self.id return self.id def getSubTopics(self): res = [] for item in self.values(): if IOnlineHelpTopic.providedBy(item): res.append(item) return res class SourceTextOnlineHelpTopic(BaseOnlineHelpTopic): """Source text methods mixin class.""" type = None @property def source(self): with open(os.path.normpath(self.path), 'rb') as f: source = f.read() return source.decode(DEFAULT_ENCODING) @implementer(ISourceTextOnlineHelpTopic) class OnlineHelpTopic(SourceTextOnlineHelpTopic): """ Represents a Help Topic. This generic implementation uses the filename extension for guess the type. This topic implementation supports plain text topics, restructured and structured text topics. HTML topics get rendered as structured text. If a file doesn't have the right file extension, use a explicit topic class for representing the right format. Implements :class:`~zope.app.onlinehelp.interfaces.ISourceTextOnlineHelpTopic`. >>> from zope.app.onlinehelp.tests.test_onlinehelp import testdir >>> path = os.path.join(testdir(), 'help.txt') Create a Help Topic from a file >>> topic = OnlineHelpTopic('help','Help',path,'') Test the title >>> topic.title 'Help' Test the topic path >>> topic.getTopicPath() 'help' >>> topic.parentPath = 'parent' >>> topic.getTopicPath() 'parent/help' The type should be set to plaintext, since the file extension is 'txt' >>> topic.type 'zope.source.plaintext' Test the help content. >>> topic.source u'This is a help!' >>> path = os.path.join(testdir(), 'help.stx') >>> topic = OnlineHelpTopic('help','Help',path,'') The type should now be structured text >>> topic.type 'zope.source.stx' HTML files are treated as structured text files >>> path = os.path.join(testdir(), 'help.html') >>> topic = OnlineHelpTopic('help','Help',path,'') The type should still be structured text >>> topic.type 'zope.source.stx' >>> path = os.path.join(testdir(), 'help.rst') >>> topic = OnlineHelpTopic('help','Help',path,'') The type should now be restructured text >>> topic.type 'zope.source.rest' Resources can be added to an online help topic. >>> topic.addResources(['test1.png', 'test2.png']) >>> topic['test1.png'].contentType 'image/png' >>> topic['test2.png'].contentType 'image/png' """ def __init__(self, id, title, path, parentPath, interface=None, view=None): """Initialize object.""" super().__init__(id, title, path, parentPath, interface, view) filename = os.path.basename(path.lower()) file_ext = 'txt' if len(filename.split('.')) > 1: file_ext = filename.split('.')[-1] self.type = 'zope.source.plaintext' if file_ext in ('rst', 'rest'): self.type = 'zope.source.rest' elif file_ext in ('stx', 'html', 'htm'): self.type = 'zope.source.stx' @implementer(IRESTOnlineHelpTopic) class RESTOnlineHelpTopic(SourceTextOnlineHelpTopic): r""" Represents a restructed text based Help Topic which has other filename extension then '.rst' or 'rest'. Implements :class:`~zope.app.onlinehelp.interfaces.IRESTOnlineHelpTopic`. >>> from zope.app.onlinehelp.tests.test_onlinehelp import testdir >>> path = os.path.join(testdir(), 'help.rst') Create a Help Topic from a file >>> topic = RESTOnlineHelpTopic('help','Help',path,'') Test the title >>> topic.title 'Help' Test the topic path >>> topic.getTopicPath() 'help' >>> topic.parentPath = 'parent' >>> topic.getTopicPath() 'parent/help' The type should be set to rest, since the file extension is 'rest' >>> topic.type 'zope.source.rest' Test the help content. >>> topic.source.splitlines()[0] u'This is a ReST help!' >>> u'\u0444\u0430\u0439\u043b' in topic.source True Resources can be added to an online help topic. >>> topic.addResources(['test1.png', 'test2.png']) >>> topic['test1.png'].contentType 'image/png' >>> topic['test2.png'].contentType 'image/png' """ type = 'zope.source.rest' @implementer(ISTXOnlineHelpTopic) class STXOnlineHelpTopic(SourceTextOnlineHelpTopic): r""" Represents a restructed text based Help Topic which has other filename extension then '.stx'. Implements :class:`~zope.app.onlinehelp.interfaces.ISTXOnlineHelpTopic`. >>> from zope.app.onlinehelp.tests.test_onlinehelp import testdir >>> path = os.path.join(testdir(), 'help.stx') Create a Help Topic from a file >>> topic = STXOnlineHelpTopic('help','Help',path,'') Test the title >>> topic.title 'Help' Test the topic path >>> topic.getTopicPath() 'help' >>> topic.parentPath = 'parent' >>> topic.getTopicPath() 'parent/help' The type should be set to stx, since the file extension is 'stx' >>> topic.type 'zope.source.stx' Test the help content. >>> topic.source.splitlines()[0] u'This is a STX help!' >>> u'\u0444\u0430\u0439\u043b' in topic.source True Resources can be added to an online help topic. >>> topic.addResources(['test1.png', 'test2.png']) >>> topic['test1.png'].contentType 'image/png' >>> topic['test2.png'].contentType 'image/png' """ type = 'zope.source.stx' @implementer(IZPTOnlineHelpTopic) class ZPTOnlineHelpTopic(BaseOnlineHelpTopic): r"""Represents a page template based Help Topic which has other filename extension than `.pt`. Implements :class:`~zope.app.onlinehelp.interfaces.IZPTOnlineHelpTopic`. >>> from zope.publisher.browser import TestRequest, BrowserView >>> from zope.app.pagetemplate.viewpagetemplatefile import \ ... ViewPageTemplateFile >>> from zope.app.onlinehelp.tests.test_onlinehelp import testdir >>> path = os.path.join(testdir(), 'help.pt') Create a page template based Help Topic from a file >>> topic = ZPTOnlineHelpTopic('help','Help',path,'') Test the title >>> topic.title 'Help' Test the topic path >>> topic.getTopicPath() 'help' >>> topic.parentPath = 'parent' >>> topic.getTopicPath() 'parent/help' Test the help content. >>> class TestView(BrowserView): ... def index(self): ... path = self.context.path ... view = ViewPageTemplateFile(path) ... return view(self) >>> request = TestRequest() >>> view = TestView(topic, request) >>> res = view.index() >>> u'<span>This is a ZPT help!</span>' in res True >>> u'\u0444\u0430\u0439\u043b' in res True Resources can be added to an online help topic. >>> topic.addResources(['test1.png', 'test2.png']) >>> topic['test1.png'].contentType 'image/png' >>> topic['test2.png'].contentType 'image/png' """
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/onlinehelptopic.py
onlinehelptopic.py
__docformat__ = 'restructuredtext' import os from zope.component import getUtilitiesFor from zope.interface import providedBy from zope.proxy import ProxyBase from zope.proxy import non_overridable from zope.testing import cleanup from zope.app.onlinehelp.interfaces import IOnlineHelpTopic from zope.app.onlinehelp.onlinehelp import OnlineHelp # Global Online Help Instance path = os.path.join(os.path.dirname(__file__), 'help', 'welcome.stx') globalhelp = OnlineHelp('Online Help', path) class _TraversedOnlineHelpProxy(ProxyBase): """ A proxy around the globalhelp object that is returned when we traverse through the helpNamespace. It adds the ``context`` attribute to the context that was traversed through. """ __slots__ = ('context',) def __init__(self, context): self.context = context ProxyBase.__init__(self, globalhelp) @non_overridable def __reduce__(self, proto=None): raise TypeError("Not picklable") __reduce_ex__ = __reduce__ class helpNamespace: """ help namespace handler """ def __init__(self, context, request=None): self.context = context def traverse(self, name, ignored): """ Used to traverse to an online help topic. Returns a proxy for the global :class:`~.OnlineHelp` instance with the traversal context. """ return _TraversedOnlineHelpProxy(self.context) def getTopicFor(obj, view=None): """Determine topic for an object and optionally a view. Iterate through all directly provided Interfaces and see if for the interface (and view) exists a Help Topic. Returns the first match. Prepare the tests: >>> import os >>> from zope.app.onlinehelp.tests.test_onlinehelp import testdir >>> from zope.app.onlinehelp.tests.test_onlinehelp import I1 >>> from zope.app.onlinehelp.tests.test_onlinehelp import Dummy1, Dummy2 >>> from zope.app.onlinehelp import tests as ztapi >>> from zope.component.interfaces import IFactory >>> from zope.component.factory import Factory >>> from zope.app.onlinehelp.onlinehelptopic import OnlineHelpTopic >>> from zope.app.onlinehelp.onlinehelptopic import RESTOnlineHelpTopic >>> from zope.app.onlinehelp.onlinehelptopic import STXOnlineHelpTopic >>> from zope.app.onlinehelp.onlinehelptopic import ZPTOnlineHelpTopic >>> default = Factory(OnlineHelpTopic) >>> rest = Factory(RESTOnlineHelpTopic) >>> stx = Factory(STXOnlineHelpTopic) >>> zpt = Factory(ZPTOnlineHelpTopic) >>> ztapi.provideUtility(IFactory, default, 'onlinehelp.topic.default') >>> ztapi.provideUtility(IFactory, rest, 'onlinehelp.topic.rest') >>> ztapi.provideUtility(IFactory, stx, 'onlinehelp.topic.stx') >>> ztapi.provideUtility(IFactory, zpt, 'onlinehelp.topic.zpt') >>> path = os.path.join(testdir(), 'help.txt') Register a help topic for the interface 'I1' and the view 'view.html' >>> onlinehelp = OnlineHelp('Help', path) >>> path = os.path.join(testdir(), 'help2.txt') >>> onlinehelp.registerHelpTopic('', 'help2', 'Help 2', ... path, I1, 'view.html') The query should return it ('Dummy1' implements 'I1): >>> getTopicFor(Dummy1(),'view.html').title 'Help 2' A query without view should not return it >>> getTopicFor(Dummy1()) is None True Do the registration again, but without a view: >>> onlinehelp = OnlineHelp('Help', path) >>> onlinehelp.registerHelpTopic('', 'help2', 'Help 2', ... path, I1, None) >>> getTopicFor(Dummy1()).title 'Help 2' Query with view should not match >>> getTopicFor(Dummy1(), 'view.html') is None True Query with an object, that does not provide 'I1' should also return None >>> getTopicFor(Dummy2()) is None True If there is a second interface also provided with the same view name and registered for that interface, still only the first topic will be found. >>> from zope.interface import Interface, implementer >>> class I3(Interface): ... pass >>> @implementer(I3) ... class Dummy3(object): ... pass >>> path = os.path.join(testdir(), 'help2.txt') >>> onlinehelp.registerHelpTopic('a', 'help3', 'Help 3', ... path, I3, None) >>> getTopicFor(Dummy3()).title 'Help 3' >>> getTopicFor(Dummy1()).title 'Help 2' >>> @implementer(I1, I3) ... class Dummy4(object): ... pass >>> getTopicFor(Dummy4()).title 'Help 2' >>> @implementer(I3, I1) ... class Dummy5(object): ... pass >>> getTopicFor(Dummy5()).title 'Help 3' """ for interface in providedBy(obj): for _name, topic in getUtilitiesFor(IOnlineHelpTopic): if topic.interface == interface and topic.view == view: return topic def _clear(): globalhelp.__init__(globalhelp.title, globalhelp.path) cleanup.addCleanUp(_clear)
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/__init__.py
__init__.py
What's the Online Help System? The Online Help provides a way to write, organize and display help documents for applications. The Online Help is basically a hierarchy of Help Topics. Topics are a pieces of the help that contain useful information. The contents of a Help Topic can be defined in different formats, which will all displayed as HTML. The Online Help supports - plain text documents - structured text documents - restructured text documents - HTML documents - Page template based content Topics are also containers and can contain further Topics or resources associated with the Help Topic. This way we can have nested help pages, which will help with content organization. It is possible to associate a topic with an interface or even a particular view of an interface. New topic classes can be easy defined and used. A new topic implementation has only to provide the constructor attributes and the interface IOnlineHelpTopic. A new topic class can be used as the dotted name of the class attribute in the "help:register" directive. The Online Help System is implemented as global service. Usage: To register help topic for your code, you need to add 'register' directive in the configuration file (see example below). You can specify the following attributes: - 'parent' - Location of this topic's parent in the OnlineHelp tree. Optional. - 'id' - The id of the help topic. Required. - 'title' - The title of the topic. It will be used in the tree as Identification. Required. - 'doc_path' - Path to the file that contains the topic. Required. - 'doc_type' - Defines the type of document this topic will be. Optional. - 'for' - The interface this topic apllies to. Optional. - 'view' - The name of the view for wich this topic is registered. Optional. - 'class' - The dotted path to the class which will be used for initialize a topic. Optional. - 'resources' - A list of resources that can be referenced by the Help Topic (e.g. images). Optional. Examples:: <configure xmlns="http://namespaces.zope.org/zope" xmlns:help="http://namespaces.zope.org/help" > .... <!-- Register Help Topics --> <help:register id="zmi" title="Zope ZMI" doc_path="./help/ui.stx" resources="mgmt-main-1.png" /> <help:register id="welcome" parent="onlinehelp" title="Welcome" doc_path="./help/welcome.stx" /> <help:register id="onlinehelp" title="Online Help System" doc_path="./help/README.stx" /> <help:register id="styleguide" title="Zope Style Guide" doc_path="styleguides.txt" class="zope.app.onlinehelp.onlinehelptopic.RESTOnlineHelpTopic" /> <help:register id="css" parent="styleguide" title="CSS Style Guide" doc_path="index.html" class="zope.app.onlinehelp.onlinehelptopic.ZPTOnlineHelpTopic" /> </configure>
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/help/README.stx
README.stx
__docformat__ = 'restructuredtext' from zope.component import getUtility from zope.i18n import translate from zope.publisher.browser import BrowserView from zope.traversing.api import getPath from zope.traversing.api import joinPath from zope.app.onlinehelp.interfaces import IOnlineHelp class OnlineHelpTopicTreeView(BrowserView): """Online help topic tree view.""" def __init__(self, context, request): super().__init__(context, request) self.onlinehelp = getUtility(IOnlineHelp, "OnlineHelp") def getTopicTree(self): """Return the tree of help topics. We build a flat list of tpoics info dict. Iterate this dict oan build from the level info a navigation tree in the page tmeplate. Each time you get a level 0 means this is a subitem of the Onlinehelp itself:: >>> info = [('id',{infoDict}),(),()] # noqa: F821 undefined name <ul class="tree" id="tree"> <li><a href="#">items</a> <ul> <li><a href="#">item</a></li> </ul> </li> <li><a href="#">items</a> <ul> <li><a href="#">items</a> <ul> <li><a href="#">item</a></li> <li><a href="#">item</a></li> <li><a href="#">item</a></li> </ul> </li> <li><a href="#">items</a> <ul> <li><a href="#">item</a></li> <li id="activeTreeNode"><a href="#">active item</a></li> <li><a href="#">item</a></li> </ul> </li> </ul> </li> <ul> """ return self.renderTree(self.onlinehelp) def renderTree(self, root): """Reder a unordered list 'ul' tree with a class name 'tree'.""" res = [] intend = " " res.append('<ul class="tree" id="tree">') for topic in root.getSubTopics(): item = self.renderLink(topic) # expand if context is in tree if self.isExpanded(topic): res.append(' <li class="expand">%s' % item) else: res.append(' <li>%s' % item) if len(topic.getSubTopics()) > 0: res.append(self.renderItemList(topic, intend)) res.append(' </li>') res.append('<ul>') return '\n'.join(res) def renderItemList(self, topic, intend): """Render a 'ul' elements as childs of the 'ul' tree.""" res = [] intend = intend + " " res.append('%s<ul>' % intend) for item in topic.getSubTopics(): # expand if context is in tree if self.isExpanded(topic): res.append(' %s<li class="expand">' % intend) else: res.append(' %s<li>' % intend) res.append(self.renderLink(item)) if len(item.getSubTopics()) > 0: res.append(' {}{}'.format( self.renderItemList(item, intend), intend)) res.append(' %s</li>' % intend) res.append('%s</ul>' % intend) return '\n'.join(res) def renderLink(self, topic): """Render a href element.""" title = translate(topic.title, context=self.request, default=topic.title) if topic.parentPath: url = joinPath(topic.parentPath, topic.id) else: url = topic.id return '<a href="/++help++/{}">{}</a>\n'.format(url, title) def isExpanded(self, topic): if topic.parentPath: path = joinPath(topic.parentPath, topic.id) else: path = topic.id try: if getPath(self.context).startswith('/' + path): return True except: # noqa: E722 do not use bare 'except' # TODO: fix it, functional test doesn't like getPath? ri pass return False
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/browser/tree.py
tree.py
var nodeCollapseClass = "collapse"; var nodeExpandClass = "expand"; var nodeItemClass = "item"; var nodeLinkClass = "link"; var activeNodeId = "activeTreeNode"; //---------------------------------------------------------------------------- // public API //---------------------------------------------------------------------------- function buildTrees() { if (!document.createElement) { return; } uls = document.getElementsByTagName("ul"); for (var i=0; i<uls.length; i++) { var ul = uls[i]; if (ul.nodeName == "UL" && ul.className == "tree") { _renderTreeList(ul); _toggleTreeList(ul, nodeExpandClass, activeNodeId); } } } function expandTree(id) { var ul = document.getElementById(id); if (ul == null) { return false; } _toggleTreeList(ul, nodeExpandClass); } function collapseTree(id) { var ul = document.getElementById(id); if (ul == null) { return false; } _toggleTreeList(ul, nodeCollapseClass); } function expandItem(treeId, itemId) { var ul = document.getElementById(treeId); if (ul == null) { return false; } var togList = _toggleTreeList(ul, nodeExpandClass, itemId); if (togList) { var o = document.getElementById(itemId); if (o.scrollIntoView) { o.scrollIntoView(false); } } } function expandActiveItem(treeId) { expandItem(treeId, activeNodeId); } //---------------------------------------------------------------------------- // private methods //---------------------------------------------------------------------------- function _toggleTreeList(ul, clsName, itemId) { if (!ul.childNodes || ul.childNodes.length==0) { return false; } for (var i=0; i<ul.childNodes.length; i++) { var item = ul.childNodes[i]; if (itemId != null && item.id == itemId) { return true; } if (item.nodeName == "LI") { var subLists = false; for (var si=0; si<item.childNodes.length; si++) { var subitem = item.childNodes[si]; if (subitem.nodeName == "UL") { subLists = true; var togList = _toggleTreeList(subitem, clsName, itemId); if (itemId != null && togList) { item.className = clsName; return true; } } } if (subLists && itemId == null) { item.className = clsName; } } } } function _renderTreeList(ul) { if (!ul.childNodes || ul.childNodes.length == 0) { return; } for (var i=0; i<ul.childNodes.length; i++) { var item = ul.childNodes[i]; if (item.nodeName == "LI") { var subLists = false; for (var si=0; si<item.childNodes.length; si++) { var subitem = item.childNodes[si]; if (subitem.nodeName == "UL") { subLists = true; _renderTreeList(subitem); } } var span = document.createElement("SPAN"); var nbsp = '\u00A0'; // &nbsp; span.className = nodeLinkClass; if (subLists) { if (item.className == null || item.className == "") { item.className = nodeCollapseClass; } if (item.firstChild.nodeName == "#text") { nbsp = nbsp + item.firstChild.nodeValue; item.removeChild(item.firstChild); } span.onclick = function () { if (this.parentNode.className == nodeExpandClass) { this.parentNode.className = nodeCollapseClass }else { this.parentNode.className = nodeExpandClass } return false; } } else { item.className = nodeItemClass; span.onclick = function () { return false; } } child = document.createTextNode(nbsp) span.appendChild(child); item.insertBefore(span, item.firstChild); } } }
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/browser/tree.js
tree.js
"""`OnlineHelp` views """ __docformat__ = 'restructuredtext' from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile from zope.component import createObject from zope.component import getMultiAdapter from zope.publisher.browser import BrowserView from zope.publisher.interfaces.browser import IBrowserView from zope.traversing.api import getName from zope.traversing.api import getParent from zope.app.onlinehelp import getTopicFor class OnlineHelpTopicView(BrowserView): """View for one particular help topic.""" def topicContent(self): """ render the source of the help topic """ source = createObject(self.context.type, self.context.source) view = getMultiAdapter((source, self.request)) html = view.render() return html renderTopic = ViewPageTemplateFile('helptopic.pt') class ZPTOnlineHelpTopicView(BrowserView): """View for a page template based help topic.""" def renderTopic(self): """Render the registred topic.""" path = self.context.path view = ViewPageTemplateFile(path) return view(self) class ContextHelpView(BrowserView): """Contextual help view.""" def __init__(self, context, request): super().__init__(context, request) self.topic = None def getContextualTopicView(self): """Retrieve and render the source of a context help topic """ topic = self.getContextHelpTopic() view = getMultiAdapter((topic, self.request), name='index.html') return view.renderTopic() def getContextHelpTopic(self): """Retrieve a help topic based on the context of the help namespace. If the context is a view, try to find a matching help topic for the view and its context. If no help topic is found, try to get a help topic for the context only. If the context is not a view, try to retrieve a help topic based on the context. If nothing is found, return the onlinehelp root topic """ if self.topic is not None: return self.topic onlinehelp = self.context help_context = onlinehelp.context self.topic = None if IBrowserView.providedBy(help_context): # called from a view self.topic = getTopicFor( getParent(help_context), getName(help_context) ) if self.topic is None: # nothing found for view try context only self.topic = getTopicFor(getParent(help_context)) else: # called without view self.topic = getTopicFor(help_context) if self.topic is None: self.topic = onlinehelp return self.topic contextHelpTopic = property(getContextHelpTopic)
zope.app.onlinehelp
/zope.app.onlinehelp-5.0-py3-none-any.whl/zope/app/onlinehelp/browser/__init__.py
__init__.py
__docformat__ = 'restructuredtext' from zope.i18nmessageid import ZopeMessageFactory as _ from zope.app.container.interfaces import IContainer, IContained from zope.app.container.constraints import ItemTypePrecondition from zope.app.container.constraints import ContainerTypesConstraint from zope.app.security.interfaces import IAuthentication, IPrincipal from zope.interface import Interface from zope.schema import Text, TextLine, Password, Field class IUserSchemafied(IPrincipal): """A User object with schema-defined attributes.""" login = TextLine( title=_("Login"), description=_("The Login/Username of the user. " "This value can change."), required=True) password = Password( title=_(u"Password"), description=_("The password for the user."), required=True) def validate(test_password): """Confirm whether 'password' is the password of the user.""" class IPrincipalSource(Interface): """A read-only source of `IPrincipals`.""" def getPrincipal(id): """Get principal meta-data. Returns an object of type `IPrincipal` for the given principal id. A ``PrincipalLookupError`` is raised if the principal cannot be found. Note that the id has three parts, separated by tabs. The first two part are an authentication utility id and a principal source id. The pricipal source will typically need to remove the two leading parts from the id when doing it's own internal lookup. Note that the authentication utility nearest to the requested resource is called. It is up to authentication utility implementations to collaborate with utilities higher in the object hierarchy. """ def getPrincipals(name): """Get principals with matching names. Get a iterable object with the principals with names that are similar to (e.g. contain) the given name. """ class IPluggableAuthentication(IAuthentication, IContainer): """An `Authentication` utility that can contain multiple pricipal sources. """ def __setitem__(id, principal_source): """Add to object""" __setitem__.precondition = ItemTypePrecondition(IPrincipalSource) def removePrincipalSource(id): """Remove a `PrincipalSource`. If id is not present, raise ``KeyError``. """ IPluggableAuthenticationService = IPluggableAuthentication class ILoginPasswordPrincipalSource(IPrincipalSource): """A principal source which can authenticate a user given a login and a password """ def authenticate(login, password): """Return a principal matching the login/password pair. If there is no principal in this principal source which matches the login/password pair, return ``None``. Note: A login is different than an id. Principals may have logins that differ from their id. For example, a user may have a login which is his email address. He'd like to be able to change his login when his email address changes without effecting his security profile on the site. """ class IContainerPrincipalSource(IContainer): """This is a marker interface for specifying principal sources that are also containers. """ class IContainedPrincipalSource(IPrincipalSource, IContained): """This is a marker interface for principal sources that can be directly added to an authentication utility. It ensures that principal source can **only** be added to pluggable authentication utilities.""" __parent__= Field( constraint = ContainerTypesConstraint(IPluggableAuthentication))
zope.app.pluggableauth
/zope.app.pluggableauth-3.4.0.tar.gz/zope.app.pluggableauth-3.4.0/src/zope/app/pluggableauth/interfaces.py
interfaces.py
================================= New Authentication Service Design ================================= The current implementation will be replaced. The following is a design I came up with together with Jim Fulton. -- itamar Note that this design is implemented (in some form) by the pluggable auth service. This document needs to be updated to reflect the final implementation. Design notes for new AuthenticationService ------------------------------------------ The service contains a list of user sources. They implement interfaces, starting with:: class IUserPassUserSource: """Authenticate using username and password.""" def authenticate(username, password): "Returns boolean saying if such username/password pair exists" class IDigestSupportingUserSource(IUserPassUserSource): """Allow fetching password, which is required by digest auth methods""" def getPassword(username): "Return password for username" etc. Probably there will be others as well, for dealing with certificate authentication and what not. Probably we need to expand above interfaces to deal with principal titles and descriptions, and so on. A login method (cookie auth, HTTP basic auth, digest auth, FTP auth), is registered as a view on one of the above interfaces. :: class ILoginMethodView: def authenticate(): """Return principal for request, or None.""" def unauthorized(): """Tell request that a login is required.""" The authentication service is then implemented something like this:: class AuthenticationService: def authenticate(self, request): for us in self.userSources: loginView = getView(self, us, "login", request) principal = loginView.authenticate() if principal is not None: return principal def unauthorized(self, request): loginView = getView(self, self.userSources[0], request) loginView.unauthorized()
zope.app.pluggableauth
/zope.app.pluggableauth-3.4.0.tar.gz/zope.app.pluggableauth-3.4.0/src/zope/app/pluggableauth/README.txt
README.txt
__docformat__ = 'restructuredtext' import random import sys import time import random import zope.schema from warnings import warn from persistent import Persistent from BTrees.IOBTree import IOBTree from BTrees.OIBTree import OIBTree from zope.interface import implements from zope.component.interfaces import IViewFactory from zope.deprecation import deprecated from zope.traversing.api import getPath from zope.location import locate from zope.app import zapi from zope.app.component import queryNextUtility from zope.app.container.interfaces import IOrderedContainer from zope.app.container.interfaces import IContainerNamesContainer, INameChooser from zope.app.container.interfaces import IContained from zope.app.container.constraints import ItemTypePrecondition from zope.app.container.constraints import ContainerTypesConstraint from zope.app.container.contained import Contained, setitem, uncontained from zope.app.container.ordered import OrderedContainer from zope.app.security.interfaces import ILoginPassword, IAuthentication from zope.app.security.interfaces import PrincipalLookupError from interfaces import IUserSchemafied, IPluggableAuthentication from interfaces import IPrincipalSource, ILoginPasswordPrincipalSource from interfaces import IContainedPrincipalSource, IContainerPrincipalSource def gen_key(): """Return a random int (1, MAXINT), suitable for use as a `BTree` key.""" return random.randint(0, sys.maxint-1) class PluggableAuthentication(OrderedContainer): implements(IPluggableAuthentication, IOrderedContainer) def __init__(self, earmark=None, hide_deprecation_warning=False): if not hide_deprecation_warning: warn("The `pluggableauth` module has been deprecated in favor of " "the new `pas` code, which is much more modular and powerful.", DeprecationWarning, 2) self.earmark = earmark # The earmark is used as a token which can uniquely identify # this authentication utility instance even if the utility moves # from place to place within the same context chain or is renamed. # It is included in principal ids of principals which are obtained # from this auth utility, so code which dereferences a principal # (like getPrincipal of this auth utility) needs to take the earmark # into account. The earmark cannot change once it is assigned. If it # does change, the system will not be able to dereference principal # references which embed the old earmark. OrderedContainer.__init__(self) def authenticate(self, request): """ See `IAuthentication`. """ for ps_key, ps in self.items(): loginView = zapi.queryMultiAdapter((ps, request), name="login") if loginView is not None: principal = loginView.authenticate() if principal is not None: return principal next = queryNextUtility(self, IAuthentication, None) if next is not None: return next.authenticate(request) return None def unauthenticatedPrincipal(self): # It's safe to assume that the global auth utility will # provide an unauthenticated principal, so we won't bother. return None def unauthorized(self, id, request): """ See `IAuthentication`. """ next = queryNextUtility(self, IAuthentication) if next is not None: return next.unauthorized(id, request) return None def getPrincipal(self, id): """ See `IAuthentication`. For this implementation, an `id` is a string which can be split into a 3-tuple by splitting on tab characters. The three tuple consists of (`auth_utility_earmark`, `principal_source_id`, `principal_id`). In the current strategy, the principal sources that are members of this authentication utility cannot be renamed; if they are, principal references that embed the old name will not be dereferenceable. """ next = None try: auth_svc_earmark, principal_src_id, principal_id = id.split('\t',2) except (TypeError, ValueError, AttributeError): auth_svc_earmark, principal_src_id, principal_id = None, None, None next = queryNextUtility(self, IAuthentication) if auth_svc_earmark != self.earmark: # this is not our reference because its earmark doesnt match ours next = queryNextUtility(self, IAuthentication) if next is not None: return next.getPrincipal(id) source = self.get(principal_src_id) if source is None: raise PrincipalLookupError(principal_src_id) return source.getPrincipal(id) def getPrincipals(self, name): """ See `IAuthentication`. """ for ps_key, ps in self.items(): for p in ps.getPrincipals(name): yield p next = queryNextUtility(self, IAuthentication) if next is not None: for p in next.getPrincipals(name): yield p def addPrincipalSource(self, id, principal_source): """ See `IPluggableAuthentication`. >>> pas = PluggableAuthentication(None, True) >>> sps = BTreePrincipalSource() >>> pas.addPrincipalSource('simple', sps) >>> sps2 = BTreePrincipalSource() >>> pas.addPrincipalSource('not_quite_so_simple', sps2) >>> pas.keys() ['simple', 'not_quite_so_simple'] """ if not IPrincipalSource.providedBy(principal_source): raise TypeError("Source must implement IPrincipalSource") locate(principal_source, self, id) self[id] = principal_source def removePrincipalSource(self, id): """ See `IPluggableAuthentication`. >>> pas = PluggableAuthentication(None, True) >>> sps = BTreePrincipalSource() >>> pas.addPrincipalSource('simple', sps) >>> sps2 = BTreePrincipalSource() >>> pas.addPrincipalSource('not_quite_so_simple', sps2) >>> sps3 = BTreePrincipalSource() >>> pas.addPrincipalSource('simpler', sps3) >>> pas.keys() ['simple', 'not_quite_so_simple', 'simpler'] >>> pas.removePrincipalSource('not_quite_so_simple') >>> pas.keys() ['simple', 'simpler'] """ del self[id] # BBB: Gone in 3.3. PluggableAuthenticationService = PluggableAuthentication deprecated('PluggableAuthenticationService', 'The pluggable authentication service has been deprecated in ' 'favor of authentication (aka PAS). This reference will be gone in ' 'Zope 3.3.') def PluggableAuthenticationAddSubscriber(self, event): r"""Generates an earmark if one is not provided. Define a stub for `PluggableAuthentication` >>> from zope.traversing.interfaces import IPhysicallyLocatable >>> class PluggableAuthStub(object): ... implements(IPhysicallyLocatable) ... def __init__(self, earmark=None): ... self.earmark = earmark ... def getName(self): ... return 'PluggableAuthName' The subscriber generates an earmark for the auth utility if one is not set in the init. >>> stub = PluggableAuthStub() >>> event = '' >>> PluggableAuthenticationAddSubscriber(stub, event) >>> stub.earmark is not None True The subscriber does not modify an earmark for the auth utility if one exists already. >>> earmark = 'my sample earmark' >>> stub = PluggableAuthStub(earmark=earmark) >>> event = '' >>> PluggableAuthenticationAddSubscriber(stub, event) >>> stub.earmark == earmark True """ if self.earmark is None: # we manufacture what is intended to be a globally unique # earmark if one is not provided in __init__ myname = zapi.name(self) rand_id = gen_key() t = int(time.time()) self.earmark = '%s-%s-%s' % (myname, rand_id, t) class IBTreePrincipalSource( ILoginPasswordPrincipalSource, IContainerPrincipalSource, IContainedPrincipalSource, INameChooser, IContainerNamesContainer, ): def __setitem__(name, principal): """Add a `principal` The name must be the same as the principal login """ __setitem__.precondition = ItemTypePrecondition(IUserSchemafied) class IBTreePrincipalSourceContained(IContained): __parent__ = zope.schema.Field( constraint = ContainerTypesConstraint(IBTreePrincipalSource), ) class BTreePrincipalSource(Persistent, Contained): """An efficient, scalable provider of Authentication Principals.""" implements(IBTreePrincipalSource) def __init__(self): self._principals_by_number = IOBTree() self._numbers_by_login = OIBTree() # IContainer-related methods def __delitem__(self, login): """ See `IContainer`. >>> sps = BTreePrincipalSource() >>> prin = SimplePrincipal('fred', 'fred', '123') >>> sps['fred'] = prin >>> int(sps.get('fred') == prin) 1 >>> del sps['fred'] >>> int(sps.get('fred') == prin) 0 """ number = self._numbers_by_login[login] uncontained(self._principals_by_number[number], self, login) del self._principals_by_number[number] del self._numbers_by_login[login] def __setitem__(self, login, ob): """ See `IContainerNamesContainer` >>> sps = BTreePrincipalSource() >>> prin = SimplePrincipal('gandalf', 'shadowfax') >>> sps['doesntmatter'] = prin >>> sps.get('doesntmatter') """ setitem(self, self.__setitem, login, ob) def __setitem(self, login, ob): store = self._principals_by_number key = gen_key() while not store.insert(key, ob): key = gen_key() ob.id = key self._numbers_by_login[ob.login] = key def keys(self): """ See `IContainer`. >>> sps = BTreePrincipalSource() >>> sps.keys() [] >>> prin = SimplePrincipal('arthur', 'tea') >>> sps['doesntmatter'] = prin >>> sps.keys() ['arthur'] >>> prin = SimplePrincipal('ford', 'towel') >>> sps['doesntmatter'] = prin >>> sps.keys() ['arthur', 'ford'] """ return list(self._numbers_by_login.keys()) def __iter__(self): """ See `IContainer`. >>> sps = BTreePrincipalSource() >>> sps.keys() [] >>> prin = SimplePrincipal('trillian', 'heartOfGold') >>> sps['doesntmatter'] = prin >>> prin = SimplePrincipal('zaphod', 'gargleblaster') >>> sps['doesntmatter'] = prin >>> [i for i in sps] ['trillian', 'zaphod'] """ return iter(self.keys()) def __getitem__(self, key): """ See `IContainer` >>> sps = BTreePrincipalSource() >>> prin = SimplePrincipal('gag', 'justzisguy') >>> sps['doesntmatter'] = prin >>> sps['gag'].login 'gag' """ number = self._numbers_by_login[key] return self._principals_by_number[number] def get(self, key, default=None): """ See `IContainer` >>> sps = BTreePrincipalSource() >>> prin = SimplePrincipal(1, 'slartibartfast', 'fjord') >>> sps['slartibartfast'] = prin >>> principal = sps.get('slartibartfast') >>> sps.get('marvin', 'No chance, dude.') 'No chance, dude.' """ try: number = self._numbers_by_login[key] except KeyError: return default return self._principals_by_number[number] def values(self): """ See `IContainer`. >>> sps = BTreePrincipalSource() >>> sps.keys() [] >>> prin = SimplePrincipal('arthur', 'tea') >>> sps['doesntmatter'] = prin >>> [user.login for user in sps.values()] ['arthur'] >>> prin = SimplePrincipal('ford', 'towel') >>> sps['doesntmatter'] = prin >>> [user.login for user in sps.values()] ['arthur', 'ford'] """ return [self._principals_by_number[n] for n in self._numbers_by_login.values()] def __len__(self): """ See `IContainer` >>> sps = BTreePrincipalSource() >>> int(len(sps) == 0) 1 >>> prin = SimplePrincipal(1, 'trillian', 'heartOfGold') >>> sps['trillian'] = prin >>> int(len(sps) == 1) 1 """ return len(self._principals_by_number) def items(self): """ See `IContainer`. >>> sps = BTreePrincipalSource() >>> sps.keys() [] >>> prin = SimplePrincipal('zaphod', 'gargleblaster') >>> sps['doesntmatter'] = prin >>> [(k, v.login) for k, v in sps.items()] [('zaphod', 'zaphod')] >>> prin = SimplePrincipal('marvin', 'paranoid') >>> sps['doesntmatter'] = prin >>> [(k, v.login) for k, v in sps.items()] [('marvin', 'marvin'), ('zaphod', 'zaphod')] """ # We're being expensive here (see values() above) for convenience return [(p.login, p) for p in self.values()] def __contains__(self, key): """ See `IContainer`. >>> sps = BTreePrincipalSource() >>> prin = SimplePrincipal('slinkp', 'password') >>> sps['doesntmatter'] = prin >>> int('slinkp' in sps) 1 >>> int('desiato' in sps) 0 """ return self._numbers_by_login.has_key(key) has_key = __contains__ # PrincipalSource-related methods def getPrincipal(self, id): """ See `IPrincipalSource`. `id` is the id as returned by ``principal.getId()``, not a login. """ id = id.split('\t')[2] id = int(id) try: return self._principals_by_number[id] except KeyError: raise PrincipalLookupError(id) def getPrincipals(self, name): """ See `IPrincipalSource`. >>> sps = BTreePrincipalSource() >>> prin1 = SimplePrincipal('gandalf', 'shadowfax') >>> sps['doesntmatter'] = prin1 >>> prin1 = SimplePrincipal('frodo', 'ring') >>> sps['doesntmatter'] = prin1 >>> prin1 = SimplePrincipal('pippin', 'pipe') >>> sps['doesntmatter'] = prin1 >>> prin1 = SimplePrincipal('sam', 'garden') >>> sps['doesntmatter'] = prin1 >>> prin1 = SimplePrincipal('merry', 'food') >>> sps['doesntmatter'] = prin1 >>> [p.login for p in sps.getPrincipals('a')] ['gandalf', 'sam'] >>> [p.login for p in sps.getPrincipals('')] ['frodo', 'gandalf', 'merry', 'pippin', 'sam'] >>> [p.login for p in sps.getPrincipals('sauron')] [] """ for k in self.keys(): if k.find(name) != -1: yield self[k] def authenticate(self, login, password): """ See `ILoginPasswordPrincipalSource`. """ number = self._numbers_by_login.get(login) if number is None: return user = self._principals_by_number[number] if user.password == password: return user def checkName(self, name, object): """Check to make sure the name is valid Don't allow suplicate names: >>> sps = BTreePrincipalSource() >>> prin1 = SimplePrincipal('gandalf', 'shadowfax') >>> sps['gandalf'] = prin1 >>> sps.checkName('gandalf', prin1) Traceback (most recent call last): ... LoginNameTaken: gandalf """ if name in self._numbers_by_login: raise LoginNameTaken(name) def chooseName(self, name, object): """Choose a name for the principal Always choose the object's existing name: >>> sps = BTreePrincipalSource() >>> prin1 = SimplePrincipal('gandalf', 'shadowfax') >>> sps.chooseName(None, prin1) 'gandalf' """ return object.login class LoginNameTaken(Exception): """A login name is in use """ class SimplePrincipal(Persistent, Contained): """A no-frills `IUserSchemafied` implementation.""" implements(IUserSchemafied, IBTreePrincipalSourceContained) def __init__(self, login, password, title='', description=''): self._id = '' self.login = login self.password = password self.title = title self.description = description self.groups = [] def _getId(self): source = self.__parent__ auth = source.__parent__ return "%s\t%s\t%s" %(auth.earmark, source.__name__, self._id) def _setId(self, id): self._id = id id = property(_getId, _setId) def getTitle(self): warn("Use principal.title instead of principal.getTitle().", DeprecationWarning, 2) return self.title def getDescription(self): warn("Use principal.description instead of principal.getDescription().", DeprecationWarning, 2) return self.description def getLogin(self): """See `IReadUser`.""" return self.login def validate(self, test_password): """ See `IReadUser`. >>> pal = SimplePrincipal('gandalf', 'shadowfax', 'The Grey Wizard', ... 'Cool old man with neato fireworks. ' ... 'Has a nice beard.') >>> pal.validate('shdaowfax') False >>> pal.validate('shadowfax') True """ return test_password == self.password class PrincipalAuthenticationView(object): """Simple basic authentication view This only handles requests which have basic auth credentials in them currently (`ILoginPassword`-based requests). If you want a different policy, you'll need to write and register a different view, replacing this one. """ implements(IViewFactory) def __init__(self, context, request): self.context = context self.request = request def authenticate(self): a = ILoginPassword(self.request, None) if a is None: return login = a.getLogin() password = a.getPassword() p = self.context.authenticate(login, password) return p
zope.app.pluggableauth
/zope.app.pluggableauth-3.4.0.tar.gz/zope.app.pluggableauth-3.4.0/src/zope/app/pluggableauth/__init__.py
__init__.py
========= CHANGES ========= 4.1.0 (2022-08-05) ================== - Add support for Python 3.7, 3.8, 3.9, 3.10. - Drop support for Python 3.4. 4.0.0 (2017-05-17) ================== - Add support for Python 3.4, 3.5, 3.6 and PyPy. - Removed test dependency on ``zope.app.zcmlfiles`` and ``zope.app.renderer``, among others. ``zope.app.renderer`` is still required at runtime. - Broke test dependency on ``zope.app.testing`` by using ``zope.app.wsgi.testlayer``. 3.8.1 (2010-06-15) ================== - Fixed BBB imports which pointed to a not existing `zope.preferences` package. 3.8.0 (2010-06-12) ================== - Depend on split out `zope.preference`. 3.7.0 (2010-06-11) ================== - Added HTML labels to ZMI forms. - Removed `edit.pt` as it seems to be unused. - Added tests for the ZMI views. 3.6.0 (2009-02-01) ================== - Use ``zope.container`` instead of ``zope.app.container``. 3.5.0 (2009-01-17) ================== - Got rid of ``zope.app.zapi`` dependency, replacing its uses with direct imports from original places. - Change mailing address from zope3-dev to zope-dev, as the first one is retired now. - Fix tests for python 2.6. - Remove zpkg stuff and zcml include files for old mkzopeinstance-based instances. 3.4.1 (2007-10-30) ================== - Avoid deprecation warnings for ``ZopeMessageFactory``. 3.4.0 (2007-10-25) ================== - Initial release independent of the main Zope tree.
zope.app.preference
/zope.app.preference-4.1.0.tar.gz/zope.app.preference-4.1.0/CHANGES.rst
CHANGES.rst
===================== zope.app.preference ===================== This package provides a user interface in the ZMI, so the user can edit the preferences. Set up ====== To show the user interface functions we need some setup beforehand: >>> from zope.testbrowser.wsgi import Browser >>> browser = Browser() >>> browser.handleErrors = False As the preferences cannot be defined through the web we have to define them in python code: >>> import zope.interface >>> import zope.schema >>> class IZMIUserSettings(zope.interface.Interface): ... """Basic User Preferences""" ... ... email = zope.schema.TextLine( ... title=u"E-mail Address", ... description=u"E-mail Address used to send notifications") ... ... skin = zope.schema.Choice( ... title=u"Skin", ... description=u"The skin that should be used for the ZMI.", ... values=['Rotterdam', 'ZopeTop', 'Basic'], ... default='Rotterdam') ... ... showZopeLogo = zope.schema.Bool( ... title=u"Show Zope Logo", ... description=u"Specifies whether Zope logo should be displayed " ... u"at the top of the screen.", ... default=True) >>> class INotCategorySettings(zope.interface.Interface): ... """An example that's not a categary""" ... comment = zope.schema.TextLine( ... title=u'A comment', ... description=u'A description') The preference schema is usually registered using a ZCML statement: >>> from zope.configuration import xmlconfig >>> import zope.preference >>> context = xmlconfig.file('meta.zcml', zope.preference) >>> context = xmlconfig.string(''' ... <configure ... xmlns="http://namespaces.zope.org/zope" ... i18n_domain="test"> ... ... <preferenceGroup ... id="ZMISettings" ... title="ZMI Settings" ... schema="zope.app.preference.README.IZMIUserSettings" ... category="true" ... /> ... ... <preferenceGroup ... id="NotCategory" ... title="Not Category" ... schema="zope.app.preference.README.INotCategorySettings" ... category="false" ... /> ... ... </configure>''', context) Editing Preferences =================== The preferences are accessable in the ``++preferences++`` namespace: >>> browser.open('http://localhost/++preferences++') The page shows a form which allows editing the preference values: >>> browser.getControl("comment").value = "A comment" >>> browser.getControl('E-mail').value = '[email protected]' >>> browser.getControl('Skin').displayOptions ['Rotterdam', 'ZopeTop', 'Basic'] >>> browser.getControl('Skin').displayValue = ['ZopeTop'] >>> browser.getControl('Show Zope Logo').selected True >>> browser.getControl('Show Zope Logo').click() After selecting `Change` the values get persisted: >>> browser.getControl('Change').click() >>> browser.url 'http://localhost/++preferences++/@@index.html' >>> browser.getControl('E-mail').value '[email protected]' >>> browser.getControl('Skin').displayValue ['ZopeTop'] >>> browser.getControl('Show Zope Logo').selected False The preference group is shown in a tree. It has a link to the form: >>> browser.getLink('ZMISettings').click() >>> browser.url 'http://localhost/++preferences++/ZMISettings/@@index.html' >>> browser.getControl('E-mail').value '[email protected]' Preference Group Trees ====================== The preferences would not be very powerful, if you could create a full preferences. So let's create a sub-group for our ZMI user settings, where we can adjust the look and feel of the folder contents view: >>> class IFolderSettings(zope.interface.Interface): ... """Basic Folder Settings""" ... ... shownFields = zope.schema.Set( ... title=u"Shown Fields", ... description=u"Fields shown in the table.", ... value_type=zope.schema.Choice(['name', 'size', 'creator']), ... default=set(['name', 'size'])) ... ... sortedBy = zope.schema.Choice( ... title=u"Sorted By", ... description=u"Data field to sort by.", ... values=['name', 'size', 'creator'], ... default='name') And register it: >>> context = xmlconfig.string(''' ... <configure ... xmlns="http://namespaces.zope.org/zope" ... i18n_domain="test"> ... ... <preferenceGroup ... id="ZMISettings.Folder" ... title="Folder Content View Settings" ... schema="zope.app.preference.README.IFolderSettings" ... /> ... ... </configure>''', context) The sub-group is displayed inside the parent group as a form: >>> browser.reload() >>> browser.getControl('Shown Fields').displayOptions ['name', 'size', 'creator'] >>> browser.getControl('Shown Fields').displayValue ['name', 'size'] >>> browser.getControl('Shown Fields').displayValue = ['size', 'creator'] >>> browser.getControl('Sorted By').displayOptions ['name', 'size', 'creator'] >>> browser.getControl('Sorted By').displayValue = ['creator'] Selecing `Change` persists these values, too: >>> browser.getControl('Change').click() >>> browser.getControl('Shown Fields').displayValue ['size', 'creator'] >>> browser.getControl('Sorted By').displayValue ['creator'] >>> browser.open("http://localhost/++preferences++/ZMISettings.Folder/@@index.html")
zope.app.preference
/zope.app.preference-4.1.0.tar.gz/zope.app.preference-4.1.0/src/zope/app/preference/README.rst
README.rst
__docformat__ = 'restructuredtext' import re import zope.component import zope.interface from zope.app.basicskin.standardmacros import StandardMacros from zope.app.form.browser.editview import EditView from zope.app.tree.browser.cookie import CookieTreeView from zope.container.interfaces import IObjectFindFilter from zope.i18n import translate from zope.i18nmessageid import Message from zope.i18nmessageid import ZopeMessageFactory as _ from zope.preference import interfaces from zope.security.proxy import removeSecurityProxy from zope.traversing.api import getParent from zope.traversing.api import getRoot NoneInterface = zope.interface.interface.InterfaceClass('None') class PreferencesMacros(StandardMacros): """Page Template METAL macros for preferences""" macro_pages = ('preference_macro_definitions',) @zope.interface.implementer(IObjectFindFilter) class PreferenceGroupFilter(object): """A special filter for preferences""" def matches(self, obj): """Decide whether the object is shown in the tree.""" matches = False if interfaces.IPreferenceCategory.providedBy(obj): # IPreferenceGroup objects dynamically implement # IPreferenceCategory matches = True elif interfaces.IPreferenceGroup.providedBy(obj): parent = getParent(obj) matches = interfaces.IPreferenceCategory.providedBy(parent) return matches class PreferencesTree(CookieTreeView): """Preferences Tree using the stateful cookie tree.""" def tree(self): root = getRoot(self.context) filter = PreferenceGroupFilter() return self.cookieTree(root, filter) pref_msg = _("${name} Preferences") class EditPreferenceGroup(EditView): def __init__(self, context, request): self.__used_for__ = removeSecurityProxy(context.__schema__) self.schema = removeSecurityProxy(context.__schema__) if self.schema is None: self.schema = NoneInterface zope.interface.alsoProvides(removeSecurityProxy(context), NoneInterface) name = translate(context.__title__, context=request, default=context.__title__) self.label = Message(pref_msg, mapping={u'name': name}) super(EditPreferenceGroup, self).__init__(context, request) self.setPrefix(context.__id__) def getIntroduction(self): text = self.context.__description__ or self.schema.__doc__ text = translate(text, context=self.request, default=text) # Determine common whitespace ... cols = len(re.match('^[ ]*', text).group()) # ... and clean it up. text = re.sub('\n[ ]{%i}' % cols, '\n', text).strip() if not text: return u'' # Render the description as ReST. source = zope.component.createObject('zope.source.rest', text) renderer = zope.component.getMultiAdapter((source, self.request)) return renderer.render()
zope.app.preference
/zope.app.preference-4.1.0.tar.gz/zope.app.preference-4.1.0/src/zope/app/preference/browser.py
browser.py
======= CHANGES ======= 5.0 (2023-02-08) ---------------- - Add support for Python 3.10, 3.11. - Drop support for Python 2.7, 3.5, 3.6. 4.5 (2020-11-05) ---------------- - Add support for Python 3.8 and 3.9. - Update the tests to ``zope.app.wsgi >= 4.3``. 4.4 (2020-05-14) ---------------- - Drop support for ``python setup.py test``. 4.3.2 (2019-12-04) ------------------ - Fix deprecation warning in tests. 4.3.1 (2019-07-01) ------------------ - Updated expected doc output to match latest library versions (yes, again). - Fixed supported Python versions in .travis.yml. - Avoid passing unicode text to logging.Logger.warning() on Python 2 (`issue 8 <https://github.com/zopefoundation/zope.app.publication/issues/8>`_). 4.3.0 (2018-10-09) ------------------ - Drop Python 3.4 support and added 3.7. - Updated expected doc output to match latest library versions. - Removed all deprecation warnings. 4.2.1 (2017-04-17) ------------------ - Include ``MANIFEST.in`` since it is needed for pip install. 4.2.0 (2016-11-23) ------------------ - Update the code to be compatible with ``transaction >= 2.0``. - Update tests to be compatible with ``ZODB >= 5.1``, thus requiring at least this version for the tests. - Drop Python 3.3 support. 4.1.0 (2016-08-08) ------------------ - Test against released final versions, thus requiring ``zope.app.http`` >= 4.0 (test dependency). 4.0.0 (2016-08-08) ------------------ - Claim compatibility to Python 3.4 and 3.5 and drop support for Python 2.6. - Improve the publication factory lookup by falling back to a more generic registration if the specific factory chooses not to handle the request after all. - Relax ZODB dependency to allow 3.10dev builds from SVN. - Introduce ZopePublication.callErrorView as a possible hook point. 3.14.0 (2012-03-09) ------------------- - Replace ZODB.POSException.ConflictError with transaction.interfaces.TransientError. The latter should be a more generic signal to retry a transaction/request. This requires ZODB3 >= 3.10.0 and transaction >= 1.1.0. - Get rid of ZODB dependency. 3.13.2 (2011-08-04) ------------------- - Add missing test dependency on zope.testing. - Remove test dependency on zope.app.exception. 3.13.1 (2011-03-14) ------------------- - Test fix: HTTP request should not have leading whitespace. 3.13.0 (2011-01-25) ------------------- - Reenabled a test which makes sure ``405 MethodNotAllowed`` is returned when PUT is not supported. This requires at least version 3.10 of zope.app.http. 3.12.0 (2010-09-14) ------------------- - Use the standard libraries doctest module. - Include the ``notfound.txt`` test again but reduce its scope to functionality relevant to this distribution. - Notify with IStartRequestEvent at the start of the request publication cycle. 3.11.1 (2010-04-19) ------------------- - Fix up tests to work with newer zope.app.wsgi release (3.9.0). 3.11.0 (2010-04-13) ------------------- - Don't depend on zope.app.testing and zope.app.zcmlfiles anymore in the tests. 3.10.2 (2010-01-08) ------------------- - Lift the test dependency on zope.app.zptpage. 3.10.1 (2010-01-08) ------------------- - make zope.testing an optional (test) dependency - Fix tests using a newer zope.publisher that requires zope.login. 3.10.0 (2009-12-15) ------------------- - Moved EndRequestEvent and IEndRequestEvent to zope.publisher. - Moved BeforeTraverseEvent and IBeforeTraverseEvent to zope.traversing. - Removed dependency on zope.i18n. - Import hooks functionality from zope.component after it was moved there from zope.site. - Import ISite from zope.component after it was moved there from zope.location. 3.9.0 (2009-09-29) ------------------ - An abort within handleExceptions could have failed without logging what caused the error. It now logs the original problem. - Moved registration of and tests for two publication-specific event handlers here from zope.site in order to invert the package dependency. - Declared the missing dependency on zope.location. 3.8.1 (2009-06-21) ------------------ - Bug fix: The publication traverseName method used ProxyFactory rather than the publication proxy method. 3.8.0 (2009-06-20) ------------------ - Added a proxy method that can be overridden in subclasses to control how/if security proxies are created. - Replaced zope.deprecation dependency with backward-compatible imports 3.7.0 (2009-05-23) ------------------ - Moved the publicationtraverse module to zope.traversing, removing the zope.app.publisher -> zope.app.publication dependency (which was a cycle). - Moved IHTTPException to zope.publisher, removing the dependency on zope.app.http. - Moved the DefaultViewName API from zope.app.publisher.browser to zope.publisher.defaultview, making it accessible to other packages that need it. - Look up the application controller through a utility registration rather than a direct reference. 3.6.0 (2009-05-18) ------------------ - Use ``zope:adapter`` ZCML directive instead of ``zope:view``. This avoid dependency on ``zope.app.component``. - Update imports from ``zope.app.security`` to ``zope.authentication`` and ``zope.principalregistry``. - Use ``zope.browser.interfaces.ISystemError`` to avoid dependency on ``zope.app.exception``. - Refactored tests so they can run successfully with ZODB 3.8 and 3.9. 3.5.3 (2009-03-13) ------------------ - Adapt to the removal of IXMLPresentation from zope.app.publisher which was removed to adapt to removal of deprecated interfaces from zope.component. 3.5.2 (2009-03-10) ------------------ - Use ISkinnable.providedBy(request) instead of IBrowserRequest as condition for calling setDefaultSkin. This at the same time removes dependency to the browser part of zope.publisher. - Remove deprecated code. - Use built-in set class instead of the deprecated sets.Set and thus don't cause deprecation warning in Python 2.6. 3.5.1 (2009-01-31) ------------------ - Import ISite from zope.location.interfaces instead of deprecated place in zope.app.component.interfaces. 3.5.0 (2008-10-09) ------------------ - Now ``zope.app.publication.zopepublication.ZopePublication`` annotates the request with the connection to the main ZODB when ``getApplication`` is called. - Removed support for non-existent Zope versions. 3.4.3 (2007-11-01) ------------------ - Removed unused imports. - Resolve ``ZopeSecurityPolicy`` deprecation warning. 3.4.2 (2007-09-26) ------------------ - Added missing files to egg distribution. 3.4.1 (2007-09-26) ------------------ - Added missing files to egg distribution. 3.4.0 (2007-09-25) ------------------ - Initial documented release. - Reflect changes form ``zope.app.error`` refactoring.
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/CHANGES.rst
CHANGES.rst
Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/LICENSE.rst
LICENSE.rst
================= HTTPFactory tests ================= This tests that httpfactory provide the right publication class, for each request type, defined in the configure.zcml with publisher directive. The publication class is chosen upon the method name, the mime type and sometimes some request headers A regular GET, POST or HEAD >>> from __future__ import print_function >>> from zope.app.wsgi.testlayer import http >>> print(http(wsgi_app, b"""\ ... GET / HTTP/1.1 ... """)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 ... >>> print(http(wsgi_app, b"""\ ... POST / HTTP/1.1 ... """)) HTTP/1.1 200 OK Content-Length: ... Content-Type: text/html;charset=utf-8 ... >>> print(http(wsgi_app, b"""\ ... HEAD / HTTP/1.1 ... """)) HTTP/1.1 200 OK Content-Length: 0 Content-Type: text/html;charset=utf-8 <BLANKLINE> A text/xml POST request, wich is an xml-rpc call >>> print(http(wsgi_app, b"""\ ... POST /RPC2 HTTP/1.0 ... Content-Type: text/xml ... """)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml;charset=utf-8 ... A text/xml POST request, with a HTTP_SOAPACTION in the headers, wich is an xml-rpc call: TODO need to create a real SOAP exchange test here >>> print(http(wsgi_app, b"""\ ... POST /RPC2 HTTP/1.0 ... Content-Type: text/xml ... HTTP_SOAPACTION: soap#action ... """)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml;charset=utf-8 ... Unknown request types: TODO need more testing here >>> print(http(wsgi_app, b"""\ ... POST /BUBA HTTP/1.0 ... Content-Type: text/topnotch ... """)) HTTP/1.0 404 Not Found ...
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/src/zope/app/publication/httpfactory.rst
httpfactory.rst
====================== Using the site manager ====================== This test ensures that the site is correctly set and cleared in a thread during traversal using event subscribers. Before we start, no site is set: >>> from zope.component import hooks >>> hooks.getSite() is None True >>> request = object() >>> from zope.app.publication import interfaces >>> from zope import site On the other hand, if a site is traversed, >>> from zope.site.tests.test_site import SiteManagerStub, CustomFolder >>> sm = SiteManagerStub() >>> mysite = CustomFolder('mysite') >>> mysite.setSiteManager(sm) >>> from zope.traversing.interfaces import BeforeTraverseEvent >>> ev = BeforeTraverseEvent(mysite, request) >>> site.threadSiteSubscriber(mysite, ev) >>> hooks.getSite() <CustomFolder mysite> Once the request is completed, >>> from zope.publisher.interfaces import EndRequestEvent >>> ev = EndRequestEvent(mysite, request) >>> site.clearThreadSiteSubscriber(ev) the site assignment is cleared again: >>> hooks.getSite() is None True
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/src/zope/app/publication/site.rst
site.rst
"""Generic object traversers """ import zope.component from zope.interface import implementer from zope.interface import providedBy from zope.publisher.defaultview import getDefaultViewName from zope.publisher.interfaces import NotFound from zope.publisher.interfaces import Unauthorized from zope.publisher.interfaces.browser import IBrowserPublisher from zope.publisher.interfaces.xmlrpc import IXMLRPCPublisher @implementer(IBrowserPublisher, IXMLRPCPublisher) class SimpleComponentTraverser: """Browser traverser for simple components that can only traverse to views """ def __init__(self, context, request): self.context = context self.request = request def browserDefault(self, request): ob = self.context view_name = getDefaultViewName(ob, request) return ob, (view_name,) def publishTraverse(self, request, name): ob = self.context view = zope.component.queryMultiAdapter((ob, request), name=name) if view is None: raise NotFound(ob, name) return view class FileContentTraverser(SimpleComponentTraverser): """Browser traverser for file content. The default view for file content has effective URLs that don't end in /. In particular, if the content inclused HTML, relative links in the HTML are relative to the container the content is in. """ def browserDefault(self, request): ob = self.context view_name = getDefaultViewName(ob, request) view = self.publishTraverse(request, view_name) if hasattr(view, 'browserDefault'): view, path = view.browserDefault(request) if len(path) == 1: view = view.publishTraverse(request, path[0]) path = () else: path = () return view, path def NoTraverser(ob, request): return None @implementer(IBrowserPublisher) class TestTraverser: """Bobo-style traverser, mostly useful for testing""" def __init__(self, context, request): self.context = context def browserDefault(self, request): ob = self.context providedIfaces = [iface for iface in providedBy(ob)] if providedIfaces: view_name = getDefaultViewName(ob, request) return ob, (("@@%s" % view_name),) return ob, () def publishTraverse(self, request, name): ob = self.context if name.startswith('@@'): return zope.component.getMultiAdapter((ob, request), name=name[6:]) if name.startswith('_'): raise Unauthorized(name) subob = getattr(ob, name, self) # self is marker here if subob is self: # no attribute try: subob = ob[name] except (KeyError, IndexError, TypeError, AttributeError): raise NotFound(ob, name, request) return subob
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/src/zope/app/publication/traversers.py
traversers.py
"""Publication Interfaces """ # BBB: Re-import symbols to their old location. from zope.publisher.interfaces import EndRequestEvent # noqa: F401 (BBB) from zope.publisher.interfaces import IEndRequestEvent # noqa: F401 (BBB) from zope.traversing.interfaces import BeforeTraverseEvent # noqa: F401 (BBB) from zope.traversing.interfaces import IBeforeTraverseEvent # noqa: F401 (BBB) from zope import interface class IPublicationRequestFactory(interface.Interface): """Publication request factory""" def __call__(input_stream, env): """Create a request object to handle the given inputs A request is created and configured with a publication object. """ class IRequestFactory(interface.Interface): def __call__(input_stream, env): """Create a request object to handle input.""" class ISOAPRequestFactory(IRequestFactory): """SOAP request factory""" class IHTTPRequestFactory(IRequestFactory): # TODO: should SOAP, XMLRPC, and Browser extend this? """generic HTTP request factory""" class IXMLRPCRequestFactory(IRequestFactory): """XMLRPC request factory""" class IBrowserRequestFactory(IRequestFactory): """Browser request factory""" class IFileContent(interface.Interface): """Marker interface for content that can be managed as files. The default view for file content has effective URLs that don't end in `/`. In particular, if the content included HTML, relative links in the HTML are relative to the container the content is in. """ class IRequestPublicationFactory(interface.Interface): """Request-publication factory""" def canHandle(environment): """Return ``True`` if it can handle the request, otherwise ``False``. `environment` can be used by the factory to make a decision based on the HTTP headers. """ def __call__(): """Return a tuple (request, publication)""" class IRequestPublicationRegistry(interface.Interface): """A registry to lookup a RequestPublicationFactory by request method + mime-type. Multiple factories can be configured for the same method+mimetype. The factory itself can introspect the environment to decide if it can handle the request as given by the environment or not. Factories are sorted in the order of their registration in ZCML. """ def register(method, mimetype, name, priority, factory): """Register a factory for method+mimetype.""" def lookup(method, mimetype, environment): """Lookup a factory for a given method+mimetype and a environment. Raises ConfigurationError if no factory can be found. """ def getFactoriesFor(method, mimetype): """Return the internal datastructure representing the configured factories (basically for testing, not for introspection). """
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/src/zope/app/publication/interfaces.py
interfaces.py
"""A registry for Request-Publication factories. """ from zope.configuration.exceptions import ConfigurationError from zope.interface import implementer from zope.app.publication.interfaces import IRequestPublicationRegistry @implementer(IRequestPublicationRegistry) class RequestPublicationRegistry: """The registry implements a three stage lookup for registered factories that have to deal with requests:: {method > { mimetype -> [{'priority' : some_int, 'factory' : factory, 'name' : some_name }, ... ] }, } The `priority` is used to define a lookup-order when multiple factories are registered for the same method and mime-type. """ def __init__(self): self._d = {} # method -> { mimetype -> {factories_data}} def register(self, method, mimetype, name, priority, factory): """Register a factory for method+mimetype""" # initialize the two-level deep nested datastructure if necessary if method not in self._d: self._d[method] = {} if mimetype not in self._d[method]: self._d[method][mimetype] = [] factories_data = self._d[method][mimetype] # Check if there is already a registered publisher factory (check by # name). If yes then it will be removed and replaced by a new # publisher. for pos, d in enumerate(factories_data): if d['name'] == name: del factories_data[pos] break # add the publisher factory + additional informations factories_data.append( {'name': name, 'factory': factory, 'priority': priority}) # order by descending priority factories_data.sort(key=lambda v: v['priority'], reverse=True) # check if the priorities are unique priorities = [item['priority'] for item in factories_data] if len(set(priorities)) != len(factories_data): raise ConfigurationError('All registered publishers for a given ' 'method+mimetype must have distinct ' 'priorities. Please check your ZCML ' 'configuration') def getFactoriesFor(self, method, mimetype): if ';' in mimetype: # `mimetype` might be something like 'text/xml; charset=utf8'. In # this case we are only interested in the first part. mimetype = mimetype.split(';')[0] try: return self._d[method][mimetype.strip()] except KeyError: return None def lookup(self, method, mimetype, environment): """Lookup a factory for a given method+mimetype and a environment. """ for m, mt in ((method, mimetype), (method, '*'), ('*', '*')): # Collect, in order, from most specific to most generic, the # factories that potentially handle the given environment. # Now iterate over all factory candidates and let them # introspect the request environment to figure out if # they can handle the request. The first one to accept the # environment, wins. found = self.getFactoriesFor(m, mt) if found is None: continue for info in found: factory = info['factory'] if factory.canHandle(environment): return factory raise ConfigurationError( f'No registered publisher found for ({method}/{mimetype})') factoryRegistry = RequestPublicationRegistry() try: import zope.testing.cleanup except ImportError: pass else: zope.testing.cleanup.addCleanUp(lambda: factoryRegistry.__init__())
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/src/zope/app/publication/requestpublicationregistry.py
requestpublicationregistry.py
Method Not Allowed errors ========================= If we get a request with a method that does not have a corresponding view, HTTP 405 Method Not Allowed response is returned: >>> from __future__ import print_function >>> from zope.app.wsgi.testlayer import http >>> print(http(wsgi_app, b"""\ ... FROG / HTTP/1.1 ... """)) HTTP/1.1 405 Method Not Allowed Allow: DELETE, OPTIONS, PUT Content-Length: 18 ... >>> print(http(wsgi_app, b"""\ ... DELETE / HTTP/1.1 ... """)) HTTP/1.1 405 Method Not Allowed ... Trying to PUT on an object which does not support PUT leads to 405: >>> print(http(wsgi_app, b"""\ ... PUT / HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """)) HTTP/1.1 405 Method Not Allowed ... Trying to PUT a not existing object on a container which does not support PUT leads to 405: >>> print(http(wsgi_app, b"""\ ... PUT /asdf HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """)) HTTP/1.1 405 Method Not Allowed ... When ``handle_errors`` is set to ``False`` a traceback is displayed: >>> print(http(wsgi_app, b"""\ ... PUT / HTTP/1.1 ... Authorization: Basic mgr:mgrpw ... """, handle_errors=False)) Traceback (most recent call last): MethodNotAllowed: <...Folder object at 0x...>, <zope.publisher.http.HTTPRequest instance URL=http://localhost>
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/src/zope/app/publication/methodnotallowed.rst
methodnotallowed.rst
import logging import sys from types import MethodType import transaction import zope.authentication.interfaces import zope.component import zope.component.interfaces from zope.authentication.interfaces import IAuthentication from zope.authentication.interfaces import IFallbackUnauthenticatedPrincipal from zope.authentication.interfaces import IUnauthenticatedPrincipal from zope.browser.interfaces import ISystemErrorView from zope.component import queryMultiAdapter from zope.error.interfaces import IErrorReportingUtility from zope.event import notify from zope.interface import implementer from zope.interface import providedBy from zope.location import LocationProxy from zope.publisher.defaultview import queryDefaultViewName from zope.publisher.interfaces import EndRequestEvent from zope.publisher.interfaces import IExceptionSideEffects from zope.publisher.interfaces import IHeld from zope.publisher.interfaces import IPublication from zope.publisher.interfaces import IPublishTraverse from zope.publisher.interfaces import IRequest from zope.publisher.interfaces import NotFound from zope.publisher.interfaces import Retry from zope.publisher.interfaces import StartRequestEvent from zope.publisher.publish import mapply from zope.security.checker import ProxyFactory from zope.security.management import endInteraction from zope.security.management import newInteraction from zope.security.proxy import removeSecurityProxy from zope.traversing.interfaces import BeforeTraverseEvent from zope.traversing.interfaces import IEtcNamespace from zope.traversing.interfaces import IPhysicallyLocatable from zope.traversing.interfaces import TraversalError from zope.traversing.namespace import namespaceLookup from zope.traversing.namespace import nsParse @implementer(IHeld) class Cleanup: def __init__(self, f): self._f = f def release(self): self._f() self._f = None def __del__(self): if self._f is not None: logging.getLogger('SiteError').error( "Cleanup without request close") self._f() @implementer(IPublication) class ZopePublication: """Base Zope publication specification.""" root_name = 'Application' def __init__(self, db): # db is a ZODB.DB.DB object. self.db = db def proxy(self, ob): """Security-proxy an object Subclasses may override this to use a different proxy (or checker) implementation or to not proxy at all. """ return ProxyFactory(ob) def beforeTraversal(self, request): notify(StartRequestEvent(request)) # Try to authenticate against the root authentication utility. auth = zope.component.getGlobalSiteManager().getUtility( zope.authentication.interfaces.IAuthentication) principal = auth.authenticate(request) if principal is None: principal = auth.unauthenticatedPrincipal() if principal is None: # Get the fallback unauthenticated principal principal = zope.component.getUtility( IFallbackUnauthenticatedPrincipal) request.setPrincipal(principal) newInteraction(request) transaction.begin() def _maybePlacefullyAuthenticate(self, request, ob): if not IUnauthenticatedPrincipal.providedBy(request.principal): # We've already got an authenticated user. There's nothing to do. # Note that beforeTraversal guarentees that user is not None. return if not zope.component.interfaces.ISite.providedBy(ob): # We won't find an authentication utility here, so give up. return sm = removeSecurityProxy(ob).getSiteManager() auth = sm.queryUtility(IAuthentication) if auth is None: # No auth utility here return # Try to authenticate against the auth utility principal = auth.authenticate(request) if principal is None: principal = auth.unauthenticatedPrincipal() if principal is None: # nothing to do here return request.setPrincipal(principal) def callTraversalHooks(self, request, ob): # Call __before_publishing_traverse__ hooks notify(BeforeTraverseEvent(ob, request)) # This is also a handy place to try and authenticate. self._maybePlacefullyAuthenticate(request, ob) def afterTraversal(self, request, ob): # recordMetaData(object, request) self._maybePlacefullyAuthenticate(request, ob) def openedConnection(self, conn): # Hook for auto-refresh pass def getApplication(self, request): # If '++etc++process' is in the path, then we should # get the parent of the application controller rather than # open the database. stack = request.getTraversalStack() if '++etc++process' in stack: obj = zope.component.getUtility(IEtcNamespace, 'process') return obj.__parent__ # Open the database. conn = self.db.open() cleanup = Cleanup(conn.close) request.hold(cleanup) # Close the connection on request.close() request.annotations['ZODB.interfaces.IConnection'] = conn self.openedConnection(conn) # conn.setDebugInfo(getattr(request, 'environ', None), request.other) root = conn.root() app = root.get(self.root_name, None) if app is None: raise SystemError("Zope Application Not Found") return self.proxy(app) def traverseName(self, request, ob, name): nm = name # the name to look up the object with if name and name[:1] in '@+': # Process URI segment parameters. ns, nm = nsParse(name) if ns: try: ob2 = namespaceLookup(ns, nm, ob, request) except TraversalError: raise NotFound(ob, name) return self.proxy(ob2) if nm == '.': return ob if IPublishTraverse.providedBy(ob): ob2 = ob.publishTraverse(request, nm) else: # self is marker adapter = queryMultiAdapter((ob, request), IPublishTraverse, default=self) if adapter is not self: ob2 = adapter.publishTraverse(request, nm) else: raise NotFound(ob, name, request) return self.proxy(ob2) def callObject(self, request, ob): return mapply(ob, request.getPositionalArguments(), request) def callErrorView(self, request, view): # We don't want to pass positional arguments. The positional # arguments were meant for the published object, not an exception # view. return mapply(view, (), request) def afterCall(self, request, ob): txn = transaction.get() if txn.isDoomed(): txn.abort() else: self.annotateTransaction(txn, request, ob) txn.commit() def endRequest(self, request, ob): endInteraction() notify(EndRequestEvent(ob, request)) def annotateTransaction(self, txn, request, ob): """Set some useful meta-information on the transaction. This information is used by the undo framework, for example. This method is not part of the `IPublication` interface, since it's specific to this particular implementation. """ if request.principal is not None: principal_id = str(request.principal.id) txn.setUser(principal_id) # Work around methods that are usually used for views bare = removeSecurityProxy(ob) if isinstance(bare, MethodType): ob = bare.__self__ # set the location path path = None locatable = IPhysicallyLocatable(ob, None) if locatable is not None: # Views are made children of their contexts, but that # doesn't necessarily mean that we can fully resolve the # path. E.g. the family tree of a resource cannot be # resolved completely, as the site manager is a dead end. try: path = locatable.getPath() except (AttributeError, TypeError): pass if path is not None: txn.setExtendedInfo('location', path) # set the request type iface = IRequest for iface in providedBy(request): if iface.extends(IRequest): break iface_dotted = iface.__module__ + '.' + iface.getName() txn.setExtendedInfo('request_type', iface_dotted) return txn def _logErrorWithErrorReportingUtility(self, object, request, exc_info): # Record the error with the ErrorReportingUtility self.beginErrorHandlingTransaction(request, object, 'error reporting utility') try: errUtility = zope.component.getUtility(IErrorReportingUtility) # It is important that an error in errUtility.raising # does not propagate outside of here. Otherwise, nothing # meaningful will be returned to the user. # # The error reporting utility should not be doing database # stuff, so we shouldn't get a conflict error. # Even if we do, it is more important that we log this # error, and proceed with the normal course of events. # We should probably (somehow!) append to the standard # error handling that this error occurred while using # the ErrorReportingUtility, and that it will be in # the zope log. errUtility.raising(exc_info, request) transaction.commit() except Exception: tryToLogException( 'Error while reporting an error to the Error Reporting utility' ) transaction.abort() def handleException(self, object, request, exc_info, retry_allowed=True): # This transaction had an exception that reached the publisher. # It must definitely be aborted. try: transaction.abort() except Exception: # Hm, a catastrophe. We might want to know what preceded it. self._logErrorWithErrorReportingUtility(object, request, exc_info) raise # Reraise Retry exceptions for the publisher to deal with. if retry_allowed and isinstance(exc_info[1], Retry): raise # Convert ConflictErrors to Retry exceptions. # where transaction.interfaces.TransientError is a more generic # exception if retry_allowed and isinstance(exc_info[1], transaction.interfaces.TransientError): tryToLogWarning( 'ZopePublication', 'Competing writes/reads at %r: %s' % (request.get('PATH_INFO', '???'), exc_info[1], ), ) raise Retry(exc_info) # Are there any reasons why we'd want to let application-level error # handling determine whether a retry is allowed or not? # Assume not for now. # Record the error with the ErrorReportingUtility. self._logErrorWithErrorReportingUtility(object, request, exc_info) response = request.response response.reset() exception = None legacy_exception = not isinstance(exc_info[1], Exception) if legacy_exception: response.handleException(exc_info) if isinstance(exc_info[1], str): tryToLogWarning( 'Publisher received a legacy string exception: %s.' ' This will be handled by the request.' % exc_info[1]) else: tryToLogWarning( 'Publisher received a legacy classic class exception: %s.' ' This will be handled by the request.' % exc_info[1].__class__) else: # We definitely have an Exception # Set the request body, and abort the current transaction. self.beginErrorHandlingTransaction( request, object, 'application error-handling') view = None try: # We need to get a location, because some template content of # the exception view might require one. # # The object might not have a parent, because it might be a # method. If we don't have a `__parent__` attribute but have # an im_self or a __self__, use it. loc = object if not hasattr(object, '__parent__'): loc = removeSecurityProxy(object) # Try to get an object, since we apparently have a method # Note: We are guaranteed that an object has a location, # so just getting the instance the method belongs to is # sufficient. loc = getattr(loc, 'im_self', loc) loc = getattr(loc, '__self__', loc) # Protect the location with a security proxy loc = self.proxy(loc) # Give the exception instance its location and look up the # view. exception = LocationProxy(exc_info[1], loc, '') name = queryDefaultViewName(exception, request) if name is not None: view = zope.component.queryMultiAdapter( (exception, request), name=name) except Exception: # Problem getting a view for this exception. Log an error. tryToLogException( 'Exception while getting view on exception') if view is not None: try: body = self.callErrorView(request, view) response.setResult(body) transaction.commit() if (ISystemErrorView.providedBy(view) and view.isSystemError()): # Got a system error, want to log the error # Lame hack to get around logging missfeature # that is fixed in Python 2.4 try: raise exc_info[1].with_traceback(exc_info[2]) except Exception: logging.getLogger('SiteError').exception( str(request.URL), ) except Exception: # Problem rendering the view for this exception. # Log an error. tryToLogException( 'Exception while rendering view on exception') # Record the error with the ErrorReportingUtility self._logErrorWithErrorReportingUtility( object, request, sys.exc_info()) view = None if view is None: # Either the view was not found, or view was set to None # because the view couldn't be rendered. In either case, # we let the request handle it. response.handleException(exc_info) transaction.abort() # See if there's an IExceptionSideEffects adapter for the # exception try: adapter = IExceptionSideEffects(exception, None) except Exception: tryToLogException( 'Exception while getting IExceptionSideEffects adapter') adapter = None if adapter is not None: self.beginErrorHandlingTransaction( request, object, 'application error-handling side-effect') try: # Although request is passed in here, it should be # considered read-only. adapter(object, request, exc_info) transaction.commit() except Exception: tryToLogException( 'Exception while calling' ' IExceptionSideEffects adapter') transaction.abort() def beginErrorHandlingTransaction(self, request, ob, note): txn = transaction.begin() txn.note(note) self.annotateTransaction(txn, request, ob) return txn def tryToLogException(arg1, arg2=None): if arg2 is None: subsystem = 'SiteError' message = arg1 else: subsystem = arg1 message = arg2 try: logging.getLogger(subsystem).exception(message) # Bare except, because we want to swallow any exception raised while # logging an exception. except Exception: pass def tryToLogWarning(arg1, arg2=None, exc_info=False): if arg2 is None: subsystem = 'SiteError' message = arg1 else: subsystem = arg1 message = arg2 try: logging.getLogger(subsystem).warning(message, exc_info=exc_info) # Bare except, because we want to swallow any exception raised while # logging a warning. except Exception: pass
zope.app.publication
/zope.app.publication-5.0.tar.gz/zope.app.publication-5.0/src/zope/app/publication/zopepublication.py
zopepublication.py
from zope.publisher.interfaces.ftp import IFTPPublisher from zope.publisher.interfaces.ftp import IFTPView class IFTPDirectoryPublisher(IFTPPublisher, IFTPView): def type(name): """Return the file type at the given name The return valie is 'd', for a directory, 'f', for a file, and None if there is no file at the path. """ def names(filter=None): """Return a sequence of the names in a directory If the filter is not None, include only those names for which the filter returns a true value. """ def ls(filter=None): """Return a sequence of information objects Return item info objects (see lsinfo) for the files in a directory. If the filter is not None, include only those names for which the filter returns a true value. """ def readfile(name, outstream, start=0, end=None): """Outputs the file at name to a stream. Data are copied starting from start. If end is not None, data are copied up to end. """ def lsinfo(name): """Return information for a unix-style ls listing for the path Data are returned as a dictionary containing the following keys: type The path type, either 'd' or 'f'. owner_name Defaults to "na". Must not include spaces. owner_readable defaults to True owner_writable defaults to True owner_executable defaults to True for directories and false otherwise. group_name Defaults to "na". Must not include spaces. group_readable defaults to True group_writable defaults to True group_executable defaults to True for directories and false otherwise. other_readable defaults to False other_writable defaults to False other_executable defaults to True for directories and false otherwise. mtime Optional time, as a datetime. nlinks The number of links. Defaults to 1. size The file size. Defaults to 0. name The file name. """ def mtime(name): """Return the modification time for the file Return None if it is unknown. """ def size(name): """Return the size of the file at path """ def mkdir(name): """Create a directory. """ def remove(name): """Remove a file. Same as unlink. """ def rmdir(name): """Remove a directory. """ def rename(old, new): """Rename a file or directory. """ def writefile(name, instream, start=None, end=None, append=False): """Write data to a file. If start or end is not None, then only part of the file is written. The remainder of the file is unchanged. If start or end are specified, they must ne non-negative. If end is None, then the file is truncated after the data are written. If end is not None, parts of the file after end, if any, are unchanged. If end is not None and there isn't enough data in instream to fill out the file, then the missing data are undefined. If neither start nor end are specified, then the file contents are overwritten. If start is specified and the file doesn't exist or is shorter than start, the file will contain undefined data before start. If append is true, start and end are ignored. """ def writable(name): """Return boolean indicating whether a file at path is writable Note that a true value should be returned if the file doesn't exist but it's directory is writable. """
zope.app.publisher
/zope.app.publisher-5.0-py3-none-any.whl/zope/app/publisher/interfaces/ftp.py
ftp.py
XML-RPC views ============= .. Let's first establish that our management views are around so we know that we're running in the right context: >>> from zope.app.publisher.testing import AppPublisherLayer >>> wsgi_app = AppPublisherLayer.make_wsgi_app() >>> print(http(wsgi_app, r""" ... GET /++etc++site/@@SelectedManagementView.html HTTP/1.0 ... Authorization: Basic bWdyOm1ncnB3 ... """)) HTTP/1.0 302 Moved Temporarily Content-Length: 0 Content-Type: text/plain;charset=utf-8 Location: @@registration.html >>> print(http(wsgi_app, r""" ... GET /@@SelectedManagementView.html HTTP/1.0 ... Authorization: Basic bWdyOm1ncnB3 ... """)) HTTP/1.0 302 Moved Temporarily Content-Length: 0 Content-Type: text/plain;charset=utf-8 Location: . >>> print(http(wsgi_app, r""" ... GET /++etc++site/manage HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... ... """, handle_errors=False)) Traceback (most recent call last): zope.security.interfaces.Unauthorized: ... XML-RPC Methods --------------- There are two ways to write XML-RPC views. You can write views that provide "methods" for other objects, and you can write views that have their own methods. Let's look at the former case first, since it's a little bit simpler. Let's write a view that returns a folder listing: >>> class FolderListing: ... def contents(self): ... return list(self.context.keys()) Now we'll register it as a view: >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... <include package="zope.security" /> ... <xmlrpc:view ... for="zope.site.interfaces.IFolder" ... methods="contents" ... class="zope.app.publisher.xmlrpc.README.FolderListing" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Now, we'll add some items to the root folder: >>> print(http(wsgi_app, r""" ... POST /@@contents.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 73 ... Content-Type: application/x-www-form-urlencoded ... ... type_name=BrowserAdd__zope.site.folder.Folder&new_value=f1""")) HTTP/1.1 303 See Other ... >>> print(http(wsgi_app, r""" ... POST /@@contents.html HTTP/1.1 ... Authorization: Basic bWdyOm1ncnB3 ... Content-Length: 73 ... Content-Type: application/x-www-form-urlencoded ... ... type_name=BrowserAdd__zope.site.folder.Folder&new_value=f2""")) HTTP/1.1 303 See Other ... And call our xmlrpc method: >>> from zope.app.publisher.xmlrpc.testing import ServerProxy >>> proxy = ServerProxy(wsgi_app, "http://mgr:mgrpw@localhost/") >>> proxy.contents() ['f1', 'f2'] Note that we get an unauthorized error if we don't supply authentication credentials: >>> proxy = ServerProxy( ... wsgi_app, "http://localhost/", handleErrors=False) >>> proxy.contents() Traceback (most recent call last): ... zope.security.interfaces.Unauthorized: ... `ServerProxy` sets an appropriate `Host` header, so applications that serve multiple virtual hosts can tell the difference: >>> class Headers: ... def host(self): ... return self.request.headers.get("Host") >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... <include package="zope.security" file="meta.zcml" /> ... ... <class class="zope.app.publisher.xmlrpc.README.Headers"> ... <allow attributes="host" /> ... </class> ... ... <xmlrpc:view ... name="headers" ... for="zope.site.interfaces.IFolder" ... methods="host" ... class="zope.app.publisher.xmlrpc.README.Headers" ... /> ... </configure> ... """) >>> proxy = ServerProxy(wsgi_app, "http://mgr:[email protected]:81/headers") >>> print(proxy.host()) nonsense.test:81 Named XML-RPC Views ------------------- Now let's look at views that have their own methods or other subobjects. Views that have their own methods have names that appear in URLs and they get traversed to get to their methods, as in:: .../somefolder/listing/contents To make this possible, the view has to support traversal, so that, when it is traversed, it traverses to its attributes. To support traversal, you can implement or provide an adapter to `zope.publisher.interfaces.IPublishTraverse`. It's actually better to provide an adapter so that accesses to attributes during traversal are mediated by the security machinery. (Object methods are always bound to unproxied objects, but adapters are bound to proxied objects unless they are trusted adapters.) The 'zope.app.publisher.xmlrpc' package provides a base class, `MethodPublisher`, that provides the necessary traversal support. In particulat, it has an adapter that simply traverses to attributes. If an XML-RPC view isn't going to be public, then it also has to implement 'zope.location.ILocation' so that security grants can be acquired for it, at least with Zope's default security policy. The `MethodPublisher` class does that too. Let's modify our view class to use `MethodPublisher`: >>> from zope.app.publisher.xmlrpc import MethodPublisher >>> class FolderListing(MethodPublisher): ... ... def contents(self): ... return list(self.context.keys()) Note that `MethodPublisher` also provides a suitable `__init__` method, so we don't need one any more. This time, we'll register it as as a named view: >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... name="listing" ... for="zope.site.folder.IFolder" ... methods="contents" ... class="zope.app.publisher.xmlrpc.README.FolderListing" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Now, when we access the `contents`, we do so through the listing view: >>> proxy = ServerProxy( ... wsgi_app, "http://mgr:mgrpw@localhost/listing/") >>> proxy.contents() ['f1', 'f2'] >>> proxy = ServerProxy(wsgi_app, "http://mgr:mgrpw@localhost/") >>> proxy.listing.contents() ['f1', 'f2'] as before, we will get an error if we don't supply credentials: >>> proxy = ServerProxy( ... wsgi_app, "http://localhost/listing/", handleErrors=False) >>> proxy.contents() Traceback (most recent call last): ... zope.security.interfaces.Unauthorized: ... Parameters ---------- Of course, XML-RPC views can take parameters, too: >>> class ParameterDemo: ... def __init__(self, context, request): ... self.context = context ... self.request = request ... ... def add(self, first, second): ... return first + second Now we'll register it as a view: >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... for="zope.site.interfaces.IFolder" ... methods="add" ... class="zope.app.publisher.xmlrpc.README.ParameterDemo" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Then we can issue a remote procedure call with a parameter and get back, surprise!, the sum: >>> proxy = ServerProxy(wsgi_app, "http://mgr:mgrpw@localhost/") >>> proxy.add(20, 22) 42 Faults ------ If you need to raise an error, the preferred way to do it is via an `xmlrpc.client.Fault`: >>> import xmlrpc.client >>> class FaultDemo: ... def __init__(self, context, request): ... self.context = context ... self.request = request ... ... def your_fault(self): ... return xmlrpc.client.Fault(42, u"It's your fault \N{SNOWMAN}!") Now we'll register it as a view: >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... for="zope.site.interfaces.IFolder" ... methods="your_fault" ... class="zope.app.publisher.xmlrpc.README.FaultDemo" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Now, when we call it, we get a proper XML-RPC fault: >>> from xmlrpc.client import Fault >>> proxy = ServerProxy(wsgi_app, "http://mgr:mgrpw@localhost/") >>> proxy.your_fault() Traceback (most recent call last): xmlrpc.client.Fault: <Fault 42: "It's your fault ☃!"> DateTime values --------------- Unfortunately, `xmlrpc.client` does not support Python's `datetime.datetime` class (it should be made to, really). DateTime values need to be encoded as `xmlrpc.client.DateTime` instances: >>> class DateTimeDemo: ... def __init__(self, context, request): ... self.context = context ... self.request = request ... ... def epoch(self): ... return xmlrpc.client.DateTime("19700101T01:00:01") Now we'll register it as a view: >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... for="zope.site.interfaces.IFolder" ... methods="epoch" ... class="zope.app.publisher.xmlrpc.README.DateTimeDemo" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Now, when we call it, we get a DateTime value >>> proxy = ServerProxy(wsgi_app, "http://mgr:mgrpw@localhost/") >>> proxy.epoch() <DateTime u'19700101T01:00:01' at ...> Protecting XML/RPC views with class-based permissions ----------------------------------------------------- When setting up an XML/RPC view with no permission, the permission check is deferred to the class that provides the view's implementation: >>> class ProtectedView(object): ... def public(self): ... return u'foo' ... def protected(self): ... return u'bar' >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... <include package="zope.security" file="meta.zcml" /> ... ... <class class="zope.app.publisher.xmlrpc.README.ProtectedView"> ... <require permission="zope.ManageContent" ... attributes="protected" /> ... <allow attributes="public" /> ... </class> ... ... <xmlrpc:view ... name="index" ... for="zope.site.interfaces.IFolder" ... methods="public protected" ... class="zope.app.publisher.xmlrpc.README.ProtectedView" ... /> ... </configure> ... """) An unauthenticated user can access the public method, but not the protected one: >>> proxy = ServerProxy( ... wsgi_app, "http://usr:usrpw@localhost/index", handleErrors=False) >>> proxy.public() 'foo' >>> proxy.protected() # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): zope.security.interfaces.Unauthorized: (<zope.app.publisher.xmlrpc.metaconfigure.ProtectedView object at 0x...>, 'protected', 'zope.ManageContent') As a manager, we can access both: >>> proxy = ServerProxy(wsgi_app, "http://mgr:mgrpw@localhost/index") >>> proxy.public() 'foo' >>> proxy.protected() 'bar' Handling errors with the ServerProxy ------------------------------------ Normal exceptions +++++++++++++++++ Our server proxy for functional testing also supports getting the original errors from Zope by not handling the errors in the publisher: >>> class ExceptionDemo: ... def __init__(self, context, request): ... self.context = context ... self.request = request ... ... def your_exception(self): ... raise Exception("Something went wrong!") Now we'll register it as a view: >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... ... <xmlrpc:view ... for="zope.site.interfaces.IFolder" ... methods="your_exception" ... class="zope.app.publisher.xmlrpc.README.ExceptionDemo" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Now, when we call it, we get an XML-RPC fault: >>> proxy = ServerProxy(wsgi_app, "http://mgr:mgrpw@localhost/") >>> proxy.your_exception() Traceback (most recent call last): xmlrpc.client.Fault: <Fault -1: 'Unexpected Zope exception: Exception: Something went wrong!'> We can also give the parameter `handleErrors` to have the errors not be handled: >>> proxy = ServerProxy( ... wsgi_app, "http://mgr:mgrpw@localhost/", handleErrors=False) >>> proxy.your_exception() Traceback (most recent call last): Exception: Something went wrong! Custom exception handlers +++++++++++++++++++++++++ Custom exception handlers might lead to status codes != 200. They are handled as ProtocolError: >>> import zope.security.interfaces >>> class ExceptionHandlingDemo: ... def __init__(self, context, request): ... self.context = context ... self.request = request ... ... def your_runtimeerror(self): ... raise RuntimeError('BadLuck!') >>> class ExceptionHandlingDemoHandler: ... def __init__(self, context, request): ... self.context = context ... self.request = request ... ... def __call__(self): ... self.request.unauthorized('basic realm="Zope"') ... return '' Now we'll register it as a view: >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:browser="http://namespaces.zope.org/browser" ... xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc" ... > ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... <include package="zope.component" file="meta.zcml" /> ... <include package="zope.app.publisher.xmlrpc" file="meta.zcml" /> ... <include package="zope.app.publisher.browser" file="meta.zcml" /> ... ... <view ... for="RuntimeError" ... type="zope.publisher.interfaces.http.IHTTPRequest" ... name="index.html" ... permission="zope.Public" ... factory="zope.app.publisher.xmlrpc.README.ExceptionHandlingDemoHandler" ... /> ... ... <browser:defaultView ... for="RuntimeError" ... layer="zope.publisher.interfaces.http.IHTTPRequest" ... name="index.html" ... /> ... ... <xmlrpc:view ... for="zope.site.interfaces.IFolder" ... methods="your_runtimeerror" ... class="zope.app.publisher.xmlrpc.README.ExceptionHandlingDemo" ... permission="zope.ManageContent" ... /> ... </configure> ... """) Now, when we call it, we get an XML-RPC ProtocolError: >>> proxy = ServerProxy(wsgi_app, "http://mgr:mgrpw@localhost/") >>> proxy.your_runtimeerror() Traceback (most recent call last): xmlrpc.client.ProtocolError: <ProtocolError for localhost/: 401 401 Unauthorized> We can also give the parameter `handleErrors` to have the errors not be handled: >>> proxy = ServerProxy( ... wsgi_app, "http://mgr:mgrpw@localhost/", handleErrors=False) >>> proxy.your_runtimeerror() Traceback (most recent call last): RuntimeError: BadLuck!
zope.app.publisher
/zope.app.publisher-5.0-py3-none-any.whl/zope/app/publisher/xmlrpc/README.rst
README.rst
import zope.configuration.fields import zope.interface import zope.schema import zope.security.zcml class IViewDirective(zope.interface.Interface): """View Directive for XML-RPC methods.""" for_ = zope.configuration.fields.GlobalObject( title="Published Object Type", description="""The types of objects to be published via XML-RPC This can be expressed with either a class or an interface """, required=True, ) interface = zope.configuration.fields.Tokens( title="Interface to be published.", required=False, value_type=zope.configuration.fields.GlobalInterface() ) methods = zope.configuration.fields.Tokens( title="Methods (or attributes) to be published", required=False, value_type=zope.configuration.fields.PythonIdentifier() ) class_ = zope.configuration.fields.GlobalObject( title="Class", description="A class that provides attributes used by the view.", required=False ) permission = zope.security.zcml.Permission( title="Permission", description="""The permission needed to use the view. If this option is used and a name is given for the view, then the names defined by the given methods or interfaces will be under the given permission. If a name is not given for the view, then, this option is required and the given permission is required to call the individual views defined by the given interface and methods. (See the name attribute.) If no permission is given, then permissions should be declared for the view using other means, such as the class directive. """, required=False) name = zope.schema.TextLine( title="The name of the view.", description=""" If a name is given, then rpc methods are accessed by traversing the name and then accessing the methods. In this case, the class should implement zope.pubisher.interfaces.IPublishTraverse. If no name is provided, then the names given by the attributes and interfaces are published directly as callable views. """, required=False, )
zope.app.publisher
/zope.app.publisher-5.0-py3-none-any.whl/zope/app/publisher/xmlrpc/metadirectives.py
metadirectives.py
"""XMLRPC configuration code""" from zope.component.interface import provideInterface from zope.component.zcml import handler from zope.configuration.exceptions import ConfigurationError from zope.interface import Interface from zope.publisher.interfaces.xmlrpc import IXMLRPCRequest from zope.security.checker import Checker from zope.security.checker import CheckerPublic from zope.security.checker import getCheckerForInstancesOf from zope.app.publisher.xmlrpc import MethodPublisher def view(_context, for_=None, interface=None, methods=None, class_=None, permission=None, name=None): interface = interface or [] methods = methods or [] # If there were special permission settings provided, then use them if permission == 'zope.Public': permission = CheckerPublic require = {} for attr_name in methods: require[attr_name] = permission if interface: for iface in interface: for field_name in iface: require[field_name] = permission _context.action( discriminator=None, callable=provideInterface, args=('', for_) ) # Make sure that the class inherits MethodPublisher, so that the views # have a location if class_ is None: class_ = original_class = MethodPublisher else: original_class = class_ class_ = type(class_.__name__, (class_, MethodPublisher), {}) if name: # Register a single view if permission: checker = Checker(require) def proxyView(context, request, class_=class_, checker=checker): view = class_(context, request) # We need this in case the resource gets unwrapped and # needs to be rewrapped view.__Security_checker__ = checker return view class_ = proxyView class_.factory = original_class else: # No permission was defined, so we defer to the checker # of the original class def proxyView(context, request, class_=class_): view = class_(context, request) view.__Security_checker__ = getCheckerForInstancesOf( original_class) return view class_ = proxyView class_.factory = original_class # Register the new view. _context.action( discriminator=('view', for_, name, IXMLRPCRequest), callable=handler, args=('registerAdapter', class_, (for_, IXMLRPCRequest), Interface, name, _context.info) ) else: if permission: checker = Checker({'__call__': permission}) else: raise ConfigurationError( "XML/RPC view has neither a name nor a permission. " "You have to specify at least one of the two.") for name in require: # create a new callable class with a security checker; cdict = {'__Security_checker__': checker, '__call__': getattr(class_, name)} new_class = type(class_.__name__, (class_,), cdict) _context.action( discriminator=('view', for_, name, IXMLRPCRequest), callable=handler, args=('registerAdapter', new_class, (for_, IXMLRPCRequest), Interface, name, _context.info) ) # Register the used interfaces with the site manager if for_ is not None: _context.action( discriminator=None, callable=provideInterface, args=('', for_) )
zope.app.publisher
/zope.app.publisher-5.0-py3-none-any.whl/zope/app/publisher/xmlrpc/metaconfigure.py
metaconfigure.py
=========== Python Page =========== Python Page provides the user with a content object that interprets Python in content space. To save typing and useless messing with output, any free-standing string and print statement are considered for output; see the example below. Example ------- Create a new content type called "Python Page" and enter the following code example:: ''' <html> <body> <ul> ''' import time print time.asctime() ''' </ul> </body> </html> '''
zope.app.pythonpage
/zope.app.pythonpage-3.5.1.tar.gz/zope.app.pythonpage-3.5.1/src/zope/app/pythonpage/README.txt
README.txt
__docformat__ = 'restructuredtext' import re from persistent import Persistent import zope.component from zope.container.contained import Contained from zope.app.interpreter.interfaces import IInterpreter from zope.interface import Interface, implements from zope.schema import SourceText, TextLine from zope.i18nmessageid import ZopeMessageFactory as _ from zope.security.untrustedpython.interpreter import CompiledProgram from zope.traversing.api import getPath, getParent class IPythonPage(Interface): """Python Page The Python Page acts as a simple content type that allows you to execute Python in content space. Additionally, if you have a free-standing triple-quoted string, it gets converted to a print statement automatically. """ source = SourceText( title=_("Source"), description=_("The source of the Python page."), required=True) contentType = TextLine( title=_("Content Type"), description=_("The content type the script outputs."), required=True, default=u"text/html") def __call__(request, **kw): """Execute the script. The script will insert the `request` and all `**kw` as global variables. Furthermore, the variables `script` and `context` (which is the container of the script) will be added. """ class PythonPage(Contained, Persistent): r"""Persistent Python Page - Content Type Examples: >>> from tests import Root >>> pp = PythonPage() >>> pp.__parent__ = Root() >>> pp.__name__ = 'pp' >>> request = None Test that can produce the correct filename >>> pp._PythonPage__filename() u'/pp' A simple test that checks that any lone-standing triple-quotes are being printed. >>> pp.setSource(u"'''<html>...</html>'''") >>> pp(request) u'<html>...</html>\n' Make sure that strings with prefixes work. >>> pp.setSource(ur"ur'''test\r'''") >>> pp(request) u'test\\r\n' Make sure that Windows (\r\n) line ends also work. >>> pp.setSource(u"if 1 == 1:\r\n\r\n '''<html>...</html>'''") >>> pp(request) u'<html>...</html>\n' Make sure that unicode strings work as expected. >>> pp.setSource(u"u'''\u0442\u0435\u0441\u0442'''") >>> pp(request) u'\u0442\u0435\u0441\u0442\n' Make sure that multi-line strings work. >>> pp.setSource(u"u'''test\ntest\ntest'''") >>> pp(request) u'test\ntest\ntest\n' Here you can see a simple Python command... >>> pp.setSource(u"print u'<html>...</html>'") >>> pp(request) u'<html>...</html>\n' ... and here a triple quote with some variable replacement. >>> pp.setSource(u"'''<html>%s</html>''' %x") >>> pp(request, x='test') u'<html>test</html>\n' Make sure that the context of the page is available. >>> pp.setSource(u"'''<html>%s</html>''' %context.__name__") >>> pp(request) u'<html>root</html>\n' Make sure that faulty syntax is interpreted correctly. # Note: We cannot just print the error directly, since there is a # 'bug' in the Linux version of Python that does not display the filename # of the source correctly. So we construct an information string by hand. >>> def print_err(err): ... err.__dict__['msg'] = err.msg ... err.__dict__['filename'] = err.filename ... err.__dict__['lineno'] = err.lineno ... err.__dict__['offset'] = err.offset ... print ('%(msg)s, %(filename)s, line %(lineno)i, offset %(offset)i' ... % err.__dict__) ... >>> try: ... pp.setSource(u"'''<html>..</html>") #'''" ... except SyntaxError, err: ... print_err(err) ... # doctest: +ELLIPSIS EOF while scanning triple-quoted string... /pp, line 1, offset ... >>> try: ... pp.setSource(u"prin 'hello'") ... except SyntaxError, err: ... print_err(err) invalid syntax, /pp, line 1, offset 12 """ implements(IPythonPage) def __init__(self, source=u'', contentType=u'text/html'): """Initialize the object.""" super(PythonPage, self).__init__() self.source = source self.contentType = contentType def __filename(self): if self.__parent__ is None: filename = 'N/A' else: filename = getPath(self) return filename def setSource(self, source): r"""Set the source of the page and compile it. This method can raise a syntax error, if the source is not valid. """ self.__source = source # Make sure the code and the source are synchronized if hasattr(self, '_v_compiled'): del self._v_compiled self.__prepared_source = self.prepareSource(source) # Compile objects cannot be pickled self._v_compiled = CompiledProgram(self.__prepared_source, self.__filename()) _tripleQuotedString = re.compile( r"^([ \t]*)[uU]?([rR]?)(('''|\"\"\")(.*)\4)", re.MULTILINE | re.DOTALL) def prepareSource(self, source): """Prepare source.""" # compile() don't accept '\r' altogether source = source.replace("\r\n", "\n") source = source.replace("\r", "\n") if isinstance(source, unicode): # Use special conversion function to work around # compiler-module failure to handle unicode in literals try: source = source.encode('ascii') except UnicodeEncodeError: return self._tripleQuotedString.sub(_print_usrc, source) return self._tripleQuotedString.sub(r"\1print u\2\3", source) def getSource(self): """Get the original source code.""" return self.__source # See IPythonPage source = property(getSource, setSource) def __call__(self, request, **kw): """See IPythonPage""" # Compile objects cannot be pickled if not hasattr(self, '_v_compiled'): self._v_compiled = CompiledProgram(self.__prepared_source, self.__filename()) kw['request'] = request kw['script'] = self kw['context'] = getParent(self) interpreter = zope.component.queryUtility(IInterpreter, 'text/server-python') return interpreter.evaluate(self._v_compiled, kw) def _print_usrc(match): string = match.group(3) raw = match.group(2) if raw: return match.group(1)+'print '+`string` return match.group(1)+'print u'+match.group(3).encode('unicode-escape')
zope.app.pythonpage
/zope.app.pythonpage-3.5.1.tar.gz/zope.app.pythonpage-3.5.1/src/zope/app/pythonpage/__init__.py
__init__.py
========= CHANGES ========= 5.0 (2023-02-08) ================ - Drop support for Python 2.7, 3.4, 3.5, 3.6. - Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11. 4.1.0 (2017-05-25) ================== - Raise the docutils ReST error report level from its default of ``error`` to ``severe``. An error-level report is issued for directives that are unknown, such as ``:class:``, which are increasingly common due to the use of Sphinx. This change prevents such an error being printed on stderr as well as rendered in the HTML. 4.0.0 (2017-05-17) ================== - Add support for Python 3.4, 3.5, 3.6 and PyPy. - Remove dependency on ``zope.app.testing``. - Use the standard library ``doctest`` module. 3.5.1 (2009-07-21) ================== - Require the new ``roman`` package, since docutils does not install it correctly. 3.5.0 (2009-01-17) ================== - Adapted to docutils 0.5 for ReST rendering: get rid of the ZopeTranslator class, because docutils changed the way it uses translator so previous implementation doesn't work anymore. Instead, use publish_parts and join needed parts in the ``render`` method of the renderer itself. - Removed deprecated meta.zcml stuff and zpkg stuff. - Replaced __used_for__ with zope.component.adapts calls. 3.4.0 (2007-10-27) ================== - Initial release independent of the main Zope tree.
zope.app.renderer
/zope.app.renderer-5.0.tar.gz/zope.app.renderer-5.0/CHANGES.rst
CHANGES.rst
__docformat__ = 'restructuredtext' import re from zope.component import adapter from zope.interface import implementer from zope.publisher.browser import BrowserView from zope.publisher.interfaces.browser import IBrowserRequest from zope.structuredtext.document import Document from zope.structuredtext.html import HTML from zope.app.renderer import SourceFactory from zope.app.renderer.i18n import ZopeMessageFactory as _ from zope.app.renderer.interfaces import IHTMLRenderer from zope.app.renderer.interfaces import ISource class IStructuredTextSource(ISource): """Marker interface for a structured text source. Note that an implementation of this interface should always derive from unicode or behave like a unicode class.""" StructuredTextSourceFactory = SourceFactory( IStructuredTextSource, _("Structured Text (STX)"), _("Structured Text (STX) Source")) @implementer(IHTMLRenderer) @adapter(IStructuredTextSource, IBrowserRequest) class StructuredTextToHTMLRenderer(BrowserView): r"""A view to convert from Plain Text to HTML. Example:: >>> from zope.app.renderer import text_type >>> from zope.publisher.browser import TestRequest >>> source = StructuredTextSourceFactory(u'This is source.') >>> renderer = StructuredTextToHTMLRenderer(source, TestRequest()) >>> rendered = renderer.render() >>> isinstance(rendered, text_type) True >>> print(rendered) <p>This is source.</p> <BLANKLINE> Make sure that unicode works as well:: >>> source = StructuredTextSourceFactory(u'This is \xc3\x9c.') >>> renderer = StructuredTextToHTMLRenderer(source, TestRequest()) >>> rendered = renderer.render() >>> isinstance(rendered, text_type) True >>> print(rendered) <p>This is ...</p> <BLANKLINE> """ def render(self): "See zope.app.interfaces.renderer.IHTMLRenderer" doc = Document()(self.context) html = HTML()(doc) # strip html & body added by some zope versions html = re.sub( r'(?sm)^<html.*<body.*?>\n(.*)</body>\n</html>\n', r'\1', html) return html
zope.app.renderer
/zope.app.renderer-5.0.tar.gz/zope.app.renderer-5.0/src/zope/app/renderer/stx.py
stx.py
__docformat__ = 'restructuredtext' import docutils.core from zope.component import adapter from zope.interface import implementer from zope.publisher.browser import BrowserView from zope.publisher.interfaces.browser import IBrowserRequest from zope.app.renderer import SourceFactory from zope.app.renderer.i18n import ZopeMessageFactory as _ from zope.app.renderer.interfaces import IHTMLRenderer from zope.app.renderer.interfaces import ISource class IReStructuredTextSource(ISource): """Marker interface for a restructured text source. Note that an implementation of this interface should always derive from unicode or behave like a unicode class.""" ReStructuredTextSourceFactory = SourceFactory( IReStructuredTextSource, _("ReStructured Text (ReST)"), _("ReStructured Text (ReST) Source")) @implementer(IHTMLRenderer) @adapter(IReStructuredTextSource, IBrowserRequest) class ReStructuredTextToHTMLRenderer(BrowserView): r"""An Adapter to convert from Restructured Text to HTML. Examples:: >>> from zope.app.renderer import text_type >>> from zope.publisher.browser import TestRequest >>> source = ReStructuredTextSourceFactory(u''' ... This is source. ... ... Header 3 ... -------- ... This is more source. ... ''') >>> renderer = ReStructuredTextToHTMLRenderer(source, TestRequest()) >>> rendered = renderer.render() >>> isinstance(rendered, text_type) True >>> print(rendered.strip()) <p>This is source.</p> <div class="section" id="header-3"> <h3>Header 3</h3> <p>This is more source.</p> </div> """ def render(self, settings_overrides=()): """See zope.app.interfaces.renderer.IHTMLRenderer Let's make sure that inputted unicode stays as unicode: >>> from zope.app.renderer import text_type >>> renderer = ReStructuredTextToHTMLRenderer(u'b\xc3h', None) >>> isinstance(renderer.render(), text_type) True >>> text = u''' ... ========= ... Heading 1 ... ========= ... ... hello world ... ... Heading 2 ... =========''' >>> overrides = {'initial_header_level': 2, ... 'doctitle_xform': 0 } >>> renderer = ReStructuredTextToHTMLRenderer(text, None) >>> print(renderer.render(overrides)) <div class="section" id="heading-1"> <h2>Heading 1</h2> <p>hello world</p> <div class="section" id="heading-2"> <h3>Heading 2</h3> </div> </div> <BLANKLINE> """ # default settings for the renderer overrides = { 'halt_level': 6, # don't stop for any errors 'report_level': 4, # only report severe errors 'input_encoding': 'unicode', 'output_encoding': 'unicode', 'initial_header_level': 3, } overrides.update(settings_overrides) parts = docutils.core.publish_parts( self.context, writer_name='html', settings_overrides=overrides, ) return ''.join((parts['body_pre_docinfo'], parts['docinfo'], parts['body']))
zope.app.renderer
/zope.app.renderer-5.0.tar.gz/zope.app.renderer-5.0/src/zope/app/renderer/rest.py
rest.py
//---------------------------------------------------------------------------- // popup window with settings //---------------------------------------------------------------------------- function popup(page, name, settings) { win = window.open(page, name, settings); win.focus(); } //---------------------------------------------------------------------------- // guess browser version, feel free to enhance it if needed. //---------------------------------------------------------------------------- var ie = document.all != null; var moz = !ie && document.getElementById != null && document.layers == null; //---------------------------------------------------------------------------- // change the status (color) of the matrix table used in grant.html //---------------------------------------------------------------------------- function changeMatrix(e) { var ele = e? e: window.event; var id = ele.getAttribute('id'); var name = ele.getAttribute('name'); if (moz) { var label = ele.parentNode; var center = label.parentNode; var td = center.parentNode; } else { var label = ele.parentElement; var center = label.parentElement; var td = center.parentElement; } resetMatrixCSS(name); if (td.className != "default") { td.className = "changed"; } } function resetMatrixCSS(name) { var inputFields = document.getElementsByTagName('input'); for (var i = 0; i < inputFields.length; i++) { var field = inputFields[i]; if (field.getAttribute('name') == name) { if (moz) { td = field.parentNode.parentNode.parentNode; } else { td = field.parentElement.parentElement.parentElement; } if (td.className != "default") { td.className = ""; } } } } //---------------------------------------------------------------------------- // toggle the status of all checkboxes that have class == "className" //---------------------------------------------------------------------------- function updateCheckboxes(master, className) { newState = master.checked; objects = document.getElementsByTagName("input") count = objects.length; for(x = 0; x < count; x++) { obj = objects[x]; if (obj.type == "checkbox") { var classes = obj.className.split(" "); for (var i = 0; i < classes.length; i++) if (classes[i] == className) { obj.checked = newState; break; } } } }
zope.app.rotterdam
/zope.app.rotterdam-5.0-py3-none-any.whl/zope/app/rotterdam/zope3.js
zope3.js
import time from email.utils import formatdate from xml.sax.saxutils import quoteattr from zope.component import getMultiAdapter from zope.component import queryMultiAdapter from zope.container.interfaces import IReadContainer from zope.i18n import translate from zope.interface import Interface from zope.proxy import sameProxiedObjects from zope.publisher.browser import BrowserView from zope.security.interfaces import Forbidden from zope.security.interfaces import Unauthorized from zope.traversing.api import getParent from zope.traversing.api import getParents from zope.traversing.api import traverse from zope.app.rotterdam.i18n import ZopeMessageFactory as _ titleTemplate = _('Contains $${num} item(s)') loadingMsg = _('Loading...') def setNoCacheHeaders(response): """Ensure that the tree isn't cached""" response.setHeader('Pragma', 'no-cache') response.setHeader('Cache-Control', 'no-cache') response.setHeader('Expires', formatdate(time.time() - 7 * 86400)) # 7 days ago try: text_type = unicode except NameError: text_type = str def _quoteattr_text(obj): if isinstance(obj, bytes): obj = obj.decode('utf-8') if not isinstance(obj, text_type): obj = text_type(obj) return quoteattr(obj) def xmlEscape(format, *args): quotedArgs = [_quoteattr_text(arg) for arg in args] return format % tuple(quotedArgs) def xmlEscapeWithCData(format, *args): cData = args[-1] quotedArgs = [_quoteattr_text(arg) for arg in args[:-1]] quotedArgsWithCData = quotedArgs + [cData] return format % tuple(quotedArgsWithCData) def getParentsFromContextToObject(context, obj): """Returns a list starting with the given context's parent followed by each of its parents till we reach the object. """ if sameProxiedObjects(context, obj): return [] parents = [] w = context while 1: w = w.__parent__ if sameProxiedObjects(w, obj): parents.append(w) break if w is None: # pragma: no cover break parents.append(w) return parents class ReadContainerXmlObjectView(BrowserView): """Provide a xml interface for dynamic navigation tree in UI""" __used_for__ = IReadContainer def getIconUrl(self, item): icon = queryMultiAdapter((item, self.request), name='zmi_icon') return icon.url() if icon else '' def getLengthOf(self, item): res = -1 if IReadContainer.providedBy(item): try: res = len(item) except (Unauthorized, Forbidden): # pragma: no cover pass return res def children_utility(self, container): """Return an XML document that contains the children of an object.""" result = [] keys = list(container.keys()) # include the site manager keys.append('++etc++site') # dont get children if we get more than 1000 objects if len(keys) >= 1000: keys = ['++etc++site'] for name in keys: # Only include items we can traverse to item = traverse(container, name, None) if item is None: continue iconUrl = self.getIconUrl(item) item_len = self.getLengthOf(item) if item_len >= 0: result.append(xmlEscape( '<collection name=%s length=%s icon_url=%s/>', name, item_len, iconUrl)) else: result.append(xmlEscape( '<item name=%s icon_url=%s/>', name, iconUrl)) return ' '.join(result) def children(self): """ Get children """ container = self.context self.request.response.setHeader('Content-Type', 'text/xml') setNoCacheHeaders(self.request.response) res = ('<?xml version="1.0" ?><children> %s </children>' % self.children_utility(container)) return res def singleBranchTree(self, root=''): """Return an XML document with the siblings and parents of an object. There is only one branch expanded, in other words, the tree is filled with the object, its siblings and its parents with their respective siblings. """ result = 'selected' oldItem = self.context vh = self.request.getVirtualHostRoot() if vh: vhrootView = getMultiAdapter( (vh, self.request), name='absolute_url') baseURL = vhrootView() + '/' try: rootName = '[' + vh.__name__ + ']' except: # noqa: E722 do not use bare 'except' pragma: no cover # we got the containment root itself as the virtual host # and there is no name. rootName = _('[top]') parents = getParentsFromContextToObject(self.context, vh) else: rootName = _('[top]') baseURL = self.request.getApplicationURL() + '/' parents = getParents(self.context) rootName = translate(rootName, context=self.request, default=rootName) for item in parents: # skip skin if present # if item == oldItem: # continue subItems = [] keys = [] if IReadContainer.providedBy(item): keys = list(item.keys()) if len(keys) >= 1000: # pragma: no cover keys = [] # include the site manager keys.append('++etc++site') for name in keys: # Only include items we can traverse to subItem = traverse(item, name, None) iconUrl = self.getIconUrl(subItem) subitem_len = self.getLengthOf(subItem) if subitem_len >= 0: # the test below seems to be broken # with the ++etc++site case if subItem == oldItem: subItems.append(xmlEscapeWithCData( '<collection name=%s length=%s ' 'icon_url=%s>%s</collection>', name, subitem_len, iconUrl, result)) else: subItems.append(xmlEscape( '<collection name=%s length=%s ' 'icon_url=%s/>', name, subitem_len, iconUrl)) else: subItems.append(xmlEscape( '<item name=%s icon_url=%s />', name, iconUrl)) result = ' '.join(subItems) oldItem = item # do not forget root folder iconUrl = self.getIconUrl(oldItem) result = xmlEscapeWithCData( '<collection name=%s baseURL=%s length=%s ' 'icon_url=%s isroot="">%s</collection>', rootName, baseURL, len(oldItem), iconUrl, result) self.request.response.setHeader('Content-Type', 'text/xml') setNoCacheHeaders(self.request.response) title = translate(titleTemplate, context=self.request, default=titleTemplate) loading = translate(loadingMsg, context=self.request, default=loadingMsg) return xmlEscapeWithCData( '<?xml version="1.0" ?>' '<children title_tpl=%s loading_msg=%s>%s</children>', title, loading, result) class XmlObjectView(BrowserView): """Provide a xml interface for dynamic navigation tree in UI""" __used_for__ = Interface def singleBranchTree(self, root=''): parent = getParent(self.context) while parent is not None: if IReadContainer.providedBy(parent): view = queryMultiAdapter( (parent, self.request), name='singleBranchTree.xml') return view() parent = getParent(parent) # pragma: no cover
zope.app.rotterdam
/zope.app.rotterdam-5.0-py3-none-any.whl/zope/app/rotterdam/xmlobject.py
xmlobject.py
var ELEMENT_NODE = 1; var TEXT_NODE = 3; var COLLECTION = 'COLLECTION'; var ICON = 'ICON'; var EXPAND = 'EXPAND'; var XML_CHILDREN_VIEW = '@@children.xml'; var SINGLE_BRANCH_TREE_VIEW = '@@singleBranchTree.xml'; var CONTENT_VIEW = '@@SelectedManagementView.html'; var NUM_TEMPLATE = '$${num}'; var LG_DEBUG = 6; var LG_TRACE_EVENTS = 5; var LG_TRACE = 4; var LG_INFO = 3; var LG_NOLOG = 0; // globals var loadingMsg = 'Loading...'; var abortMsg = 'Unavailable'; var titleTemplate = 'Contains ' + NUM_TEMPLATE + ' item(s)'; var baseurl; var navigationTree; var docNavTree; var loglevel = LG_NOLOG; //class navigationTreeNode function navigationTreeNode (domNode) { this.childNodes = new Array(); this.isEmpty = 1; this.isCollapsed = 1; this.domNode = domNode; this.loadingNode = null; this.path = ''; this.parentNode = null; } navigationTreeNode.prototype.appendChild = function(node) { this.childNodes.push(node); this.domNode.appendChild(node.domNode); node.parentNode = this; } navigationTreeNode.prototype.setPath = function(path) { this.path = path; this.domNode.setAttribute("path", path); } navigationTreeNode.prototype.setSelected = function() { this.domNode.getElementsByTagName('icon')[0].className='selected'; } navigationTreeNode.prototype.collapse = function() { this.isCollapsed = 1; this.changeExpandIcon("pl.gif"); } navigationTreeNode.prototype.expand = function() { this.isCollapsed = 0; this.changeExpandIcon("mi.gif"); } navigationTreeNode.prototype.changeExpandIcon = function(icon) { var expand = this.domNode.getElementsByTagName('expand')[0]; expand.style.backgroundImage = 'url("' + baseurl + '@@/' + icon + '")'; } navigationTreeNode.prototype.getNodeByPath = function(path) { var numchildren = this.childNodes.length; if (path == this.path) return this; else { for (var i=0; i<numchildren; i++) { foundChild = this.childNodes[i].getNodeByPath(path); if (foundChild) return foundChild; } } return null; } navigationTreeNode.prototype.toggleExpansion = function() { with (this) { prettydump('toggleExpansion', LG_TRACE); // If this collection is empty, load it from server // todo xxx optimize for the case where collection has null length if (isEmpty) startLoadingChildren(); else refreshExpansion(); } } navigationTreeNode.prototype.startLoadingChildren = function() { with (this) { //already loading? if (loadingNode) return; loadingNode = createLoadingNode(); domNode.appendChild(loadingNode); //var url = baseurl + path + XML_CHILDREN_VIEW; var url = path + XML_CHILDREN_VIEW; loadtreexml(url, this); } } navigationTreeNode.prototype.finishLoadingChildren = function() { with (this) { isEmpty = 0; refreshExpansion(); domNode.removeChild(loadingNode); loadingNode = null; } } navigationTreeNode.prototype.abortLoadingChildren = function() { with (this) { domNode.removeChild(loadingNode); loadingNode = null; } } navigationTreeNode.prototype.refreshExpansion = function() { with (this) { if (isCollapsed) { expand(); showChildren(); } else { collapse(); hideChildren(); } } } navigationTreeNode.prototype.hideChildren = function() { with (this) { prettydump('hideChildren', LG_TRACE); var num = childNodes.length; for (var i=num-1; i>=0; i--) { childNodes[i].domNode.style.display = 'none'; } } } navigationTreeNode.prototype.showChildren = function() { with (this) { prettydump('showChildren', LG_TRACE); var num = childNodes.length; for (var i=num-1; i>=0; i--) { childNodes[i].domNode.style.display = 'block'; } } } // utilities function prettydump(s, locallog) { // Put the string "s" in a box on the screen as an log message if (locallog > loglevel) return; var logger = document.getElementById('logger'); var msg = document.createElement('code'); var br1 = document.createElement('br'); var br2 = document.createElement('br'); var msg_text = document.createTextNode(s); msg.appendChild(msg_text); logger.insertBefore(br1, logger.firstChild); logger.insertBefore(br2, logger.firstChild); logger.insertBefore(msg, logger.firstChild); } function debug(s) { var oldlevel = loglevel; loglevel = LG_DEBUG; prettydump("Debug : " + s, LG_DEBUG); loglevel = oldlevel; } // DOM utilities function getTreeEventTarget(e) { var elem; if (e.target) { // Mozilla uses this if (e.target.nodeType == TEXT_NODE) { elem=e.target.parentNode; } else elem=e.target; } else { // IE uses this elem=e.srcElement; } return elem; } function isCollection(elem) { return checkTagName(elem, COLLECTION); } function isIcon(elem) { return checkTagName(elem, ICON); } function isExpand(elem) { return checkTagName(elem, EXPAND); } function checkTagName(elem, tagName) { return elem.tagName.toUpperCase() == tagName; } function getCollectionChildNodes(xmlDomElem) { // get collection element nodes among childNodes of elem var result = new Array(); var items = xmlDomElem.childNodes; var numitems = items.length; var currentItem; for (var i=0; i<numitems; i++) { currentItem = items[i]; if (currentItem.nodeType == ELEMENT_NODE && isCollection(currentItem)) { result.push(currentItem); } } return result; } //events function treeclicked(e) { prettydump('treeclicked', LG_TRACE_EVENTS); var elem = getTreeEventTarget(e); if (elem.id == 'navtree') return; // if node clicked is expand elem, toggle expansion if (isExpand(elem) && !elem.getAttribute('disabled')) { //get collection node elem = elem.parentNode; var navTreeNode = navigationTree.getNodeByPath(elem.getAttribute('path')); navTreeNode.toggleExpansion(); } } // helpers function getControlPrefix() { if (getControlPrefix.prefix) return getControlPrefix.prefix; var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"]; var o, o2; for (var i=0; i<prefixes.length; i++) { try { // try to create the objects o = new ActiveXObject(prefixes[i] + ".XmlHttp"); o2 = new ActiveXObject(prefixes[i] + ".XmlDom"); return getControlPrefix.prefix = prefixes[i]; } catch (ex) {}; } throw new Error("Could not find an installed XML parser"); } // XmlHttp factory function XmlHttp() {} XmlHttp.create = function() { if (window.XMLHttpRequest) { var req = new XMLHttpRequest(); // some older versions of Moz did not support the readyState property // and the onreadystate event so we patch it! if (req.readyState == null) { req.readyState = 1; req.addEventListener("load", function() { req.readyState = 4; if (typeof req.onreadystatechange == "function") req.onreadystatechange();}, false); } return req; } if (window.ActiveXObject) { s = getControlPrefix() + '.XmlHttp'; return new ActiveXObject(getControlPrefix() + ".XmlHttp"); } return; }; function loadtreexml (url, node) { var xmlHttp = XmlHttp.create(); if (!xmlHttp) return; prettydump('URL ' + url, LG_INFO); xmlHttp.open('GET', url, true); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState != 4) return; prettydump('Response XML ' + xmlHttp.responseText, LG_INFO); parseXML(xmlHttp.responseXML, node); }; // call in new thread to allow ui to update window.setTimeout(function() { xmlHttp.send(null); }, 10); } function loadtree (rooturl, thisbaseurl) { baseurl = rooturl; // Global baseurl docNavTree = document.getElementById('navtreecontents'); var url = thisbaseurl + SINGLE_BRANCH_TREE_VIEW; loadtreexml(url, null); } function removeChildren(node) { var items = node.childNodes; var numitems = items.length; for (var i=0; i<numitems; i++) { node.removeChild(items[i]); } } function parseXML(responseXML, node) { if (responseXML) { var data = responseXML.documentElement; if (node == null) { //[top] node removeChildren(docNavTree); titleTemplate = data.getAttribute('title_tpl'); loadingMsg = data.getAttribute('loading_msg'); addNavigationTreeNodes(data, null, 1); // docNavTree.appendChild(navigationTree.domNode); } else { //expanding nodes addNavigationTreeNodes(data, node, 0); node.finishLoadingChildren(); } } else { // no XML response, reset the loadingNode if (node == null) { //unable to retrieve [top] node docNavTree.innerHTML = abortMsg; } else { //abort expanding nodes node.abortLoadingChildren() } } } function addNavigationTreeNodes(sourceNode, targetNavTreeNode, deep) { // create tree nodes from XML children nodes of sourceNode // and add them to targetNode // if deep, create all descendants of sourceNode var basePath = ""; if (targetNavTreeNode) basePath = targetNavTreeNode.path; var items = getCollectionChildNodes(sourceNode); var numitems = items.length; for (var i=0; i<numitems; i++) { var navTreeChild = createNavigationTreeNode(items[i], basePath, deep); if (targetNavTreeNode) targetNavTreeNode.appendChild(navTreeChild); } } function createPresentationNodes(title, targetUrl, icon_url, length) { // create nodes hierarchy for one collection (without children) // create elem for plus/minus icon var expandElem = document.createElement('expand'); // create elem for item icon var iconElem = document.createElement('icon'); expandElem.appendChild(iconElem); // Mozilla tries to infer an URL if url is empty and reloads containing page if (icon_url != '') { iconElem.style.backgroundImage = 'url("' + icon_url + '")'; } // create link var linkElem = document.createElement('a'); var titleTextNode = document.createTextNode(title); linkElem.appendChild(titleTextNode); var titleText = titleTemplate.split(NUM_TEMPLATE).join(length); linkElem.setAttribute('title', titleText); linkElem.setAttribute('href', targetUrl); iconElem.appendChild(linkElem); return expandElem; } function createLoadingNode() { var loadingElem = document.createElement('loading'); var titleTextNode = document.createTextNode(loadingMsg); loadingElem.appendChild(titleTextNode); return loadingElem; } function createNavigationTreeNode(source, basePath, deep) { var newelem = document.createElement(source.tagName); var navTreeNode = new navigationTreeNode(newelem); var elemPath; var elemTitle; if (source.getAttribute('isroot') != null) { elemTitle = source.getAttribute('name'); //elemPath = basePath; // set base url for virtual host support baseurl = source.getAttribute('baseURL'); elemPath = source.getAttribute('baseURL'); newelem.style.marginLeft = '0px'; navigationTree = navTreeNode; docNavTree.appendChild(newelem); } else { elemTitle = source.getAttribute('name'); elemPath = basePath + elemTitle + '/'; } navTreeNode.setPath(elemPath); //could show number of child items var length = source.getAttribute('length'); var icon_url = source.getAttribute('icon_url'); var targetUrl = elemPath + CONTENT_VIEW; var expandElem = createPresentationNodes(elemTitle, targetUrl, icon_url, length); newelem.appendChild(expandElem); // If no child element, we can disable the tree expansion if (length == '0') expandElem.setAttribute('disabled','1'); // If this is the selected node, we want to highlight it with CSS if (source.firstChild && source.firstChild.nodeValue == 'selected') navTreeNode.setSelected(); if (deep) { var children = getCollectionChildNodes(source); var numchildren = children.length; for (var i=0; i<numchildren; i++) { var navTreeNodeChild = createNavigationTreeNode(children[i], navTreeNode.path, deep); navTreeNode.appendChild(navTreeNodeChild); } if (numchildren) { navTreeNode.isEmpty = 0; navTreeNode.expand(); } else { navTreeNode.isEmpty = 1; // if no child, we do not display icon '+' if (length != '0') navTreeNode.collapse(); } } else { navTreeNode.isEmpty = 1; // if no child, we do not display icon '+' if (length != '0') navTreeNode.collapse(); } return navTreeNode; }
zope.app.rotterdam
/zope.app.rotterdam-5.0-py3-none-any.whl/zope/app/rotterdam/xmltree.js
xmltree.js
"""Custom Widgets for the rotterdam layer. """ __docformat__ = 'restructuredtext' from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile from zope.formlib.interfaces import IInputWidget from zope.formlib.widget import escape from zope.formlib.widget import renderElement from zope.formlib.widgets import TextAreaWidget from zope.interface import implementer @implementer(IInputWidget) class SimpleEditingWidget(TextAreaWidget): """Improved textarea editing, with async saving using JavaScript. Multi-line text (unicode) input. >>> from zope.publisher.browser import TestRequest >>> from zope.schema import Text >>> field = Text(__name__='foo', title=u'on') >>> request = TestRequest(form={'field.foo': u'Hello\\r\\nworld!'}) >>> widget = SimpleEditingWidget(field, request) >>> widget.style = '' >>> widget.hasInput() True >>> widget.getInputValue() u'Hello\\nworld!' >>> def normalize(s): ... return '\\n '.join(filter(None, s.split(' '))) >>> print(normalize( widget() )) <textarea cols="60" id="field.foo" name="field.foo" rows="15" >Hello\r world!</textarea> >>> print(normalize( widget.hidden() )) <input class="hiddenType" id="field.foo" name="field.foo" type="hidden" value="Hello&#13;&#10;world!" /> Calling `setRenderedValue` will change what gets output: >>> widget.setRenderedValue("Hey\\ndude!") >>> print(normalize( widget() )) <textarea cols="60" id="field.foo" name="field.foo" rows="15" >Hey\r dude!</textarea> Check that HTML is correctly encoded and decoded: >>> request = TestRequest( ... form={'field.foo': u'<h1>&copy;</h1>'}) >>> widget = SimpleEditingWidget(field, request) >>> widget.style = '' >>> widget.getInputValue() u'<h1>&copy;</h1>' >>> print(normalize( widget() )) <textarea cols="60" id="field.foo" name="field.foo" rows="15" >&lt;h1&gt;&amp;copy;&lt;/h1&gt;</textarea> """ default = "" width = 60 height = 15 extra = "" style = "width: 98%; font-family: monospace;" rowTemplate = ViewPageTemplateFile("simpleeditingrow.pt") rowFragment = ViewPageTemplateFile("simpleeditingrowfragment.pt") def _toFieldValue(self, value): if self.context.min_length and not value: # pragma: no cover return None return super()._toFieldValue(value) def __call__(self): return renderElement("textarea", name=self.name, id=self.name, cssClass=self.cssClass, rows=self.height, cols=self.width, style=self.style, contents=escape(self._getFormValue()), extra=self.extra) def contents(self): # pragma: no cover """Make the contents available to the template""" return self._getFormData()
zope.app.rotterdam
/zope.app.rotterdam-5.0-py3-none-any.whl/zope/app/rotterdam/editingwidgets.py
editingwidgets.py
========= CHANGES ========= 5.0 (2023-02-07) ================ - Drop support for Python 2.7, 3.5, 3.6. - Add support for Python 3.7, 3.8, 3.9, 3.10, 3.11. 4.1.0 (2017-05-10) ================== - Replaced the local implementation of ``ZopeVocabularyRegistry`` with one imported from ``zope.vocabularyregistry``. Backwards compatibility imports remain. 4.0.1 (2017-05-10) ================== - Packaging: Add the Python version and implementation classifiers. 4.0.0 (2017-04-17) ================== - Support for Python 3.5, 3.6 and PyPy has been added. - Added support for tox. - Drop dependency on ``zope.app.testing``, since it was not needed. 3.6.0 (2017-04-17) ================== - Package modernization including manifest. 3.5.0 (2008-12-16) ================== - Remove deprecated ``vocabulary`` directive. - Add test for component-based vocabulary registry. 3.4.0 (2007-10-27) ================== - Initial release independent of the main Zope tree.
zope.app.schema
/zope.app.schema-5.0.tar.gz/zope.app.schema-5.0/CHANGES.rst
CHANGES.rst
===================================== Component-based Vocabulary Registry ===================================== This package provides a vocabulary registry for zope.schema, based on the component architecture. **NOTE:** This functionality has been replaced with ``zope.vocabularyregistry``. These imports continue to work for backwards compatibility. It replaces the zope.schema's simple vocabulary registry when ``zope.app.schema`` package is imported, so it's done automatically. All we need is provide vocabulary factory utilities: >>> import zope.app.schema >>> from zope.component import provideUtility >>> from zope.schema.interfaces import IVocabularyFactory >>> from zope.schema.vocabulary import SimpleTerm >>> from zope.schema.vocabulary import SimpleVocabulary >>> def SomeVocabulary(context=None): ... terms = [SimpleTerm(1), SimpleTerm(2)] ... return SimpleVocabulary(terms) >>> provideUtility(SomeVocabulary, IVocabularyFactory, ... name='SomeVocabulary') Now we can get the vocabulary using standard zope.schema way: >>> from zope.schema.vocabulary import getVocabularyRegistry >>> vr = getVocabularyRegistry() >>> voc = vr.get(None, 'SomeVocabulary') >>> [term.value for term in voc] [1, 2] Configuration ============= This package provides configuration that sets security permissions and factories for the objects provided in ``zope.schema``. The ``zope.security`` package must be installed to use it. >>> from zope.configuration import xmlconfig >>> _ = xmlconfig.string(r""" ... <configure xmlns="http://namespaces.zope.org/zope" i18n_domain="zope"> ... <include package="zope.app.schema" /> ... </configure> ... """)
zope.app.schema
/zope.app.schema-5.0.tar.gz/zope.app.schema-5.0/src/zope/app/schema/README.rst
README.rst
======= CHANGES ======= 6.0 (2023-02-17) ---------------- - Add support for Python 3.10, 3.11. - Drop support for Python 2.7, 3.5, 3.6. 5.1.0 (2020-10-28) ------------------ - Add support for Python 3.8 and 3.9. - Drop support for Python 3.5. - Drop security declarations for the deprecated ``binhex`` standard library module from globalmodules.zcml. Note that globalmodules.zcml should be avoided. It's better to make declarations for only what you actually need to use. 5.0.0 (2019-07-12) ------------------ - Add support for Python 3.7. - Drop support for Python 3.4. - Drop security declarations for the deprecated ``formatter`` standard library module from globalmodules.zcml. Note that globalmodules.zcml should be avoided. It's better to make declarations for only what you actually need to use. 4.0.0 (2017-04-27) ------------------ - Removed use of 'zope.testing.doctestunit' in favor of stdlib's doctest. - Removed use of ``zope.app.testing`` in favor of ``zope.app.wsgi``. - Add support for PyPy, Python 3.4, 3.5 and 3.6. 3.7.5 (2010-01-08) ------------------ - Move 'zope.ManageApplication' permission to zope.app.applicationcontrol - Fix tests using a newer zope.publisher that requires zope.login. 3.7.3 (2009-11-29) ------------------ - provide a clean zope setup and move zope.app.testing to a test dependency - removed unused dependencies like ZODB3 etc. from install_requires 3.7.2 (2009-09-10) ------------------ - Added data attribute to '_protections.zcml' for PersistentList and PersistentDict to accomodate UserList and UserDict behavior when they are proxied. 3.7.1 (2009-08-15) ------------------ - Changed globalmodules.zcml to avoid making declarations for deprecated standard modules, to avoid deprecation warnings. Note that globalmodules.zcml should be avoided. It's better to make declarations for only what you actually need to use. 3.7.0 (2009-03-14) ------------------ - All interfaces, as well as some authentication-related helper classes and functions (checkPrincipal, PrincipalSource, PrincipalTerms, etc.) were moved into the new ``zope.authentication`` package. Backward-compatibility imports are provided. - The "global principal registry" along with its zcml directives was moved into new "zope.principalregistry" package. Backward-compatibility imports are provided. - The IPrincipal -> zope.publisher.interfaces.logginginfo.ILoggingInfo adapter was moved to ``zope.publisher``. Backward-compatibility import is provided. - The PermissionsVocabulary and PermissionIdsVocabulary has been moved to the ``zope.security`` package. Backward-compatibility imports are provided. - The registration of the "zope.Public" permission as well as some other common permissions, like "zope.View" have been moved to ``zope.security``. Its configure.zcml is now included by this package. - The "protect" function is now a no-op and is not needed anymore, because zope.security now knows about i18n messages and __name__ and __parent__ attributes and won't protect them by default. - The addCheckerPublic was moved from zope.app.security.tests to zope.security.testing. Backward-compatibility import is provided. - The ``LocalPermission`` class is now moved to new ``zope.app.localpermission`` package. This package now only has backward-compatibility imports and zcml includes. - Cleanup dependencies after refactorings. Also, don't depend on zope.app.testing for tests anymore. - Update package's description to point about refactorings done. 3.6.2 (2009-03-10) ------------------ - The `Allow`, `Deny` and `Unset` permission settings was preferred to be imported from ``zope.securitypolicy.interfaces`` for a long time and now they are completely moved there from ``zope.app.security.settings`` as well as the ``PermissionSetting`` class. The only thing left for backward compatibility is the import of Allow/Unset/Deny constants if ``zope.securitypolicy`` is installed to allow unpickling of security settings. 3.6.1 (2009-03-09) ------------------ - Depend on new ``zope.password`` package instead of ``zope.app.authentication`` to get password managers for the authentication utility, thus remove dependency on ``zope.app.authentication``. - Use template for AuthUtilitySearchView instead of ugly HTML constructing in the python code. - Bug: The `sha` and `md5` modules has been deprecated in Python 2.6. Whenever the ZCML of this package was included when using Python 2.6, a deprecation warning had been raised stating that `md5` and `sha` have been deprecated. Provided a simple condition to check whether Python 2.6 or later is installed by checking for the presense of `json` module thas was added only in Python 2.6 and thus optionally load the security declaration for `md5` and `sha`. - Remove deprecated code, thus removing explicit dependency on zope.deprecation and zope.deferredimport. - Cleanup code a bit, replace old __used_for__ statements by ``adapts`` calls. 3.6.0 (2009-01-31) ------------------ - Changed mailing list address to zope-dev at zope.org, because zope3-dev is retired now. Changed "cheeseshop" to "pypi" in the package homepage. - Moved the `protectclass` module to `zope.security` leaving only a compatibility module here that imports from the new location. - Moved the <module> directive implementation to `zope.security`. - Use `zope.container` instead of `zope.app.container`;. 3.5.3 (2008-12-11) ------------------ - use zope.browser.interfaces.ITerms instead of `zope.app.form.browser.interfaces`. 3.5.2 (2008-07-31) ------------------ - Bug: It turned out that checking for regex was not much better of an idea, since it causes deprecation warnings in Python 2.4. Thus let's look for a library that was added in Python 2.5. 3.5.1 (2008-06-24) ------------------ - Bug: The `gopherlib` module has been deprecated in Python 2.5. Whenever the ZCML of this package was included when using Python 2.5, a deprecation warning had been raised stating that `gopherlib` has been deprecated. Provided a simple condition to check whether Python 2.5 or later is installed by checking for the deleted `regex` module and thus optionally load the security declaration for `gopherlib`. 3.5.0 (2008-02-05) ------------------ - Feature: `zope.app.security.principalregistry.PrincipalRegistry.getPrincipal` returns `zope.security.management.system_user` when its id is used for the search key. 3.4.0 (2007-10-27) ------------------ - Initial release independent of the main Zope tree.
zope.app.security
/zope.app.security-6.0.tar.gz/zope.app.security-6.0/CHANGES.rst
CHANGES.rst
This package provides ZMI browser views for Zope security components. It used to provide a large part of security functionality for Zope 3, but it was factored out from this package to several little packages to reduce dependencies and improve reusability. The functionality was splitted into these new packages: * zope.authentication - the IAuthentication interface and related utilities. * zope.principalregistry - the global principal registry and its zcml directives. * zope.app.localpermission - the LocalPermission class that implements persistent permissions. The rest of functionality that were provided by this package is merged into ``zope.security`` and ``zope.publisher``. Backward-compatibility imports are provided to ensure that older applications work. See CHANGES.txt for more info.
zope.app.security
/zope.app.security-6.0.tar.gz/zope.app.security-6.0/README.rst
README.rst
==================== Login/Logout Snippet ==================== The class LoginLogout: >>> from zope.app.security.browser.auth import LoginLogout is used as a view to generate an HTML snippet suitable for logging in or logging out based on whether or not the current principal is authenticated. When the current principal is unauthenticated, it provides IUnauthenticatedPrincipal: >>> from zope.authentication.interfaces import IUnauthenticatedPrincipal >>> from zope.principalregistry.principalregistry import UnauthenticatedPrincipal >>> anonymous = UnauthenticatedPrincipal('anon', '', '') >>> IUnauthenticatedPrincipal.providedBy(anonymous) True When LoginLogout is used for a request that has an unauthenticated principal, it provides the user with a link to 'Login': >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> request.setPrincipal(anonymous) >>> print(LoginLogout(None, request)()) <a href="@@login.html?nextURL=http%3A//127.0.0.1">[Login]</a> Attempting to login at this point will fail because nothing has authorized the principal yet: >>> from zope.app.security.browser.auth import HTTPAuthenticationLogin >>> login = HTTPAuthenticationLogin() >>> login.request = request >>> login.context = None >>> login.failed = lambda: 'Login Failed' >>> login.login() 'Login Failed' There is a failsafe that will attempt to ask for HTTP Basic authentication: >>> from zope.app.security.browser.auth import HTTPBasicAuthenticationLogin >>> basic_login = HTTPBasicAuthenticationLogin() >>> basic_login.request = request >>> basic_login.failed = lambda: 'Basic Login Failed' >>> basic_login.login() 'Basic Login Failed' >>> request._response.getHeader('WWW-Authenticate', literal=True) 'basic realm="Zope"' >>> request._response.getStatus() 401 Of course, an unauthorized principal is confirmed to be logged out: >>> from zope.app.security.browser.auth import HTTPAuthenticationLogout >>> logout = HTTPAuthenticationLogout(None, request) >>> logout.logout(nextURL="bye.html") 'bye.html' >>> logout.confirmation = lambda: 'Good Bye' >>> logout.logout() 'Good Bye' Logout, however, behaves differently. Not all authentication protocols (i.e. credentials extractors/challengers) support 'logout'. Furthermore, we don't know how an admin may have configured Zope's authentication. Our solution is to rely on the admin to tell us explicitly that the site supports logout. By default, the LoginLogout snippet will not provide a logout link for an unauthenticated principal. To illustrate, we'll first setup a request with an unauthenticated principal: >>> from zope.security.interfaces import IPrincipal >>> from zope.interface import implementer >>> @implementer(IPrincipal) ... class Bob: ... id = 'bob' ... title = description = '' >>> bob = Bob() >>> IUnauthenticatedPrincipal.providedBy(bob) False >>> request.setPrincipal(bob) In this case, the default behavior is to return None for the snippet: >>> print(LoginLogout(None, request)()) None And at this time, login will correctly direct us to the next URL, or to the confirmation page: >>> login = HTTPAuthenticationLogin() >>> login.request = request >>> login.context = None >>> login.login(nextURL='good.html') >>> login.confirmation = lambda: "You Passed" >>> login.login() 'You Passed' Likewise for HTTP Basic authentication: >>> login = HTTPBasicAuthenticationLogin() >>> login.request = request >>> login.context = None >>> login.confirmation = lambda: "You Passed" >>> login.login() 'You Passed' To show a logout prompt, an admin must register a marker adapter that provides the interface: >>> from zope.authentication.interfaces import ILogoutSupported This flags to LoginLogout that the site supports logout. There is a 'no-op' adapter that can be registered for this: >>> from zope.authentication.logout import LogoutSupported >>> from zope.component import provideAdapter >>> provideAdapter(LogoutSupported, (None,), ILogoutSupported) Now when we use LoginLogout with an unauthenticated principal, we get a logout prompt: >>> print(LoginLogout(None, request)()) <a href="@@logout.html?nextURL=http%3A//127.0.0.1">[Logout]</a> And we can log this principal out, passing a URL to redirect to: >>> logout = HTTPAuthenticationLogout(None, request) >>> logout.redirect = lambda: 'You have been redirected.' >>> logout.logout(nextURL="loggedout.html") 'You have been redirected.'
zope.app.security
/zope.app.security-6.0.tar.gz/zope.app.security-6.0/src/zope/app/security/browser/loginlogout.rst
loginlogout.rst
import urllib.parse from zope.app.pagetemplate import ViewPageTemplateFile from zope.app.publisher.interfaces.http import ILogin from zope.authentication.interfaces import IAuthentication from zope.authentication.interfaces import ILogout from zope.authentication.interfaces import ILogoutSupported from zope.authentication.interfaces import IUnauthenticatedPrincipal from zope.i18n import translate from zope.interface import implementer from zope import component from zope.app.security.i18n import _ class AuthUtilitySearchView: template = ViewPageTemplateFile('authutilitysearchview.pt') searchTitle = 'principals.zcml' def __init__(self, context, request): self.context = context self.request = request def render(self, name): return self.template(title=self.searchTitle, name=name) def results(self, name): if (name + '.search') not in self.request: return None searchstring = self.request[name + '.searchstring'] return [principal.id for principal in self.context.getPrincipals(searchstring)] @implementer(ILogin) class HTTPAuthenticationLogin: confirmation = ViewPageTemplateFile('login.pt') failed = ViewPageTemplateFile('login_failed.pt') def login(self, nextURL=None): # we don't want to keep challenging if we're authenticated if IUnauthenticatedPrincipal.providedBy(self.request.principal): component.getUtility(IAuthentication).unauthorized( self.request.principal.id, self.request) return self.failed() else: return self._confirm(nextURL) def _confirm(self, nextURL): if nextURL is None: return self.confirmation() self.request.response.redirect(nextURL) class HTTPBasicAuthenticationLogin(HTTPAuthenticationLogin): """Issues a challenge to the browser to get basic auth credentials. This view can be used as a fail safe login in the even the normal login fails because of an improperly configured authentication utility. The failsafeness of this view relies on the fact that the global principal registry, which typically contains an adminitrator principal, uses basic auth credentials to authenticate. """ def login(self, nextURL=None): # we don't want to keep challenging if we're authenticated if IUnauthenticatedPrincipal.providedBy(self.request.principal): # hard-code basic auth challenge self.request.unauthorized('basic realm="Zope"') return self.failed() else: return self._confirm(nextURL) @implementer(ILogout) class HTTPAuthenticationLogout: """Since HTTP Authentication really does not know about logout, we are simply challenging the client again.""" confirmation = ViewPageTemplateFile('logout.pt') redirect = ViewPageTemplateFile('redirect.pt') def __init__(self, context, request): self.context = context self.request = request def logout(self, nextURL=None): if not IUnauthenticatedPrincipal.providedBy(self.request.principal): auth = component.getUtility(IAuthentication) ILogout(auth).logout(self.request) if nextURL: return self.redirect() if nextURL is None: return self.confirmation() else: return self.request.response.redirect(nextURL) class LoginLogout: def __init__(self, context, request): self.context = context self.request = request def __call__(self): if IUnauthenticatedPrincipal.providedBy(self.request.principal): return '<a href="@@login.html?nextURL={}">{}</a>'.format( urllib.parse.quote(self.request.getURL()), translate(_('[Login]'), context=self.request, default='[Login]')) if ILogoutSupported(self.request, None) is not None: return '<a href="@@logout.html?nextURL={}">{}</a>'.format( urllib.parse.quote(self.request.getURL()), translate(_('[Logout]'), context=self.request, default='[Logout]')) return None
zope.app.security
/zope.app.security-6.0.tar.gz/zope.app.security-6.0/src/zope/app/security/browser/auth.py
auth.py
=========================================== The Query View for Authentication Utilities =========================================== A regular authentication service will not provide the `ISourceQueriables` interface, but it is a queriable itself, since it provides the simple `getPrincipals(name)` method: >>> class Principal: ... def __init__(self, id): ... self.id = id >>> class MyAuthUtility: ... data = {'jim': Principal(42), 'don': Principal(0), ... 'stephan': Principal(1)} ... ... def getPrincipals(self, name): ... return [principal ... for id, principal in self.data.items() ... if name in id] Now that we have our queriable, we create the view for it: >>> from zope.app.security.browser.auth import AuthUtilitySearchView >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> view = AuthUtilitySearchView(MyAuthUtility(), request) This allows us to render a search form. >>> print(view.render('test')) # doctest: +NORMALIZE_WHITESPACE <h4>principals.zcml</h4> <div class="row"> <div class="label"> Search String </div> <div class="field"> <input type="text" name="test.searchstring" /> </div> </div> <div class="row"> <div class="field"> <input type="submit" name="test.search" value="Search" /> </div> </div> If we ask for results: >>> view.results('test') We don't get any, since we did not provide any. But if we give input: >>> request.form['test.searchstring'] = 'n' we still don't get any: >>> view.results('test') because we did not press the button. So let's press the button: >>> request.form['test.search'] = 'Search' so that we now get results (!): >>> ids = list(view.results('test')) >>> ids.sort() >>> ids [0, 1]
zope.app.security
/zope.app.security-6.0.tar.gz/zope.app.security-6.0/src/zope/app/security/browser/authutilitysearchview.rst
authutilitysearchview.rst
"""Functions that control how the Zope appserver knits itself together. """ import asyncore import logging import os import sys from time import process_time from time import time as wall_clock_time import zope.app.appsetup.appsetup import zope.app.appsetup.product import zope.processlifetime from zdaemon import zdoptions from zope.event import notify from zope.server.taskthreads import ThreadedTaskDispatcher CONFIG_FILENAME = "zope.conf" class ZopeOptions(zdoptions.ZDOptions): logsectionname = None def default_configfile(self): # XXX: this probably assumes a monolithic zope 3 source tree # layout and isn't likely to work dir = os.path.normpath( os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir)) for filename in [CONFIG_FILENAME, CONFIG_FILENAME + ".in"]: filename = os.path.join(dir, filename) if os.path.isfile(filename): return filename return None exit_status = None def main(args=None): # Record start times (real time and CPU time) t0 = wall_clock_time() c0 = process_time() setup(load_options(args)) t1 = wall_clock_time() c1 = process_time() logging.info("Startup time: %.3f sec real, %.3f sec CPU", t1 - t0, c1 - c0) run() sys.exit(exit_status or 0) def debug(args=None): options = load_options(args) zope.app.appsetup.product.setProductConfigurations( options.product_config) zope.app.appsetup.config(options.site_definition) db = zope.app.appsetup.appsetup.multi_database(options.databases)[0][0] notify(zope.processlifetime.DatabaseOpened(db)) return db def run(): try: global exit_status while asyncore.socket_map and exit_status is None: asyncore.poll(30.0) except KeyboardInterrupt: # Exit without spewing an exception. pass def load_options(args=None): if args is None: args = sys.argv[1:] options = ZopeOptions() options.schemadir = os.path.dirname(os.path.abspath(__file__)) options.realize(args) options = options.configroot if options and options.path: sys.path[:0] = [os.path.abspath(p) for p in options.path] return options def setup(options): sys.setcheckinterval(options.check_interval) zope.app.appsetup.product.setProductConfigurations( options.product_config) options.eventlog() options.accesslog() for logger in options.loggers: logger() features = ('zserver',) # Provide the devmode, if activated if options.devmode: features += ('devmode',) logging.warning( "Developer mode is enabled: this is a security risk " "and should NOT be enabled on production servers. Developer mode " "can be turned off in etc/zope.conf") zope.app.appsetup.config(options.site_definition, features=features) db = zope.app.appsetup.appsetup.multi_database(options.databases)[0][0] notify(zope.processlifetime.DatabaseOpened(db)) task_dispatcher = ThreadedTaskDispatcher() task_dispatcher.setThreadCount(options.threads) for server in options.servers: server.create(task_dispatcher, db) notify(zope.processlifetime.ProcessStarting()) return db
zope.app.server
/zope.app.server-5.0-py3-none-any.whl/zope/app/server/main.py
main.py