code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
"""``ul``, ``ol``, and ``li`` directives. """ __docformat__ = "reStructuredText" import copy import reportlab.lib.styles import reportlab.platypus import zope.schema from reportlab.platypus import flowables # noqa: F401 imported but unused from z3c.rml import attr from z3c.rml import directive from z3c.rml import flowable from z3c.rml import interfaces from z3c.rml import occurence from z3c.rml import stylesheet class IListItem(stylesheet.IMinimalListStyle, flowable.IFlow): """A list item in an ordered or unordered list.""" style = attr.Style( title='Style', description='The list style that is applied to the list.', required=False) class ListItem(flowable.Flow): signature = IListItem klass = reportlab.platypus.ListItem attrMapping = {} styleAttributes = zope.schema.getFieldNames(stylesheet.IMinimalListStyle) def processStyle(self, style): attrs = self.getAttributeValues(select=self.styleAttributes) if attrs or not hasattr(style, 'value'): style = copy.deepcopy(style) # Sigh, this is needed since unordered list items expect the value. style.value = style.start for name, value in attrs: setattr(style, name, value) return style def process(self): self.processSubDirectives() args = dict(self.getAttributeValues(ignore=self.styleAttributes)) if 'style' not in args: args['style'] = self.parent.baseStyle args['style'] = self.processStyle(args['style']) li = self.klass(self.flow, **args) self.parent.flow.append(li) class IOrderedListItem(IListItem): """An ordered list item.""" value = attr.Integer( title='Bullet Value', description='The counter value.', required=False) class OrderedListItem(ListItem): signature = IOrderedListItem class IUnorderedListItem(IListItem): """An ordered list item.""" value = attr.Combination( title='Bullet Value', description='The type of bullet character.', value_types=( attr.Choice(choices=interfaces.UNORDERED_BULLET_VALUES), attr.Text(max_length=1) ), required=False) class UnorderedListItem(ListItem): signature = IUnorderedListItem styleAttributes = ListItem.styleAttributes + ['value'] class IListBase(stylesheet.IBaseListStyle): style = attr.Style( title='Style', description='The list style that is applied to the list.', required=False) class ListBase(directive.RMLDirective): klass = reportlab.platypus.ListFlowable factories = {'li': ListItem} attrMapping = {} styleAttributes = zope.schema.getFieldNames(stylesheet.IBaseListStyle) def __init__(self, *args, **kw): super().__init__(*args, **kw) self.flow = [] def processStyle(self, style): attrs = self.getAttributeValues( select=self.styleAttributes, attrMapping=self.attrMapping) if attrs: style = copy.deepcopy(style) for name, value in attrs: setattr(style, name, value) return style def process(self): args = dict(self.getAttributeValues( ignore=self.styleAttributes, attrMapping=self.attrMapping)) if 'style' not in args: args['style'] = reportlab.lib.styles.ListStyle('List') args['style'] = self.baseStyle = self.processStyle(args['style']) self.processSubDirectives() li = self.klass(self.flow, **args) self.parent.flow.append(li) class IOrderedList(IListBase): """An ordered list.""" occurence.containing( occurence.ZeroOrMore('li', IOrderedListItem), ) bulletType = attr.Choice( title='Bullet Type', description='The type of bullet formatting.', choices=interfaces.ORDERED_LIST_TYPES, doLower=False, required=False) class OrderedList(ListBase): signature = IOrderedList factories = {'li': OrderedListItem} styleAttributes = ListBase.styleAttributes + ['bulletType'] class IUnorderedList(IListBase): """And unordered list.""" occurence.containing( occurence.ZeroOrMore('li', IUnorderedListItem), ) value = attr.Choice( title='Bullet Value', description='The type of bullet character.', choices=interfaces.UNORDERED_BULLET_VALUES, default='circle', required=False) class UnorderedList(ListBase): signature = IUnorderedList attrMapping = {'value': 'start'} factories = {'li': UnorderedListItem} def getAttributeValues(self, *args, **kw): res = super().getAttributeValues(*args, **kw) res.append(('bulletType', 'bullet')) return res flowable.Flow.factories['ol'] = OrderedList flowable.IFlow.setTaggedValue( 'directives', flowable.IFlow.getTaggedValue('directives') + (occurence.ZeroOrMore('ol', IOrderedList),) ) flowable.Flow.factories['ul'] = UnorderedList flowable.IFlow.setTaggedValue( 'directives', flowable.IFlow.getTaggedValue('directives') + (occurence.ZeroOrMore('ul', IUnorderedList),) )
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/list.py
list.py
"""RML Directive Implementation """ import logging import zope.interface import zope.schema from lxml import etree from z3c.rml import interfaces from z3c.rml.attr import getManager logging.raiseExceptions = False logger = logging.getLogger("z3c.rml") ABORT_ON_INVALID_DIRECTIVE = False def DeprecatedDirective(iface, reason): zope.interface.directlyProvides(iface, interfaces.IDeprecatedDirective) iface.setTaggedValue('deprecatedReason', reason) return iface def getFileInfo(directive, element=None): root = directive while root.parent: root = root.parent if element is None: element = directive.element return '(file %s, line %i)' % (root.filename, element.sourceline) @zope.interface.implementer(interfaces.IRMLDirective) class RMLDirective: signature = None factories = {} def __init__(self, element, parent): self.element = element self.parent = parent def getAttributeValues(self, ignore=None, select=None, attrMapping=None, includeMissing=False, valuesOnly=False): """See interfaces.IRMLDirective""" manager = getManager(self) cache = '{}.{}'.format( self.signature.__module__, self.signature.__name__) if cache in manager.attributesCache: fields = manager.attributesCache[cache] else: fields = [] for name, attr in zope.schema.getFieldsInOrder(self.signature): fields.append((name, attr)) manager.attributesCache[cache] = fields items = [] for name, attr in fields: # Only add the attribute to the list, if it is supposed there if ((ignore is None or name not in ignore) and (select is None or name in select)): # Get the value. value = attr.bind(self).get() # If no value was found for a required field, raise a value # error if attr.required and value is attr.missing_value: raise ValueError( 'No value for required attribute "%s" ' 'in directive "%s" %s.' % ( name, self.element.tag, getFileInfo(self))) # Only add the entry if the value is not the missing value or # missing values are requested to be included. if value is not attr.missing_value or includeMissing: items.append((name, value)) # Sort the items based on the section if select is not None: select = list(select) items = sorted(items, key=lambda n: select.index(n[0])) # If the attribute name does not match the internal API # name, then convert the name to the internal one if attrMapping: items = [(attrMapping.get(name, name), value) for name, value in items] # Sometimes we only want the values without the names if valuesOnly: return [value for name, value in items] return items def processSubDirectives(self, select=None, ignore=None): # Go through all children of the directive and try to process them. for element in self.element.getchildren(): # Ignore all comments if isinstance(element, etree._Comment): continue # Raise an error/log any unknown directive. if element.tag not in self.factories: msg = "Directive %r could not be processed and was " \ "ignored. %s" % (element.tag, getFileInfo(self, element)) # Record any tags/elements that could not be processed. logger.warning(msg) if ABORT_ON_INVALID_DIRECTIVE: raise ValueError(msg) continue if select is not None and element.tag not in select: continue if ignore is not None and element.tag in ignore: continue directive = self.factories[element.tag](element, self) directive.process() def process(self): self.processSubDirectives()
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/directive.py
directive.py
"""RML ``document`` element """ import io import logging import reportlab.pdfgen.canvas import zope.interface from reportlab.lib import colors from reportlab.lib import fonts from reportlab.pdfbase import cidfonts from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase import ttfonts from reportlab.platypus import tableofcontents from reportlab.platypus.doctemplate import IndexingFlowable from z3c.rml import attr from z3c.rml import canvas from z3c.rml import directive from z3c.rml import doclogic # noqa: F401 imported but unused from z3c.rml import interfaces from z3c.rml import list # noqa: F401 imported but unused from z3c.rml import occurence from z3c.rml import pdfinclude # noqa: F401 imported but unused from z3c.rml import special from z3c.rml import storyplace # noqa: F401 imported but unused from z3c.rml import stylesheet from z3c.rml import template LOGGER_NAME = 'z3c.rml.render' class IRegisterType1Face(interfaces.IRMLDirectiveSignature): """Register a new Type 1 font face.""" afmFile = attr.File( title='AFM File', description='Path to AFM file used to register the Type 1 face.', doNotOpen=True, required=True) pfbFile = attr.File( title='PFB File', description='Path to PFB file used to register the Type 1 face.', doNotOpen=True, required=True) class RegisterType1Face(directive.RMLDirective): signature = IRegisterType1Face def process(self): args = self.getAttributeValues(valuesOnly=True) face = pdfmetrics.EmbeddedType1Face(*args) pdfmetrics.registerTypeFace(face) class IRegisterFont(interfaces.IRMLDirectiveSignature): """Register a new font based on a face and encoding.""" name = attr.Text( title='Name', description=('The name under which the font can be used in style ' 'declarations or other parameters that lookup a font.'), required=True) faceName = attr.Text( title='Face Name', description=('The name of the face the font uses. The face has to ' 'be previously registered.'), required=True) encName = attr.Text( title='Encoding Name', description=('The name of the encdoing to be used.'), required=True) class RegisterFont(directive.RMLDirective): signature = IRegisterFont def process(self): args = self.getAttributeValues(valuesOnly=True) font = pdfmetrics.Font(*args) pdfmetrics.registerFont(font) class IAddMapping(interfaces.IRMLDirectiveSignature): """Map various styles(bold, italic) of a font name to the actual ps fonts used.""" faceName = attr.Text( title='Name', description=('The name of the font to be mapped'), required=True) bold = attr.Integer( title='Bold', description=('Bold'), required=True) italic = attr.Integer( title='Italic', description=('Italic'), required=True) psName = attr.Text( title='psName', description=('Actual font name mapped'), required=True) class AddMapping(directive.RMLDirective): signature = IAddMapping def process(self): args = self.getAttributeValues(valuesOnly=True) fonts.addMapping(*args) class IRegisterTTFont(interfaces.IRMLDirectiveSignature): """Register a new TrueType font given the TT file and face name.""" faceName = attr.Text( title='Face Name', description=('The name of the face the font uses. The face has to ' 'be previously registered.'), required=True) fileName = attr.File( title='File Name', description='File path of the of the TrueType font.', doNotOpen=True, doNotModify=True, required=True) class RegisterTTFont(directive.RMLDirective): signature = IRegisterTTFont def process(self): args = self.getAttributeValues(valuesOnly=True) font = ttfonts.TTFont(*args) pdfmetrics.registerFont(font) class IRegisterCidFont(interfaces.IRMLDirectiveSignature): """Register a new CID font given the face name.""" faceName = attr.Text( title='Face Name', description=('The name of the face the font uses. The face has to ' 'be previously registered.'), required=True) encName = attr.Text( title='Encoding Name', description=('The name of the encoding to use for the font.'), required=False) class RegisterCidFont(directive.RMLDirective): signature = IRegisterCidFont attrMapping = {'faceName': 'face', 'encName': 'encoding'} def process(self): args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) if 'encoding' in args: font = cidfonts.CIDFont(**args) else: font = cidfonts.UnicodeCIDFont(**args) pdfmetrics.registerFont(font) class IRegisterFontFamily(interfaces.IRMLDirectiveSignature): """Register a new font family.""" name = attr.Text( title='Name', description=('The name of the font family.'), required=True) normal = attr.Text( title='Normal Font Name', description=('The name of the normal font variant.'), required=False) bold = attr.Text( title='Bold Font Name', description=('The name of the bold font variant.'), required=False) italic = attr.Text( title='Italic Font Name', description=('The name of the italic font variant.'), required=False) boldItalic = attr.Text( title='Bold/Italic Font Name', description=('The name of the bold/italic font variant.'), required=True) class RegisterFontFamily(directive.RMLDirective): signature = IRegisterFontFamily attrMapping = {'name': 'family'} def process(self): args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) pdfmetrics.registerFontFamily(**args) class IColorDefinition(interfaces.IRMLDirectiveSignature): """Define a new color and give it a name to be known under.""" id = attr.Text( title='Id', description=('The id/name the color will be available under.'), required=True) RGB = attr.Color( title='RGB Color', description=('The color value that is represented.'), required=False) CMYK = attr.Color( title='CMYK Color', description=('The color value that is represented.'), required=False) value = attr.Color( title='Color', description=('The color value that is represented.'), required=False) spotName = attr.Text( title='Spot Name', description=('The Spot Name of the CMYK color.'), required=False) density = attr.Float( title='Density', description=('The color density of the CMYK color.'), min=0.0, max=1.0, required=False) knockout = attr.Text( title='Knockout', description=('The knockout of the CMYK color.'), required=False) alpha = attr.Float( title='Alpha', description=('The alpha channel of the color.'), min=0.0, max=1.0, required=False) class ColorDefinition(directive.RMLDirective): signature = IColorDefinition def process(self): kwargs = dict(self.getAttributeValues()) id = kwargs.pop('id') for attrName in ('RGB', 'CMYK', 'value'): color = kwargs.pop(attrName, None) if color is not None: # CMYK has additional attributes. for name, value in kwargs.items(): setattr(color, name, value) manager = attr.getManager(self) manager.colors[id] = color return raise ValueError('At least one color definition must be specified.') # Initialize also supports the <color> tag. stylesheet.Initialize.factories['color'] = ColorDefinition stylesheet.IInitialize.setTaggedValue( 'directives', stylesheet.IInitialize.getTaggedValue('directives') + (occurence.ZeroOrMore('color', IColorDefinition),) ) class IStartIndex(interfaces.IRMLDirectiveSignature): """Start a new index.""" name = attr.Text( title='Name', description='The name of the index.', default='index', required=True) offset = attr.Integer( title='Offset', description='The counting offset.', min=0, required=False) format = attr.Choice( title='Format', description=('The format the index is going to use.'), choices=interfaces.LIST_FORMATS, required=False) class StartIndex(directive.RMLDirective): signature = IStartIndex def process(self): kwargs = dict(self.getAttributeValues()) name = kwargs['name'] manager = attr.getManager(self) manager.indexes[name] = tableofcontents.SimpleIndex(**kwargs) class ICropMarks(interfaces.IRMLDirectiveSignature): """Crop Marks specification""" name = attr.Text( title='Name', description='The name of the index.', default='index', required=True) borderWidth = attr.Measurement( title='Border Width', description='The width of the crop mark border.', required=False) markColor = attr.Color( title='Mark Color', description='The color of the crop marks.', required=False) markWidth = attr.Measurement( title='Mark Width', description='The line width of the actual crop marks.', required=False) markLength = attr.Measurement( title='Mark Length', description='The length of the actual crop marks.', required=False) markLast = attr.Boolean( title='Mark Last', description='If set, marks are drawn after the content is rendered.', required=False) bleedWidth = attr.Measurement( title='Bleed Width', description=('The width of the page bleed.'), required=False) class CropMarksProperties: borderWidth = 36 markWidth = 0.5 markColor = colors.toColor('green') markLength = 18 markLast = True bleedWidth = 0 class CropMarks(directive.RMLDirective): signature = ICropMarks def process(self): cmp = CropMarksProperties() for name, value in self.getAttributeValues(): setattr(cmp, name, value) self.parent.parent.cropMarks = cmp class ILogConfig(interfaces.IRMLDirectiveSignature): """Configure the render logger.""" level = attr.Choice( title='Level', description='The default log level.', choices=interfaces.LOG_LEVELS, doLower=False, required=False) format = attr.Text( title='Format', description='The format of the log messages.', required=False) filename = attr.File( title='File Name', description='The path to the file that is being logged.', doNotOpen=True, required=True) filemode = attr.Choice( title='File Mode', description='The mode to open the file in.', choices={'WRITE': 'w', 'APPEND': 'a'}, default='a', required=False) datefmt = attr.Text( title='Date Format', description='The format of the log message date.', required=False) class LogConfig(directive.RMLDirective): signature = ILogConfig def process(self): args = dict(self.getAttributeValues()) logger = logging.getLogger(LOGGER_NAME) handler = logging.FileHandler(args['filename'][8:], args['filemode']) formatter = logging.Formatter( args.get('format'), args.get('datefmt')) handler.setFormatter(formatter) logger.addHandler(handler) if 'level' in args: logger.setLevel(args['level']) self.parent.parent.logger = logger class IDocInit(interfaces.IRMLDirectiveSignature): occurence.containing( occurence.ZeroOrMore('color', IColorDefinition), occurence.ZeroOrMore('name', special.IName), occurence.ZeroOrMore('registerType1Face', IRegisterType1Face), occurence.ZeroOrMore('registerFont', IRegisterFont), occurence.ZeroOrMore('registerCidFont', IRegisterCidFont), occurence.ZeroOrMore('registerTTFont', IRegisterTTFont), occurence.ZeroOrMore('registerFontFamily', IRegisterFontFamily), occurence.ZeroOrMore('addMapping', IAddMapping), occurence.ZeroOrMore('logConfig', ILogConfig), occurence.ZeroOrMore('cropMarks', ICropMarks), occurence.ZeroOrMore('startIndex', IStartIndex), ) pageMode = attr.Choice( title='Page Mode', description=('The page mode in which the document is opened in ' 'the viewer.'), choices=('UseNone', 'UseOutlines', 'UseThumbs', 'FullScreen'), required=False) pageLayout = attr.Choice( title='Page Layout', description=('The layout in which the pages are displayed in ' 'the viewer.'), choices=('SinglePage', 'OneColumn', 'TwoColumnLeft', 'TwoColumnRight'), required=False) useCropMarks = attr.Boolean( title='Use Crop Marks', description='A flag when set shows crop marks on the page.', required=False) hideToolbar = attr.TextBoolean( title='Hide Toolbar', description=('A flag indicating that the toolbar is hidden in ' 'the viewer.'), required=False) hideMenubar = attr.TextBoolean( title='Hide Menubar', description=('A flag indicating that the menubar is hidden in ' 'the viewer.'), required=False) hideWindowUI = attr.TextBoolean( title='Hide Window UI', description=('A flag indicating that the window UI is hidden in ' 'the viewer.'), required=False) fitWindow = attr.TextBoolean( title='Fit Window', description='A flag indicating that the page fits in the viewer.', required=False) centerWindow = attr.TextBoolean( title='Center Window', description=('A flag indicating that the page fits is centered ' 'in the viewer.'), required=False) displayDocTitle = attr.TextBoolean( title='Display Doc Title', description=('A flag indicating that the document title is displayed ' 'in the viewer.'), required=False) nonFullScreenPageMode = attr.Choice( title='Non-Full-Screen Page Mode', description=('Non-Full-Screen page mode in the viewer.'), choices=('UseNone', 'UseOutlines', 'UseThumbs', 'UseOC'), required=False) direction = attr.Choice( title='Text Direction', description=('The text direction of the PDF.'), choices=('L2R', 'R2L'), required=False) viewArea = attr.Choice( title='View Area', description=('View Area setting used in the viewer.'), choices=('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox'), required=False) viewClip = attr.Choice( title='View Clip', description=('View Clip setting used in the viewer.'), choices=('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox'), required=False) printArea = attr.Choice( title='Print Area', description=('Print Area setting used in the viewer.'), choices=('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox'), required=False) printClip = attr.Choice( title='Print Clip', description=('Print Clip setting used in the viewer.'), choices=('MediaBox', 'CropBox', 'BleedBox', 'TrimBox', 'ArtBox'), required=False) printScaling = attr.Choice( title='Print Scaling', description=('The print scaling mode in which the document is opened ' 'in the viewer.'), choices=('None', 'AppDefault'), required=False) class DocInit(directive.RMLDirective): signature = IDocInit factories = { 'name': special.Name, 'color': ColorDefinition, 'registerType1Face': RegisterType1Face, 'registerFont': RegisterFont, 'registerTTFont': RegisterTTFont, 'registerCidFont': RegisterCidFont, 'registerFontFamily': RegisterFontFamily, 'addMapping': AddMapping, 'logConfig': LogConfig, 'cropMarks': CropMarks, 'startIndex': StartIndex, } viewerOptions = { option[0].lower() + option[1:]: option for option in ['HideToolbar', 'HideMenubar', 'HideWindowUI', 'FitWindow', 'CenterWindow', 'DisplayDocTitle', 'NonFullScreenPageMode', 'Direction', 'ViewArea', 'ViewClip', 'PrintArea', 'PrintClip', 'PrintScaling']} def process(self): kwargs = dict(self.getAttributeValues()) self.parent.cropMarks = kwargs.get('useCropMarks', False) self.parent.pageMode = kwargs.get('pageMode') self.parent.pageLayout = kwargs.get('pageLayout') for name in self.viewerOptions: setattr(self.parent, name, kwargs.get(name)) super().process() class IDocument(interfaces.IRMLDirectiveSignature): occurence.containing( occurence.ZeroOrOne('docinit', IDocInit), occurence.ZeroOrOne('stylesheet', stylesheet.IStylesheet), occurence.ZeroOrOne('template', template.ITemplate), occurence.ZeroOrOne('story', template.IStory), occurence.ZeroOrOne('pageInfo', canvas.IPageInfo), occurence.ZeroOrMore('pageDrawing', canvas.IPageDrawing), ) filename = attr.Text( title='File Name', description=('The default name of the output file, if no output ' 'file was provided.'), required=True) title = attr.Text( title='Title', description=('The "Title" annotation for the PDF document.'), required=False) subject = attr.Text( title='Subject', description=('The "Subject" annotation for the PDF document.'), required=False) author = attr.Text( title='Author', description=('The "Author" annotation for the PDF document.'), required=False) creator = attr.Text( title='Creator', description=('The "Creator" annotation for the PDF document.'), required=False) debug = attr.Boolean( title='Debug', description='A flag to activate the debug output.', default=False, required=False) compression = attr.BooleanWithDefault( title='Compression', description=('A flag determining whether page compression should ' 'be used.'), required=False) invariant = attr.BooleanWithDefault( title='Invariant', description=('A flag that determines whether the produced PDF ' 'should be invariant with respect to the date and ' 'the exact contents.'), required=False) @zope.interface.implementer(interfaces.IManager, interfaces.IPostProcessorManager, interfaces.ICanvasManager) class Document(directive.RMLDirective): signature = IDocument factories = { 'docinit': DocInit, 'stylesheet': stylesheet.Stylesheet, 'template': template.Template, 'story': template.Story, 'pageInfo': canvas.PageInfo, 'pageDrawing': canvas.PageDrawing, } def __init__(self, element, canvasClass=None): super().__init__(element, None) self.names = {} self.styles = {} self.colors = {} self.indexes = {} self.postProcessors = [] self.filename = '<unknown>' self.cropMarks = False self.pageLayout = None self.pageMode = None self.logger = None self.svgs = {} self.attributesCache = {} for name in DocInit.viewerOptions: setattr(self, name, None) if not canvasClass: canvasClass = reportlab.pdfgen.canvas.Canvas self.canvasClass = canvasClass def _indexAdd(self, canvas, name, label): self.indexes[name](canvas, name, label) def _beforeDocument(self): self._initCanvas(self.doc.canv) self.canvas = self.doc.canv def _initCanvas(self, canvas): canvas._indexAdd = self._indexAdd canvas.manager = self if self.pageLayout: canvas._doc._catalog.setPageLayout(self.pageLayout) if self.pageMode: canvas._doc._catalog.setPageMode(self.pageMode) for name, option in DocInit.viewerOptions.items(): if getattr(self, name) is not None: canvas.setViewerPreference(option, getattr(self, name)) # Setting annotations. data = dict(self.getAttributeValues( select=('title', 'subject', 'author', 'creator'))) canvas.setTitle(data.get('title')) canvas.setSubject(data.get('subject')) canvas.setAuthor(data.get('author')) canvas.setCreator(data.get('creator')) def process(self, outputFile=None, maxPasses=2): """Process document""" # Reset all reportlab global variables. This is very important for # ReportLab not to fail. reportlab.rl_config._reset() debug = self.getAttributeValues(select=('debug',), valuesOnly=True)[0] if not debug: reportlab.rl_config.shapeChecking = 0 # Add our colors mapping to the default ones. colors.toColor.setExtraColorsNameSpace(self.colors) if outputFile is None: # TODO: This is relative to the input file *not* the CWD!!! outputFile = open(self.element.get('filename'), 'wb') # Create a temporary output file, so that post-processors can # massage the output self.outputFile = tempOutput = io.BytesIO() # Process common sub-directives self.processSubDirectives(select=('docinit', 'stylesheet')) # Handle Page Drawing Documents if self.element.find('pageDrawing') is not None: kwargs = dict(self.getAttributeValues( select=('compression', 'debug'), attrMapping={'compression': 'pageCompression', 'debug': 'verbosity'} )) kwargs['cropMarks'] = self.cropMarks self.canvas = self.canvasClass(tempOutput, **kwargs) self._initCanvas(self.canvas) self.processSubDirectives(select=('pageInfo', 'pageDrawing')) if hasattr(self.canvas, 'AcroForm'): # Makes default values appear in ReportLab >= 3.1.44 self.canvas.AcroForm.needAppearances = 'true' self.canvas.save() # Handle Flowable-based documents. elif self.element.find('template') is not None: self.processSubDirectives(select=('template', 'story')) self.doc.beforeDocument = self._beforeDocument def callback(event, value): if event == 'PASS': self.doc.current_pass = value self.doc.setProgressCallBack(callback) self.doc.multiBuild( self.flowables, maxPasses=maxPasses, **{'canvasmaker': self.canvasClass}) # Process all post processors for name, processor in self.postProcessors: tempOutput.seek(0) tempOutput = processor.process(tempOutput) # Save the result into our real output file tempOutput.seek(0) outputFile.write(tempOutput.getvalue()) # Cleanup. colors.toColor.setExtraColorsNameSpace({}) reportlab.rl_config.shapeChecking = 1 def get_name(self, name, default=None): if default is None: default = '' if name not in self.names: if self.doc._indexingFlowables and isinstance( self.doc._indexingFlowables[-1], DummyIndexingFlowable ): return default self.doc._indexingFlowables.append(DummyIndexingFlowable()) return self.names.get(name, default) class DummyIndexingFlowable(IndexingFlowable): """A dummy flowable to trick multiBuild into performing +1 pass.""" def __init__(self): self.i = -1 def isSatisfied(self): self.i += 1 return self.i
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/document.py
document.py
"""Page Drawing Related Element Processing """ import types import reportlab.pdfbase.pdfform from z3c.rml import attr from z3c.rml import directive from z3c.rml import interfaces from z3c.rml import occurence try: import reportlab.graphics.barcode except ImportError: # barcode package has not been installed import reportlab.graphics reportlab.graphics.barcode = types.ModuleType('barcode') reportlab.graphics.barcode.getCodeNames = lambda: () class IBarCodeBase(interfaces.IRMLDirectiveSignature): """Create a bar code.""" code = attr.Choice( title='Code', description='The name of the type of code to use.', choices=reportlab.graphics.barcode.getCodeNames(), required=True) value = attr.TextNode( title='Value', description='The value represented by the code.', required=True) width = attr.Measurement( title='Width', description='The width of the barcode.', required=False) height = attr.Measurement( title='Height', description='The height of the barcode.', required=False) barStrokeColor = attr.Color( title='Bar Stroke Color', description=('The color of the line strokes in the barcode.'), required=False) barStrokeWidth = attr.Measurement( title='Bar Stroke Width', description='The width of the line strokes in the barcode.', required=False) barFillColor = attr.Color( title='Bar Fill Color', description=('The color of the filled shapes in the barcode.'), required=False) gap = attr.Measurement( title='Gap', description='The width of the inter-character gaps.', required=False) # Bar code dependent attributes # I2of5, Code128, Standard93, FIM, POSTNET, Ean13B barWidth = attr.Measurement( title='Bar Width', description='The width of the smallest bar within the barcode', required=False) # I2of5, Code128, Standard93, FIM, POSTNET barHeight = attr.Measurement( title='Bar Height', description='The height of the symbol.', required=False) # I2of5 ratio = attr.Float( title='Ratio', description=('The ratio of wide elements to narrow elements. ' 'Must be between 2.0 and 3.0 (or 2.2 and 3.0 if the ' 'barWidth is greater than 20 mils (.02 inch)).'), min=2.0, max=3.0, required=False) # I2of5 # Should be boolean, but some code want it as int; will still work checksum = attr.Integer( title='Ratio', description=('A flag that enables the computation and inclusion of ' 'the check digit.'), required=False) # I2of5 bearers = attr.Float( title='Bearers', description=('Height of bearer bars (horizontal bars along the top ' 'and bottom of the barcode). Default is 3 ' 'x-dimensions. Set to zero for no bearer bars.' '(Bearer bars help detect misscans, so it is ' 'suggested to leave them on).'), required=False) # I2of5, Code128, Standard93, FIM, Ean13 quiet = attr.Boolean( title='Quiet Zone', description=('A flag to include quiet zones in the symbol.'), required=False) # I2of5, Code128, Standard93, FIM, Ean13 lquiet = attr.Measurement( title='Left Quiet Zone', description=("Quiet zone size to the left of code, if quiet is " "true. Default is the greater of .25 inch or .15 times " "the symbol's length."), required=False) # I2of5, Code128, Standard93, FIM, Ean13 rquiet = attr.Measurement( title='Right Quiet Zone', description=("Quiet zone size to the right of code, if quiet is " "true. Default is the greater of .25 inch or .15 times " "the symbol's length."), required=False) # I2of5, Code128, Standard93, FIM, POSTNET, Ean13 fontName = attr.Text( title='Font Name', description=('The font used to print the value.'), required=False) # I2of5, Code128, Standard93, FIM, POSTNET, Ean13 fontSize = attr.Measurement( title='Font Size', description=('The size of the value text.'), required=False) # I2of5, Code128, Standard93, FIM, POSTNET, Ean13 humanReadable = attr.Boolean( title='Human Readable', description=('A flag when set causes the value to be printed below ' 'the bar code.'), required=False) # I2of5, Standard93 stop = attr.Boolean( title='Show Start/Stop', description=('A flag to specify whether the start/stop symbols ' 'are to be shown.'), required=False) # FIM, POSTNET spaceWidth = attr.Measurement( title='Space Width', description='The space of the inter-character gaps.', required=False) # POSTNET shortHeight = attr.Measurement( title='Short Height', description='The height of the short bar.', required=False) # Ean13 textColor = attr.Color( title='Text Color', description=('The color of human readable text.'), required=False) # USPS4S routing = attr.Text( title='Routing', description='The routing information string.', required=False) # QR barLevel = attr.Choice( title='Bar Level', description='The error correction level for QR code', choices=['L', 'M', 'Q', 'H'], required=False) barBorder = attr.Measurement( title='Bar Border', description='The width of the border around a QR code.', required=False) class IBarCode(IBarCodeBase): """A barcode graphic.""" x = attr.Measurement( title='X-Position', description='The x-position of the lower-left corner of the barcode.', default=0, required=False) y = attr.Measurement( title='Y-Position', description='The y-position of the lower-left corner of the barcode.', default=0, required=False) isoScale = attr.Boolean( title='Isometric Scaling', description='When set, the aspect ration of the barcode is enforced.', required=False) class BarCode(directive.RMLDirective): signature = IBarCode def process(self): kw = dict(self.getAttributeValues()) name = kw.pop('code') kw['value'] = str(kw['value']) x = kw.pop('x', 0) y = kw.pop('y', 0) code = reportlab.graphics.barcode.createBarcodeDrawing(name, **kw) manager = attr.getManager(self, interfaces.ICanvasManager) code.drawOn(manager.canvas, x, y) class IField(interfaces.IRMLDirectiveSignature): """A field.""" title = attr.Text( title='Title', description='The title of the field.', required=True) x = attr.Measurement( title='X-Position', description='The x-position of the lower-left corner of the field.', default=0, required=True) y = attr.Measurement( title='Y-Position', description='The y-position of the lower-left corner of the field.', default=0, required=True) class Field(directive.RMLDirective): signature = IField callable = None attrMapping = {} def process(self): kwargs = dict(self.getAttributeValues(attrMapping=self.attrMapping)) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas getattr(reportlab.pdfbase.pdfform, self.callable)(canvas, **kwargs) class ITextField(IField): """A text field within the PDF""" width = attr.Measurement( title='Width', description='The width of the text field.', required=True) height = attr.Measurement( title='Height', description='The height of the text field.', required=True) value = attr.Text( title='Value', description='The default text value of the field.', required=False) maxLength = attr.Integer( title='Maximum Length', description='The maximum amount of characters allowed in the field.', required=False) multiline = attr.Boolean( title='Multiline', description='A flag when set allows multiple lines within the field.', required=False) class TextField(Field): signature = ITextField callable = 'textFieldAbsolute' attrMapping = {'maxLength': 'maxlen'} class IButtonField(IField): """A button field within the PDF""" value = attr.Choice( title='Value', description='The value of the button.', choices=('Yes', 'Off'), required=True) class ButtonField(Field): signature = IButtonField callable = 'buttonFieldAbsolute' class IOption(interfaces.IRMLDirectiveSignature): """An option in the select field.""" value = attr.TextNode( title='Value', description='The value of the option.', required=True) class Option(directive.RMLDirective): signature = IOption def process(self): value = self.getAttributeValues(valuesOnly=True)[0] self.parent.options.append(value) class ISelectField(IField): """A selection field within the PDF""" occurence.containing( occurence.ZeroOrMore('option', IOption)) width = attr.Measurement( title='Width', description='The width of the select field.', required=True) height = attr.Measurement( title='Height', description='The height of the select field.', required=True) value = attr.Text( title='Value', description='The default value of the field.', required=False) class SelectField(Field): signature = ISelectField callable = 'selectFieldAbsolute' factories = {'option': Option} def process(self): self.options = [] self.processSubDirectives() kwargs = dict(self.getAttributeValues(attrMapping=self.attrMapping)) kwargs['options'] = self.options canvas = attr.getManager(self, interfaces.ICanvasManager).canvas getattr(reportlab.pdfbase.pdfform, self.callable)(canvas, **kwargs)
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/form.py
form.py
"""RML to PDF Converter """ import argparse import io import os import sys import zope.interface from lxml import etree from z3c.rml import document from z3c.rml import interfaces zope.interface.moduleProvides(interfaces.IRML2PDF) def parseString(xml, removeEncodingLine=True, filename=None): if isinstance(xml, str) and removeEncodingLine: # RML is a unicode string, but oftentimes documents declare their # encoding using <?xml ...>. Unfortuantely, I cannot tell lxml to # ignore that directive. Thus we remove it. if xml.startswith('<?xml'): xml = xml.split('\n', 1)[-1] root = etree.fromstring(xml) doc = document.Document(root) if filename: doc.filename = filename output = io.BytesIO() doc.process(output) output.seek(0) return output def go(xmlInputName, outputFileName=None, outDir=None, dtdDir=None): if hasattr(xmlInputName, 'read'): # it is already a file-like object xmlFile = xmlInputName xmlInputName = 'input.pdf' else: with open(xmlInputName, 'rb') as xmlFile: return go(xmlFile, outputFileName, outDir, dtdDir) # If an output filename is specified, create an output file for it outputFile = None if outputFileName is not None: if hasattr(outputFileName, 'write'): # it is already a file-like object outputFile = outputFileName outputFileName = 'output.pdf' else: if outDir is not None: outputFileName = os.path.join(outDir, outputFileName) with open(outputFileName, 'wb') as outputFile: return go(xmlFile, outputFile, outDir, dtdDir) if dtdDir is not None: sys.stderr.write('The ``dtdDir`` option is not yet supported.\n') root = etree.parse(xmlFile).getroot() doc = document.Document(root) doc.filename = xmlInputName # Create a Reportlab canvas by processing the document doc.process(outputFile) def main(args=None): if args is None: parser = argparse.ArgumentParser( prog='rml2pdf', description='Converts file in RML format into PDF file.', epilog='Copyright (c) 2007 Zope Foundation and Contributors.' ) parser.add_argument('xmlInputName', help='RML file to be processed') parser.add_argument( 'outputFileName', nargs='?', help='output PDF file name') parser.add_argument('outDir', nargs='?', help='output directory') parser.add_argument( 'dtdDir', nargs='?', help='directory with XML DTD (not yet supported)') pargs = parser.parse_args() args = ( pargs.xmlInputName, pargs.outputFileName, pargs.outDir, pargs.dtdDir) go(*args) if __name__ == '__main__': canvas = go(sys.argv[1])
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/rml2pdf.py
rml2pdf.py
"""RML to PDF Converter Interfaces """ __docformat__ = "reStructuredText" import collections import logging import reportlab.lib.enums import zope.interface import zope.schema from z3c.rml.occurence import OneOrMore # noqa: F401 imported but unused from z3c.rml.occurence import ZeroOrMore # noqa: F401 imported but unused from z3c.rml.occurence import ZeroOrOne # noqa: F401 imported but unused JOIN_CHOICES = collections.OrderedDict([ ('round', 1), ('mitered', 0), ('bevelled', 2) ]) CAP_CHOICES = collections.OrderedDict([ ('default', 0), ('butt', 0), ('round', 1), ('square', 2) ]) ALIGN_CHOICES = { 'left': reportlab.lib.enums.TA_LEFT, 'right': reportlab.lib.enums.TA_RIGHT, 'center': reportlab.lib.enums.TA_CENTER, 'centre': reportlab.lib.enums.TA_CENTER, 'justify': reportlab.lib.enums.TA_JUSTIFY} ALIGN_TEXT_CHOICES = collections.OrderedDict([ ('left', 'LEFT'), ('right', 'RIGHT'), ('center', 'CENTER'), ('centre', 'CENTER'), ('decimal', 'DECIMAL') ]) VALIGN_TEXT_CHOICES = { 'top': 'TOP', 'middle': 'MIDDLE', 'bottom': 'BOTTOM'} SPLIT_CHOICES = ('splitfirst', 'splitlast') WORD_WRAP_CHOICES = ('CJK', 'RTL', 'LTR') TEXT_TRANSFORM_CHOICES = ('none', 'uppercase', 'lowercase', 'capitalize') TEXT_DECORATION_CHOICES = ('underline', 'strike') UNDERLINE_KIND_CHOICES = ('single', 'double', 'triple') STRIKE_KIND_CHOICES = ('single', 'double', 'triple') BULLET_ANCHOR_CHOICES = ('start', 'middle', 'end', 'numeric') LIST_FORMATS = ('I', 'i', '123', 'ABC', 'abc') ORDERED_LIST_TYPES = ('I', 'i', '1', 'A', 'a', 'l', 'L', 'O', 'o', 'R', 'r') UNORDERED_BULLET_VALUES = ( 'bulletchar', 'bullet', 'circle', 'square', 'disc', 'diamond', 'rarrowhead', 'diamondwx', 'sparkle', 'squarelrs', 'blackstar') LOG_LEVELS = collections.OrderedDict([ ('DEBUG', logging.DEBUG), ('INFO', logging.INFO), ('WARNING', logging.WARNING), ('ERROR', logging.ERROR), ('CRITICAL', logging.CRITICAL), ]) class IRML2PDF(zope.interface.Interface): """This is the main public API of z3c.rml""" def parseString(xml): """Parse an XML string and convert it to PDF. The output is a ``StringIO`` object. """ def go(xmlInputName, outputFileName=None, outDir=None, dtdDir=None): """Convert RML 2 PDF. The generated file will be located in the ``outDir`` under the name ``outputFileName``. """ class IManager(zope.interface.Interface): """A manager of all document-global variables.""" names = zope.interface.Attribute("Names dict") styles = zope.interface.Attribute("Styles dict") colors = zope.interface.Attribute("Colors dict") class IPostProcessorManager(zope.interface.Interface): """Manages all post processors""" postProcessors = zope.interface.Attribute( "List of tuples of the form: (name, processor)") class ICanvasManager(zope.interface.Interface): """A manager for the canvas.""" canvas = zope.interface.Attribute("Canvas") class IRMLDirectiveSignature(zope.interface.Interface): """The attribute and sub-directives signature of the current RML directive.""" class IRMLDirective(zope.interface.Interface): """A directive in RML extracted from an Element Tree element.""" signature = zope.schema.Field( title='Signature', description=('The signature of the RML directive.'), required=True) parent = zope.schema.Field( title='Parent RML Element', description='The parent in the RML element hierarchy', required=True,) element = zope.schema.Field( title='Element', description=('The Element Tree element from which the data ' 'is retrieved.'), required=True) def getAttributeValues(ignore=None, select=None, includeMissing=False): """Return a list of name-value-tuples based on the signature. If ``ignore`` is specified, all attributes are returned except the ones listed in the argument. The values of the sequence are the attribute names. If ``select`` is specified, only attributes listed in the argument are returned. The values of the sequence are the attribute names. If ``includeMissing`` is set to true, then even missing attributes are included in the value list. """ def processSubDirectives(self): """Process all sub-directives.""" def process(self): """Process the directive. The main task for this method is to interpret the available data and to make the corresponding calls in the Reportlab document. This call should also process all sub-directives and process them. """ class IDeprecated(zope.interface.Interface): """Mark an attribute as being compatible.""" deprecatedName = zope.schema.TextLine( title='Name', description='The name of the original attribute.', required=True) deprecatedReason = zope.schema.Text( title='Reason', description='The reason the attribute has been deprecated.', required=False) class IDeprecatedDirective(zope.interface.interfaces.IInterface): """A directive that is deprecated."""
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/interfaces.py
interfaces.py
"""``doc*`` directives. """ import reportlab.platypus from z3c.rml import attr from z3c.rml import directive # noqa: F401 imported but unused from z3c.rml import flowable from z3c.rml import interfaces from z3c.rml import occurence class IDocAssign(interfaces.IRMLDirectiveSignature): """Assign a value to the namesapce.""" var = attr.Text( title='Variable Name', description='The name under which the value is stored.', required=True) expr = attr.Text( title='Expression', description='The expression that creates the value when evaluated.', required=True) class DocAssign(flowable.Flowable): signature = IDocAssign klass = reportlab.platypus.flowables.DocAssign class IDocExec(interfaces.IRMLDirectiveSignature): """Execute a statement.""" stmt = attr.Text( title='Statement', description='The statement to be executed.', required=True) class DocExec(flowable.Flowable): signature = IDocExec klass = reportlab.platypus.flowables.DocExec class IDocPara(interfaces.IRMLDirectiveSignature): """Create a paragraph with the value returned from the expression.""" expr = attr.Text( title='Expression', description='The expression to be executed.', required=True) format = attr.Text( title='Format', description='The format used to render the expression value.', required=False) style = attr.Style( title='Style', description='The style of the paragraph.', required=False) escape = attr.Boolean( title='Escape Text', description='When set (default) the expression value is escaped.', required=False) class DocPara(flowable.Flowable): signature = IDocPara klass = reportlab.platypus.flowables.DocPara class IDocAssert(interfaces.IRMLDirectiveSignature): """Assert a certain condition.""" cond = attr.Text( title='Condition', description='The condition to be asserted.', required=True) format = attr.Text( title='Format', description='The text displayed if assertion fails.', required=False) class DocAssert(flowable.Flowable): signature = IDocAssert klass = reportlab.platypus.flowables.DocAssert class IDocElse(interfaces.IRMLDirectiveSignature): """Starts 'else' block.""" class DocElse(flowable.Flowable): signature = IDocElse def process(self): if not isinstance(self.parent, DocIf): raise ValueError("<docElse> can only be placed inside a <docIf>") self.parent.flow = self.parent.elseFlow class IDocIf(flowable.IFlow): """Display story flow based on the value of the condition.""" cond = attr.Text( title='Condition', description='The condition to be tested.', required=True) class DocIf(flowable.Flow): signature = IDocAssert klass = reportlab.platypus.flowables.DocIf def __init__(self, *args, **kw): super(flowable.Flow, self).__init__(*args, **kw) self.thenFlow = self.flow = [] self.elseFlow = [] def process(self): args = dict(self.getAttributeValues()) self.processSubDirectives() dif = self.klass( thenBlock=self.thenFlow, elseBlock=self.elseFlow, **args) self.parent.flow.append(dif) class IDocWhile(flowable.IFlow): """Repeat the included directives as long as the condition is true.""" cond = attr.Text( title='Condition', description='The condition to be tested.', required=True) class DocWhile(flowable.Flow): signature = IDocAssert klass = reportlab.platypus.flowables.DocWhile def process(self): args = dict(self.getAttributeValues()) self.processSubDirectives() dwhile = self.klass(whileBlock=self.flow, **args) self.parent.flow.append(dwhile) flowable.Flow.factories['docAssign'] = DocAssign flowable.Flow.factories['docExec'] = DocExec flowable.Flow.factories['docPara'] = DocPara flowable.Flow.factories['docAssert'] = DocAssert flowable.Flow.factories['docIf'] = DocIf flowable.Flow.factories['docElse'] = DocElse flowable.Flow.factories['docWhile'] = DocWhile flowable.IFlow.setTaggedValue( 'directives', flowable.IFlow.getTaggedValue('directives') + (occurence.ZeroOrMore('docAssign', IDocAssign), occurence.ZeroOrMore('docExec', IDocExec), occurence.ZeroOrMore('docPara', IDocPara), occurence.ZeroOrMore('docIf', IDocIf), occurence.ZeroOrMore('docElse', IDocElse), occurence.ZeroOrMore('docWhile', IDocWhile), ) )
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/doclogic.py
doclogic.py
"""``pdfInclude`` Directive. """ __docformat__ = "reStructuredText" from reportlab.platypus import flowables from z3c.rml import attr from z3c.rml import flowable from z3c.rml import interfaces from z3c.rml import occurence class StoryPlaceFlowable(flowables.Flowable): def __init__(self, x, y, width, height, origin, flows): flowables.Flowable.__init__(self) self.x = x self.y = y self.width = width self.height = height self.origin = origin self.flows = flows def wrap(self, *args): return (0, 0) def draw(self): x, y = self.x, self.y self.canv.restoreState() if self.origin == 'frame': x += self._frame._x1 y += self._frame._y1 elif self.origin == 'local': x += self._frame._x y += self._frame._y else: # origin == 'page' pass width, height = self.width, self.height y += height for flow in self.flows.flow: flowWidth, flowHeight = flow.wrap(width, height) if flowWidth <= width and flowHeight <= height: y -= flowHeight flow.drawOn(self.canv, x, y) height -= flowHeight else: raise ValueError("Not enough space") self.canv.saveState() class IStoryPlace(interfaces.IRMLDirectiveSignature): """Draws a set of flowables on the canvas within a given region.""" x = attr.Measurement( title='X-Coordinate', description=('The X-coordinate of the lower-left position of the ' 'place.'), required=True) y = attr.Measurement( title='Y-Coordinate', description=('The Y-coordinate of the lower-left position of the ' 'place.'), required=True) width = attr.Measurement( title='Width', description='The width of the place.', required=False) height = attr.Measurement( title='Height', description='The height of the place.', required=False) origin = attr.Choice( title='Origin', description='The origin of the coordinate system for the story.', choices=('page', 'frame', 'local'), default='page', required=False) class StoryPlace(flowable.Flowable): signature = IStoryPlace def process(self): x, y, width, height, origin = self.getAttributeValues( select=('x', 'y', 'width', 'height', 'origin'), valuesOnly=True) flows = flowable.Flow(self.element, self.parent) flows.process() self.parent.flow.append( StoryPlaceFlowable(x, y, width, height, origin, flows)) flowable.Flow.factories['storyPlace'] = StoryPlace flowable.IFlow.setTaggedValue( 'directives', flowable.IFlow.getTaggedValue('directives') + (occurence.ZeroOrMore('storyPlace', IStoryPlace),) )
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/storyplace.py
storyplace.py
"""Chart Element Processing """ import reportlab.lib.formatters from reportlab.graphics import shapes from reportlab.graphics.charts import barcharts from reportlab.graphics.charts import doughnut # noqa: F401 unused from reportlab.graphics.charts import lineplots from reportlab.graphics.charts import piecharts from reportlab.graphics.charts import spider from z3c.rml import attr from z3c.rml import directive from z3c.rml import interfaces from z3c.rml import occurence # Patches against Reportlab 2.0 lineplots.Formatter = reportlab.lib.formatters.Formatter class PropertyItem(directive.RMLDirective): def process(self): attrs = dict(self.getAttributeValues()) self.parent.dataList.append(attrs) class PropertyCollection(directive.RMLDirective): propertyName = None def processAttributes(self): prop = getattr(self.parent.context, self.propertyName) # Get global properties for name, value in self.getAttributeValues(): setattr(prop, name, value) def process(self): self.processAttributes() # Get item specific properties prop = getattr(self.parent.context, self.propertyName) self.dataList = [] self.processSubDirectives() for index, data in enumerate(self.dataList): for name, value in data.items(): setattr(prop[index], name, value) class IText(interfaces.IRMLDirectiveSignature): """Draw a text on the chart.""" x = attr.Measurement( title='X-Coordinate', description=('The X-coordinate of the lower-left position of the ' 'text.'), required=True) y = attr.Measurement( title='Y-Coordinate', description=('The Y-coordinate of the lower-left position of the ' 'text.'), required=True) angle = attr.Float( title='Rotation Angle', description=('The angle about which the text will be rotated.'), required=False) text = attr.TextNode( title='Text', description='The text to be printed.', required=True) fontName = attr.Text( title='Font Name', description='The name of the font.', required=False) fontSize = attr.Measurement( title='Font Size', description='The font size for the text.', required=False) fillColor = attr.Color( title='Fill Color', description='The color in which the text will appear.', required=False) textAnchor = attr.Choice( title='Text Anchor', description='The position in the text to which the coordinates refer.', choices=('start', 'middle', 'end', 'boxauto'), required=False) class Text(directive.RMLDirective): signature = IText def process(self): attrs = dict(self.getAttributeValues()) string = shapes.String( attrs.pop('x'), attrs.pop('y'), attrs.pop('text')) angle = attrs.pop('angle', 0) for name, value in attrs.items(): setattr(string, name, value) group = shapes.Group(string) group.translate(0, 0) group.rotate(angle) self.parent.parent.drawing.add(group) class ITexts(interfaces.IRMLDirectiveSignature): """A set of texts drawn on the chart.""" occurence.containing( occurence.ZeroOrMore('text', IText) ) class Texts(directive.RMLDirective): signature = ITexts factories = {'text': Text} class Series(directive.RMLDirective): def process(self): attrs = self.getAttributeValues(valuesOnly=True) self.parent.data.append(attrs[0]) class Data(directive.RMLDirective): series = None def process(self): self.data = [] self.factories = {'series': self.series} self.processSubDirectives() self.parent.context.data = self.data class ISeries1D(interfaces.IRMLDirectiveSignature): """A one-dimensional series.""" values = attr.TextNodeSequence( title='Values', description="Numerical values representing the series' data.", value_type=attr.Float(), required=True) class Series1D(Series): signature = ISeries1D class IData1D(interfaces.IRMLDirectiveSignature): """A 1-D data set.""" occurence.containing( occurence.OneOrMore('series', ISeries1D) ) class Data1D(Data): signature = IData1D series = Series1D class ISingleData1D(interfaces.IRMLDirectiveSignature): """A 1-D data set.""" occurence.containing( occurence.One('series', ISeries1D) ) class SingleData1D(Data1D): signature = ISingleData1D def process(self): self.data = [] self.factories = {'series': self.series} self.processSubDirectives() self.parent.context.data = self.data[0] class ISeries2D(interfaces.IRMLDirectiveSignature): """A two-dimensional series.""" values = attr.TextNodeGrid( title='Values', description="Numerical values representing the series' data.", value_type=attr.Float(), columns=2, required=True) class Series2D(Series): signature = ISeries2D class IData2D(interfaces.IRMLDirectiveSignature): """A 2-D data set.""" occurence.containing( occurence.OneOrMore('series', ISeries2D) ) class Data2D(Data): signature = IData2D series = Series2D class IBar(interfaces.IRMLDirectiveSignature): """Define the look of a bar.""" strokeColor = attr.Color( title='Stroke Color', description='The color in which the bar border is drawn.', required=False) strokeWidth = attr.Measurement( title='Stroke Width', description='The width of the bar border line.', required=False) fillColor = attr.Color( title='Fill Color', description='The color with which the bar is filled.', required=False) class Bar(PropertyItem): signature = IBar class IBars(IBar): """Collection of bar subscriptions.""" occurence.containing( occurence.ZeroOrMore('bar', IBar) ) class Bars(PropertyCollection): signature = IBars propertyName = 'bars' factories = {'bar': Bar} class ILabelBase(interfaces.IRMLDirectiveSignature): dx = attr.Measurement( title='Horizontal Extension', description=('The width of the label.'), required=False) dy = attr.Measurement( title='Vertical Extension', description=('The height of the label.'), required=False) angle = attr.Float( title='Angle', description=('The angle to rotate the label.'), required=False) boxAnchor = attr.Choice( title='Box Anchor', description=('The position relative to the label.'), choices=( 'nw', 'n', 'ne', 'w', 'c', 'e', 'sw', 's', 'se', 'autox', 'autoy'), required=False) boxStrokeColor = attr.Color( title='Box Stroke Color', description=('The color of the box border line.'), acceptNone=True, required=False) boxStrokeWidth = attr.Measurement( title='Box Stroke Width', description='The width of the box border line.', required=False) boxFillColor = attr.Color( title='Box Fill Color', description=('The color in which the box is filled.'), acceptNone=True, required=False) boxTarget = attr.Text( title='Box Target', description='The box target.', required=False) fillColor = attr.Color( title='Fill Color', description=('The color in which the label is filled.'), required=False) strokeColor = attr.Color( title='Stroke Color', description=('The color of the label.'), required=False) strokeWidth = attr.Measurement( title='Stroke Width', description='The width of the label line.', required=False) fontName = attr.Text( title='Font Name', description='The font used to print the value.', required=False) fontSize = attr.Measurement( title='Font Size', description='The size of the value text.', required=False) leading = attr.Measurement( title='Leading', description=('The height of a single text line. It includes ' 'character height.'), required=False) width = attr.Measurement( title='Width', description='The width the label.', required=False) maxWidth = attr.Measurement( title='Maximum Width', description='The maximum width the label.', required=False) height = attr.Measurement( title='Height', description='The height the label.', required=False) textAnchor = attr.Choice( title='Text Anchor', description='The position in the text to which the coordinates refer.', choices=('start', 'middle', 'end', 'boxauto'), required=False) visible = attr.Boolean( title='Visible', description='A flag making the label text visible.', required=False) leftPadding = attr.Measurement( title='Left Padding', description='The size of the padding on the left side.', required=False) rightPadding = attr.Measurement( title='Right Padding', description='The size of the padding on the right side.', required=False) topPadding = attr.Measurement( title='Top Padding', description='The size of the padding on the top.', required=False) bottomPadding = attr.Measurement( title='Bottom Padding', description='The size of the padding on the bottom.', required=False) class IPositionLabelBase(ILabelBase): x = attr.Measurement( title='X-Coordinate', description=('The X-coordinate of the lower-left position of the ' 'label.'), required=False) y = attr.Measurement( title='Y-Coordinate', description=('The Y-coordinate of the lower-left position of the ' 'label.'), required=False) class ILabel(IPositionLabelBase): """A label for the chart on an axis.""" text = attr.TextNode( title='Text', description='The label text to be displayed.', required=True) class Label(PropertyItem): signature = ILabel class IBarLabels(ILabelBase): """A set of labels for a bar chart""" occurence.containing( occurence.ZeroOrMore('label', ILabel) ) class BarLabels(PropertyCollection): signature = IBarLabels propertyName = 'barLabels' factories = {'label': Label} name = 'barLabels' class ILabels(IPositionLabelBase): """A set of labels of an axis.""" occurence.containing( occurence.ZeroOrMore('label', ILabel) ) class Labels(PropertyCollection): signature = ILabels propertyName = 'labels' factories = {'label': Label} class IAxis(interfaces.IRMLDirectiveSignature): occurence.containing( occurence.ZeroOrMore('labels', ILabels) ) visible = attr.Boolean( title='Visible', description='When true, draw the entire axis with all details.', required=False) visibleAxis = attr.Boolean( title='Visible Axis', description='When true, draw the axis line.', required=False) visibleTicks = attr.Boolean( title='Visible Ticks', description='When true, draw the axis ticks on the line.', required=False) visibleLabels = attr.Boolean( title='Visible Labels', description='When true, draw the axis labels.', required=False) visibleGrid = attr.Boolean( title='Visible Grid', description='When true, draw the grid lines for the axis.', required=False) strokeWidth = attr.Measurement( title='Stroke Width', description='The width of axis line and ticks.', required=False) strokeColor = attr.Color( title='Stroke Color', description='The color in which the axis line and ticks are drawn.', required=False) strokeDashArray = attr.Sequence( title='Stroke Dash Array', description='The dash array that is used for the axis line and ticks.', value_type=attr.Float(), required=False) gridStrokeWidth = attr.Measurement( title='Grid Stroke Width', description='The width of the grid lines.', required=False) gridStrokeColor = attr.Color( title='Grid Stroke Color', description='The color in which the grid lines are drawn.', required=False) gridStrokeDashArray = attr.Sequence( title='Grid Stroke Dash Array', description='The dash array that is used for the grid lines.', value_type=attr.Float(), required=False) gridStart = attr.Measurement( title='Grid Start', description=('The start of the grid lines with respect to the ' 'axis origin.'), required=False) gridEnd = attr.Measurement( title='Grid End', description=('The end of the grid lines with respect to the ' 'axis origin.'), required=False) style = attr.Choice( title='Style', description='The plot style of the common categories.', choices=('parallel', 'stacked', 'parallel_3d'), required=False) class Axis(directive.RMLDirective): signature = IAxis name = '' factories = {'labels': Labels} def process(self): self.context = axis = getattr(self.parent.context, self.name) for name, value in self.getAttributeValues(): setattr(axis, name, value) self.processSubDirectives() class IName(interfaces.IRMLDirectiveSignature): """A category name""" text = attr.TextNode( title='Text', description='The text value that is the name.', required=True) class Name(directive.RMLDirective): signature = IName def process(self): text = self.getAttributeValues(valuesOnly=True)[0] self.parent.names.append(text) class ICategoryNames(interfaces.IRMLDirectiveSignature): """A list of category names.""" occurence.containing( occurence.OneOrMore('name', IName), ) class CategoryNames(directive.RMLDirective): signature = ICategoryNames factories = {'name': Name} def process(self): self.names = [] self.processSubDirectives() self.parent.context.categoryNames = self.names class ICategoryAxis(IAxis): """An axis displaying categories (instead of numerical values).""" occurence.containing( occurence.ZeroOrOne('categoryNames', ICategoryNames), *IAxis.queryTaggedValue('directives', ()) ) categoryNames = attr.Sequence( title='Category Names', description='A simple list of category names.', value_type=attr.Text(), required=False) joinAxis = attr.Boolean( title='Join Axis', description='When true, both axes join together.', required=False) joinAxisPos = attr.Measurement( title='Join Axis Position', description='The position at which the axes should join together.', required=False) reverseDirection = attr.Boolean( title='Reverse Direction', description='A flag to reverse the direction of category names.', required=False) labelAxisMode = attr.Choice( title='Label Axis Mode', description='Defines the relative position of the axis labels.', choices=('high', 'low', 'axis'), required=False) tickShift = attr.Boolean( title='Tick Shift', description=('When true, place the ticks in the center of a ' 'category instead the beginning and end.'), required=False) class CategoryAxis(Axis): signature = ICategoryAxis name = 'categoryAxis' factories = Axis.factories.copy() factories.update({ 'categoryNames': CategoryNames, }) class IXCategoryAxis(ICategoryAxis): """X-Category Axis""" tickUp = attr.Measurement( title='Tick Up', description='Length of tick above the axis line.', required=False) tickDown = attr.Measurement( title='Tick Down', description='Length of tick below the axis line.', required=False) joinAxisMode = attr.Choice( title='Join Axis Mode', description='Mode for connecting axes.', choices=('bottom', 'top', 'value', 'points', 'None'), required=False) class XCategoryAxis(CategoryAxis): signature = IXCategoryAxis class IYCategoryAxis(ICategoryAxis): """Y-Category Axis""" tickLeft = attr.Measurement( title='Tick Left', description='Length of tick left to the axis line.', required=False) tickRight = attr.Measurement( title='Tick Right', description='Length of tick right to the axis line.', required=False) joinAxisMode = attr.Choice( title='Join Axis Mode', description='Mode for connecting axes.', choices=('bottom', 'top', 'value', 'points', 'None'), required=False) class YCategoryAxis(CategoryAxis): signature = IYCategoryAxis class IValueAxis(IAxis): forceZero = attr.Boolean( title='Force Zero', description='When set, the range will contain the origin.', required=False) minimumTickSpacing = attr.Measurement( title='Minimum Tick Spacing', description='The minimum distance between ticks.', required=False) maximumTicks = attr.Integer( title='Maximum Ticks', description='The maximum number of ticks to be shown.', required=False) labelTextFormat = attr.Combination( title='Label Text Format', description=( 'Formatting string or Python path to formatting function for ' 'axis labels.'), value_types=( # Python path to function. attr.ObjectRef(), # Formatting String. attr.Text(), ), required=False) labelTextPostFormat = attr.Text( title='Label Text Post Format', description='An additional formatting string.', required=False) labelTextScale = attr.Float( title='Label Text Scale', description='The sclaing factor for the label tick values.', required=False) valueMin = attr.Float( title='Minimum Value', description='The smallest value on the axis.', required=False) valueMax = attr.Float( title='Maximum Value', description='The largest value on the axis.', required=False) valueStep = attr.Float( title='Value Step', description='The step size between ticks', required=False) valueSteps = attr.Sequence( title='Step Sizes', description='List of step sizes between ticks.', value_type=attr.Float(), required=False) rangeRound = attr.Choice( title='Range Round', description='Method to be used to round the range values.', choices=('none', 'both', 'ceiling', 'floor'), required=False) zrangePref = attr.Float( title='Zero Range Preference', description='Zero range axis limit preference.', required=False) class ValueAxis(Axis): signature = IValueAxis name = 'valueAxis' class IXValueAxis(IValueAxis): """X-Value Axis""" tickUp = attr.Measurement( title='Tick Up', description='Length of tick above the axis line.', required=False) tickDown = attr.Measurement( title='Tick Down', description='Length of tick below the axis line.', required=False) joinAxis = attr.Boolean( title='Join Axis', description='Whether to join the axes.', required=False) joinAxisMode = attr.Choice( title='Join Axis Mode', description='Mode for connecting axes.', choices=('bottom', 'top', 'value', 'points', 'None'), required=False) joinAxisPos = attr.Measurement( title='Join Axis Position', description='The position in the plot at which to join the axes.', required=False) class XValueAxis(ValueAxis): signature = IXValueAxis class LineXValueAxis(XValueAxis): name = 'xValueAxis' class IYValueAxis(IValueAxis): """Y-Value Axis""" tickLeft = attr.Measurement( title='Tick Left', description='Length of tick left to the axis line.', required=False) tickRight = attr.Measurement( title='Tick Right', description='Length of tick right to the axis line.', required=False) joinAxis = attr.Boolean( title='Join Axis', description='Whether to join the axes.', required=False) joinAxisMode = attr.Choice( title='Join Axis Mode', description='Mode for connecting axes.', choices=('bottom', 'top', 'value', 'points', 'None'), required=False) joinAxisPos = attr.Measurement( title='Join Axis Position', description='The position in the plot at which to join the axes.', required=False) class YValueAxis(ValueAxis): signature = IYValueAxis class LineYValueAxis(YValueAxis): name = 'yValueAxis' class ILineLabels(IPositionLabelBase): """A set of labels of an axis.""" occurence.containing( occurence.ZeroOrMore('label', ILabel) ) class LineLabels(PropertyCollection): signature = ILineLabels propertyName = 'lineLabels' factories = {'label': Label} class ILineBase(interfaces.IRMLDirectiveSignature): strokeWidth = attr.Measurement( title='Stroke Width', description='The width of the plot line.', required=False) strokeColor = attr.Color( title='Stroke Color', description='The color of the plot line.', required=False) strokeDashArray = attr.Sequence( title='Stroke Dash Array', description='The dash array of the plot line.', value_type=attr.Float(), required=False) symbol = attr.Symbol( title='Symbol', description='The symbol to be used for every data point in the plot.', required=False) class ILine(ILineBase): """A line description of a series of a line plot.""" name = attr.Text( title='Name', description='The name of the line.', required=False) class Line(PropertyItem): signature = ILine class ILines(ILineBase): """The set of all line descriptions in the line plot.""" occurence.containing( occurence.OneOrMore('line', ILine), ) class Lines(PropertyCollection): signature = ILines propertyName = 'lines' factories = {'line': Line} class ISliceLabel(ILabelBase): """The label of a slice within a bar chart.""" text = attr.TextNode( title='Text', description='The label text to be displayed.', required=True) class SliceLabel(Label): signature = ISliceLabel def process(self): for name, value in self.getAttributeValues(): self.parent.context['label_' + name] = value # Now we do not have simple labels anymore self.parent.parent.parent.context.simpleLabels = False class ISlicePointer(interfaces.IRMLDirectiveSignature): """A pointer to a slice in a pie chart.""" strokeColor = attr.Color( title='Stroke Color', description='The color of the pointer line.', required=False) strokeWidth = attr.Measurement( title='Stroke Width', description='The wodth of the pointer line.', required=False) elbowLength = attr.Measurement( title='Elbow Length', description='The length of the final segment of the pointer.', required=False) edgePad = attr.Measurement( title='Edge Padding', description='The padding between between the pointer label and box.', required=False) piePad = attr.Measurement( title='Pie Padding', description='The padding between between the pointer label and chart.', required=False) class SlicePointer(directive.RMLDirective): signature = ISlicePointer def process(self): for name, value in self.getAttributeValues(): self.parent.context['label_pointer_' + name] = value class ISliceBase(interfaces.IRMLDirectiveSignature): strokeWidth = attr.Measurement( title='Stroke Width', description='The wodth of the slice line.', required=False) fillColor = attr.Color( title='Fill Color', description='The fill color of the slice.', required=False) strokeColor = attr.Color( title='Stroke Color', description='The color of the pointer line.', required=False) strokeDashArray = attr.Sequence( title='Stroke Dash Array', description='Teh dash array of the slice borderline.', value_type=attr.Float(), required=False) popout = attr.Measurement( title='Popout', description='The distance of how much the slice should be popped out.', required=False) fontName = attr.Text( title='Font Name', description='The font name of the label.', required=False) fontSize = attr.Measurement( title='Font Size', description='The font size of the label.', required=False) labelRadius = attr.Measurement( title='Label Radius', description=('The radius at which the label should be placed around ' 'the pie.'), required=False) class ISlice(ISliceBase): """A slice in a pie chart.""" occurence.containing( occurence.ZeroOrOne('label', ISliceLabel), occurence.ZeroOrOne('pointer', ISlicePointer), ) swatchMarker = attr.Symbol( required=False) class Slice(directive.RMLDirective): signature = ISlice factories = { 'label': SliceLabel, 'pointer': SlicePointer} def process(self): self.context = attrs = dict(self.getAttributeValues()) self.processSubDirectives() self.parent.context.append(attrs) class ISlice3D(ISlice): """A 3-D slice of a 3-D pie chart.""" fillColorShaded = attr.Color( title='Fill Color Shade', description='The shade used for the fill color.', required=False) class Slice3D(Slice): signature = ISlice3D factories = {} # Sigh, the 3-D Pie does not support advanced slice labels. :-( # 'label': SliceLabel} class ISlices(ISliceBase): """The collection of all 2-D slice descriptions.""" occurence.containing( occurence.OneOrMore('slice', ISlice), ) class Slices(directive.RMLDirective): signature = ISlices factories = {'slice': Slice} def process(self): # Get global slice properties for name, value in self.getAttributeValues(): setattr(self.parent.context.slices, name, value) # Get slice specific properties self.context = slicesData = [] self.processSubDirectives() for index, sliceData in enumerate(slicesData): for name, value in sliceData.items(): setattr(self.parent.context.slices[index], name, value) class ISlices3D(ISliceBase): """The collection of all 3-D slice descriptions.""" occurence.containing( occurence.OneOrMore('slice', ISlice3D), ) fillColorShaded = attr.Color( required=False) class Slices3D(Slices): signature = ISlices3D factories = {'slice': Slice3D} class ISimpleLabel(IName): """A simple label""" class SimpleLabel(Name): signature = ISimpleLabel class ISimpleLabels(interfaces.IRMLDirectiveSignature): """A set of simple labels for a chart.""" occurence.containing( occurence.OneOrMore('label', ISimpleLabel), ) class SimpleLabels(directive.RMLDirective): signature = ISimpleLabels factories = {'label': Name} def process(self): self.names = [] self.processSubDirectives() self.parent.context.labels = self.names class IStrandBase(interfaces.IRMLDirectiveSignature): strokeWidth = attr.Measurement( title='Stroke Width', description='The line width of the strand.', required=False) fillColor = attr.Color( title='Fill Color', description='The fill color of the strand area.', required=False) strokeColor = attr.Color( title='Stroke Color', description='The color of the strand line.', required=False) strokeDashArray = attr.Sequence( title='Stroke Dash Array', description='The dash array of the strand line.', value_type=attr.Float(), required=False) symbol = attr.Symbol( title='Symbol', description='The symbol to use to mark the strand.', required=False) symbolSize = attr.Measurement( title='Symbol Size', description='The size of the strand symbol.', required=False) class IStrand(IStrandBase): """A strand in the spider diagram""" name = attr.Text( title='Name', description='The name of the strand.', required=False) class Strand(PropertyItem): signature = IStrand class IStrands(IStrand): """A collection of strands.""" occurence.containing( occurence.OneOrMore('strand', IStrand) ) class Strands(PropertyCollection): signature = IStrands propertyName = 'strands' attrs = IStrandBase factories = {'strand': Strand} class IStrandLabelBase(ILabelBase): row = attr.Integer( title='Row', description='The row of the strand label', required=False) col = attr.Integer( title='Column', description='The column of the strand label.', required=False) format = attr.Text( title='Format', description='The format string for the label.', required=False) class IStrandLabel(IStrandLabelBase): """A label for a strand.""" _text = attr.TextNode( title='Text', description='The label text of the strand.', required=False) dR = attr.Float( title='Radial Shift', description='The radial shift of the label.', required=False) class StrandLabel(Label): signature = IStrandLabel class IStrandLabels(IStrandLabelBase): """A set of strand labels.""" occurence.containing( occurence.OneOrMore('label', IStrandLabel) ) class StrandLabels(PropertyCollection): signature = IStrandLabels propertyName = 'strandLabels' factories = {'label': StrandLabel} def process(self): self.processAttributes() # Get item specific properties prop = getattr(self.parent.context, self.propertyName) self.dataList = [] self.processSubDirectives() for data in self.dataList: row = data.pop('row') col = data.pop('col') for name, value in data.items(): setattr(prop[row, col], name, value) class ISpoke(interfaces.IRMLDirectiveSignature): """A spoke in the spider diagram.""" strokeWidth = attr.Measurement( title='Stroke Width', description="The width of the spoke's line.", required=False) fillColor = attr.Color( title='Fill Color', description="The fill color of the spoke's area.", required=False) strokeColor = attr.Color( title='Stroke Color', description='The color of the spoke line.', required=False) strokeDashArray = attr.Sequence( title='Stroke Dash Array', description='The dash array of the spoke line.', value_type=attr.Float(), required=False) labelRadius = attr.Measurement( title='Label Radius', description='The radius of the label arouns the spoke.', required=False) visible = attr.Boolean( title='Visible', description='When true, the spoke line is drawn.', required=False) class Spoke(PropertyItem): signature = ISpoke class ISpokes(ISpoke): """A collection of spokes.""" occurence.containing( occurence.OneOrMore('spoke', ISpoke) ) class Spokes(PropertyCollection): signature = ISpokes propertyName = 'spokes' factories = {'spoke': Spoke} class ISpokeLabelBase(ILabelBase): pass class ISpokeLabel(ISpokeLabelBase): """A label for a spoke.""" _text = attr.TextNode( title='Text', description='The text of the spoke (label).', required=False) class SpokeLabel(Label): signature = ISpokeLabel class ISpokeLabels(ISpokeLabelBase): """A set of spoke labels.""" occurence.containing( occurence.OneOrMore('label', ISpokeLabel) ) class SpokeLabels(PropertyCollection): signature = ISpokeLabels propertyName = 'spokeLabels' factories = {'label': SpokeLabel} class IChart(interfaces.IRMLDirectiveSignature): occurence.containing( occurence.ZeroOrOne('texts', ITexts), ) # Drawing Options dx = attr.Measurement( title='Drawing X-Position', description='The x-position of the entire drawing on the canvas.', required=False) dy = attr.Measurement( title='Drawing Y-Position', description='The y-position of the entire drawing on the canvas.', required=False) dwidth = attr.Measurement( title='Drawing Width', description='The width of the entire drawing', required=False) dheight = attr.Measurement( title='Drawing Height', description='The height of the entire drawing', required=False) angle = attr.Float( title='Angle', description='The orientation of the drawing as an angle in degrees.', required=False) # Plot Area Options x = attr.Measurement( title='Chart X-Position', description='The x-position of the chart within the drawing.', required=False) y = attr.Measurement( title='Chart Y-Position', description='The y-position of the chart within the drawing.', required=False) width = attr.Measurement( title='Chart Width', description='The width of the chart.', required=False) height = attr.Measurement( title='Chart Height', description='The height of the chart.', required=False) strokeColor = attr.Color( title='Stroke Color', description='Color of the chart border.', required=False) strokeWidth = attr.Measurement( title='Stroke Width', description='Width of the chart border.', required=False) fillColor = attr.Color( title='Fill Color', description='Color of the chart interior.', required=False) debug = attr.Boolean( title='Debugging', description='A flag that when set to True turns on debug messages.', required=False) class Chart(directive.RMLDirective): signature = IChart factories = { 'texts': Texts } attrMapping = {} def createChart(self, attributes): raise NotImplementedError def process(self): attrs = dict(self.getAttributeValues(attrMapping=self.attrMapping)) angle = attrs.pop('angle', 0) x, y = attrs.pop('dx'), attrs.pop('dy') self.drawing = shapes.Drawing( attrs.pop('dwidth'), attrs.pop('dheight')) self.context = chart = self.createChart(attrs) self.processSubDirectives() group = shapes.Group(chart) group.translate(0, 0) group.rotate(angle) self.drawing.add(group) manager = attr.getManager(self, interfaces.ICanvasManager) self.drawing.drawOn(manager.canvas, x, y) class IBarChart(IChart): """Creates a two-dimensional bar chart.""" occurence.containing( occurence.One('data', IData1D), occurence.ZeroOrOne('bars', IBars), occurence.ZeroOrOne('categoryAxis', ICategoryAxis), occurence.ZeroOrOne('valueAxis', IValueAxis), occurence.ZeroOrOne('barLabels', IBarLabels), *IChart.queryTaggedValue('directives', ()) ) direction = attr.Choice( title='Direction', description='The direction of the bars within the chart.', choices=('horizontal', 'vertical'), default='horizontal', required=False) useAbsolute = attr.Boolean( title='Use Absolute Spacing', description='Flag to use absolute spacing values.', default=False, required=False) barWidth = attr.Measurement( title='Bar Width', description='The width of an individual bar.', default=10, required=False) groupSpacing = attr.Measurement( title='Group Spacing', description='Width between groups of bars.', default=5, required=False) barSpacing = attr.Measurement( title='Bar Spacing', description='Width between individual bars.', default=0, required=False) barLabelFormat = attr.Text( title='Bar Label Text Format', description='Formatting string for bar labels.', required=False) class BarChart(Chart): signature = IBarChart nameBase = 'BarChart' factories = Chart.factories.copy() factories.update({ 'data': Data1D, 'bars': Bars, 'barLabels': BarLabels, }) def createChart(self, attrs): direction = attrs.pop('direction') # Setup sub-elements based on direction if direction == 'horizontal': self.factories['categoryAxis'] = YCategoryAxis self.factories['valueAxis'] = XValueAxis else: self.factories['categoryAxis'] = XCategoryAxis self.factories['valueAxis'] = YValueAxis # Generate the chart chart = getattr( barcharts, direction.capitalize() + self.nameBase)() for name, value in attrs.items(): setattr(chart, name, value) return chart class IBarChart3D(IBarChart): """Creates a three-dimensional bar chart.""" occurence.containing( *IBarChart.queryTaggedValue('directives', ()) ) thetaX = attr.Float( title='Theta-X', description='Fraction of dx/dz.', required=False) thetaY = attr.Float( title='Theta-Y', description='Fraction of dy/dz.', required=False) zDepth = attr.Measurement( title='Z-Depth', description='Depth of an individual series/bar.', required=False) zSpace = attr.Measurement( title='Z-Space', description='Z-Gap around a series/bar.', required=False) class BarChart3D(BarChart): signature = IBarChart3D nameBase = 'BarChart3D' attrMapping = {'thetaX': 'theta_x', 'thetaY': 'theta_y'} class ILinePlot(IChart): """A line plot.""" occurence.containing( occurence.One('data', IData2D), occurence.ZeroOrOne('lines', ILines), occurence.ZeroOrOne('xValueAxis', IXValueAxis), occurence.ZeroOrOne('yValueAxis', IYValueAxis), occurence.ZeroOrOne('lineLabels', ILineLabels), *IChart.queryTaggedValue('directives', ()) ) reversePlotOrder = attr.Boolean( title='Reverse Plot Order', description='When true, the coordinate system is reversed.', required=False) lineLabelNudge = attr.Measurement( title='Line Label Nudge', description='The distance between the data point and its label.', required=False) lineLabelFormat = attr.Text( title='Line Label Format', description='Formatting string for data point labels.', required=False) joinedLines = attr.Boolean( title='Joined Lines', description='When true, connect all data points with lines.', required=False) inFill = attr.Boolean( title='Name', description=( 'Flag indicating whether the line plot should be filled, ' 'in other words converted to an area chart.'), required=False) class LinePlot(Chart): signature = ILinePlot attrMapping = {'inFill': '_inFill'} factories = Chart.factories.copy() factories.update({ 'data': Data2D, 'lines': Lines, 'xValueAxis': LineXValueAxis, 'yValueAxis': LineYValueAxis, 'lineLabels': LineLabels, }) def createChart(self, attrs): # Generate the chart chart = lineplots.LinePlot() for name, value in attrs.items(): setattr(chart, name, value) return chart class ILinePlot3D(ILinePlot): """Creates a three-dimensional line plot.""" occurence.containing( *ILinePlot.queryTaggedValue('directives', ()) ) thetaX = attr.Float( title='Theta-X', description='Fraction of dx/dz.', required=False) thetaY = attr.Float( title='Theta-Y', description='Fraction of dy/dz.', required=False) zDepth = attr.Measurement( title='Z-Depth', description='Depth of an individual series/bar.', required=False) zSpace = attr.Measurement( title='Z-Space', description='Z-Gap around a series/bar.', required=False) class LinePlot3D(LinePlot): signature = ILinePlot3D nameBase = 'LinePlot3D' attrMapping = {'thetaX': 'theta_x', 'thetaY': 'theta_y'} def createChart(self, attrs): # Generate the chart chart = lineplots.LinePlot3D() for name, value in attrs.items(): setattr(chart, name, value) return chart class IPieChart(IChart): """A pie chart.""" occurence.containing( occurence.One('data', ISingleData1D), occurence.ZeroOrOne('slices', ISlices), occurence.ZeroOrOne('labels', ISimpleLabels), *IChart.queryTaggedValue('directives', ()) ) startAngle = attr.Integer( title='Start Angle', description='The start angle in the chart of the first slice ' 'in degrees.', required=False) direction = attr.Choice( title='Direction', description='The direction in which the pie chart will be built.', choices=('clockwise', 'anticlockwise'), required=False) checkLabelOverlap = attr.Boolean( title='Check Label Overlap', description=('When true, check and attempt to fix standard ' 'label overlaps'), required=False) pointerLabelMode = attr.Choice( title='Pointer Label Mode', description=('The location relative to the slace the label should ' 'be placed.'), choices={'none': None, 'leftright': 'LeftRight', 'leftandright': 'LeftAndRight'}, required=False) sameRadii = attr.Boolean( title='Same Radii', description='When true, make x/y radii the same.', required=False) orderMode = attr.Choice( title='Order Mode', description='', choices=('fixed', 'alternate'), required=False) xradius = attr.Measurement( title='X-Radius', description='The radius of the X-directions', required=False) yradius = attr.Measurement( title='Y-Radius', description='The radius of the Y-directions', required=False) class PieChart(Chart): signature = IPieChart chartClass = piecharts.Pie factories = Chart.factories.copy() factories.update({ 'data': SingleData1D, 'slices': Slices, 'labels': SimpleLabels, }) def createChart(self, attrs): # Generate the chart chart = self.chartClass() for name, value in attrs.items(): setattr(chart, name, value) return chart class IPieChart3D(IPieChart): """A 3-D pie chart.""" occurence.containing( occurence.One('slices', ISlices3D), *IChart.queryTaggedValue('directives', ()) ) perspective = attr.Float( title='Perspsective', description='The flattening parameter.', required=False) depth_3d = attr.Measurement( title='3-D Depth', description='The depth of the pie.', required=False) angle_3d = attr.Float( title='3-D Angle', description='The view angle in the Z-coordinate.', required=False) class PieChart3D(PieChart): signature = IPieChart3D chartClass = piecharts.Pie3d factories = PieChart.factories.copy() factories.update({ 'slices': Slices3D, }) class ISpiderChart(IChart): """A spider chart.""" occurence.containing( occurence.One('data', IData1D), occurence.ZeroOrOne('strands', IStrands), occurence.ZeroOrOne('strandLabels', IStrandLabels), occurence.ZeroOrOne('spokes', ISpokes), occurence.ZeroOrOne('spokeLabels', ISpokeLabels), occurence.ZeroOrOne('labels', ISimpleLabels), *IChart.queryTaggedValue('directives', ()) ) startAngle = attr.Integer( title='Start Angle', description='The start angle in the chart of the first strand ' 'in degrees.', required=False) direction = attr.Choice( title='Direction', description='The direction in which the spider chart will be built.', choices=('clockwise', 'anticlockwise'), required=False) class SpiderChart(Chart): signature = ISpiderChart factories = Chart.factories.copy() factories.update({ 'data': Data1D, 'strands': Strands, 'strandLabels': StrandLabels, 'spokes': Spokes, 'spokeLabels': SpokeLabels, 'labels': SimpleLabels, }) def createChart(self, attrs): # Generate the chart chart = spider.SpiderChart() for name, value in attrs.items(): setattr(chart, name, value) return chart
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/chart.py
chart.py
"""RML to PDF Converter """ import os import subprocess import sys _fileOpen = None def excecuteSubProcess(xmlInputName, outputFileName, testing=None): # set the sys path given from the parent process sysPath = os.environ['Z3CRMLSYSPATH'] sys.path[:] = sysPath.split(';') # now it come the ugly thing, but we need to hook our test changes into # our subprocess. if testing is not None: # set some globals import z3c.rml.attr import z3c.rml.directive global _fileOpen _fileOpen = z3c.rml.attr.File.open def testOpen(img, filename): # cleanup win paths like: # ....\\input\\file:///D:\\trunk\\... if sys.platform[:3].lower() == "win": if filename.startswith('file:///'): filename = filename[len('file:///'):] path = os.path.join(os.path.dirname(xmlInputName), filename) return open(path, 'rb') # override some testing stuff for our tests z3c.rml.attr.File.open = testOpen import z3c.rml.tests.module sys.modules['module'] = z3c.rml.tests.module sys.modules['mymodule'] = z3c.rml.tests.module # import rml and process the pdf from z3c.rml import rml2pdf rml2pdf.go(xmlInputName, outputFileName) if testing is not None: # reset some globals z3c.rml.attr.File.open = _fileOpen del sys.modules['module'] del sys.modules['mymodule'] def goSubProcess(xmlInputName, outputFileName, testing=False): """Processes PDF rendering in a sub process. This method is much slower then the ``go`` method defined in rml2pdf.py because each PDF generation is done in a sub process. But this will make sure, that we do not run into problems. Note, the ReportLab lib is not threadsafe. Use this method from python and it will dispatch the pdf generation to a subprocess. Note: this method does not take care on how much process will started. Probably it's a good idea to use a queue or a global utility which only start a predefined amount of sub processes. """ # get the sys path used for this python process env = os.environ sysPath = ';'.join(sys.path) # set the sys path as env var for the new sub process env['Z3CRMLSYSPATH'] = sysPath py = sys.executable # setup the cmd program = [ py, __file__, 'excecuteSubProcess', xmlInputName, outputFileName] if testing is True: program.append('testing=1') program = " ".join(program) # run the subprocess in the rml input file folder, this will make it easy # to include images. If this doesn't fit, feel free to add a additional # home argument, and let this be the default, ri os.chdir(os.path.dirname(xmlInputName)) # start processing in a sub process, raise exception or return None try: p = subprocess.Popen(program, executable=py, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except Exception as e: raise Exception("Subprocess error: %s" % e) # Do we need to improve the implementation and kill the subprocess which # will fail? ri stdout, stderr = p.communicate() error = stderr if error: raise Exception("Subprocess error: %s" % error) if __name__ == '__main__': if len(sys.argv) == 5: # testing support canvas = excecuteSubProcess(sys.argv[2], sys.argv[3], sys.argv[4]) else: canvas = excecuteSubProcess(sys.argv[2], sys.argv[3])
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/rml2pdfscript.py
rml2pdfscript.py
"""RML Attribute Implementation """ import collections import io import logging import os import re import urllib from importlib import import_module import reportlab.graphics.widgets.markers import reportlab.lib.colors import reportlab.lib.pagesizes import reportlab.lib.styles import reportlab.lib.units import reportlab.lib.utils import zope.interface import zope.schema from lxml import etree from z3c.rml import SampleStyleSheet from z3c.rml import interfaces MISSING = object() logger = logging.getLogger("z3c.rml") def getFileInfo(directive): root = directive while root.parent: root = root.parent # Elements added through API won't have a sourceline if directive.element.sourceline is None: return '(file %s)' % (root.filename) return '(file %s, line %i)' % ( root.filename, directive.element.sourceline) def getManager(context, interface=None): if interface is None: # Avoid circular imports from z3c.rml import interfaces interface = interfaces.IManager # Walk up the path until the manager is found # Using interface.providedBy is much slower because it does many more # checks while ( context is not None and interface not in context.__class__.__dict__.get('__implemented__', {}) ): context = context.parent # If no manager was found, raise an error if context is None: raise ValueError('The manager could not be found.') return context def deprecated(oldName, attr, reason): zope.interface.directlyProvides(attr, interfaces.IDeprecated) attr.deprecatedName = oldName attr.deprecatedReason = reason return attr class RMLAttribute(zope.schema.Field): """An attribute of the RML directive.""" missing_value = MISSING default = MISSING def fromUnicode(self, ustr): """See zope.schema.interfaces.IField""" if self.context is None: raise ValueError('Attribute not bound to a context.') return super().fromUnicode(str(ustr)) def get(self): """See zope.schema.interfaces.IField""" # If the attribute has a deprecated partner and the deprecated name # has been specified, use it. if ( interfaces.IDeprecated.providedBy(self) and self.deprecatedName in self.context.element.attrib ): name = self.deprecatedName logger.warning( 'Deprecated attribute "{}": {} {}'.format( name, self.deprecatedReason, getFileInfo(self.context)) ) else: name = self.__name__ # Extract the value. value = self.context.element.get(name, self.missing_value) # Get the correct default value. if value is self.missing_value: if self.default is not None: return self.default return self.missing_value return self.fromUnicode(value) class BaseChoice(RMLAttribute): choices = {} doLower = True def fromUnicode(self, value): if self.doLower: value = value.lower() if value in self.choices: return self.choices[value] raise ValueError( '{!r} not a valid value for attribute "{}". {}'.format( value, self.__name__, getFileInfo(self.context)) ) class Combination(RMLAttribute): """A combination of several other attribute types.""" def __init__(self, value_types=(), *args, **kw): super().__init__(*args, **kw) self.value_types = value_types @property def element(self): return self.context.element @property def parent(self): return self.context.parent def fromUnicode(self, value): for value_type in self.value_types: bound = value_type.bind(self) try: return bound.fromUnicode(value) except ValueError: pass raise ValueError( f'"{value}" is not a valid value. {getFileInfo(self.context)}' ) class Text(RMLAttribute, zope.schema.Text): """A simple unicode string.""" class Integer(RMLAttribute, zope.schema.Int): """An integer. A minimum and maximum value can be specified.""" # By making min and max simple attributes, we avoid some validation # problems. min = None max = None class Float(RMLAttribute, zope.schema.Float): """An flaoting point. A minimum and maximum value can be specified.""" # By making min and max simple attributes, we avoid some validation # problems. min = None max = None class StringOrInt(RMLAttribute): """A (bytes) string or an integer.""" def fromUnicode(self, value): try: return int(value) except ValueError: return str(value) class Sequence(RMLAttribute, zope.schema._field.AbstractCollection): """A list of values of a specified type.""" splitre = re.compile('[ \t\n,;]+') def __init__(self, splitre=None, *args, **kw): super().__init__(*args, **kw) if splitre is not None: self.splitre = splitre def fromUnicode(self, ustr): if ustr.startswith('(') and ustr.endswith(')'): ustr = ustr[1:-1] ustr = ustr.strip() raw_values = self.splitre.split(ustr) result = [self.value_type.bind(self.context).fromUnicode(raw.strip()) for raw in raw_values] if ( (self.min_length is not None and len(result) < self.min_length) or (self.max_length is not None and len(result) > self.max_length) ): raise ValueError( f'Length of sequence must be at least {self.min_length} ' f'and at most {self.max_length}. {getFileInfo(self.context)}' ) return result class IntegerSequence(Sequence): """A sequence of integers.""" def __init__( self, numberingStartsAt=0, lowerBoundInclusive=True, upperBoundInclusive=True, *args, **kw): super(Sequence, self).__init__(*args, **kw) self.numberingStartsAt = numberingStartsAt self.lowerBoundInclusive = lowerBoundInclusive self.upperBoundInclusive = upperBoundInclusive def fromUnicode(self, ustr): ustr = ustr.strip() pieces = self.splitre.split(ustr) numbers = [] for piece in pieces: # Ignore empty pieces. if not piece: continue # The piece is a range. if '-' in piece: start, end = map(int, piece.split('-')) # Make sure internally numbering starts as 0 start -= self.numberingStartsAt end -= self.numberingStartsAt # Apply lower-bound exclusive. if not self.lowerBoundInclusive: start += 1 # Apply upper-bound inclusive. if self.upperBoundInclusive: end += 1 # Make range lower and upper bound inclusive. numbers.append((start, end)) continue # The piece is just a number value = int(piece) value -= self.numberingStartsAt numbers.append((value, value + 1)) return numbers class Choice(BaseChoice): """A choice of several values. The values are always case-insensitive.""" def __init__(self, choices=None, doLower=True, *args, **kw): super().__init__(*args, **kw) if not isinstance(choices, dict): choices = collections.OrderedDict( [(val.lower() if doLower else val, val) for val in choices]) else: choices = collections.OrderedDict( [(key.lower() if doLower else key, val) for key, val in choices.items()]) self.choices = choices self.doLower = doLower class Boolean(BaseChoice): '''A boolean value. For true the values "true", "yes", and "1" are allowed. For false, the values "false", "no", "1" are allowed. ''' choices = {'true': True, 'false': False, 'yes': True, 'no': False, '1': True, '0': False, } class TextBoolean(BaseChoice): '''A boolean value as text. ReportLab sometimes exposes low-level APIs, so we have to provide values that are directly inserted into the PDF. For "true" the values "true", "yes", and "1" are allowed. For "false", the values "false", "no", "1" are allowed. ''' choices = {'true': 'true', 'false': 'false', 'yes': 'true', 'no': 'false', '1': 'true', '0': 'false', } class BooleanWithDefault(Boolean): '''This is a boolean field that can also receive the value "default".''' choices = Boolean.choices.copy() choices.update({'default': None}) class Measurement(RMLAttribute): '''This field represents a length value. The units "in" (inch), "cm", "mm", and "pt" are allowed. If no units are specified, the value is given in points/pixels. ''' def __init__(self, allowPercentage=False, allowStar=False, *args, **kw): super().__init__(*args, **kw) self.allowPercentage = allowPercentage self.allowStar = allowStar units = [ (re.compile(r'^(-?[0-9\.]+)\s*in$'), reportlab.lib.units.inch), (re.compile(r'^(-?[0-9\.]+)\s*cm$'), reportlab.lib.units.cm), (re.compile(r'^(-?[0-9\.]+)\s*mm$'), reportlab.lib.units.mm), (re.compile(r'^(-?[0-9\.]+)\s*pt$'), 1), (re.compile(r'^(-?[0-9\.]+)\s*$'), 1) ] allowPercentage = False allowStar = False def fromUnicode(self, value): if value == 'None': return None if value == '*' and self.allowStar: return value if value.endswith('%') and self.allowPercentage: return value for unit in self.units: res = unit[0].search(value, 0) if res: return unit[1] * float(res.group(1)) raise ValueError( 'The value {!r} is not a valid measurement. {}'.format( value, getFileInfo(self.context) ) ) class FontSizeRelativeMeasurement(RMLAttribute): """This field is a measurement always relative to the current font size. The units "F", "f" and "L" refer to a multiple of the current font size, while "P" refers to the fractional font size. If no units are specified, the value is given in points/pixels. """ _format = re.compile(r'^\s*(\+?-?[0-9\.]*)\s*(P|L|f|F)?\s*$') def fromUnicode(self, value): if value == 'None': return None # Normalize match = self._format.match(value) if match is None: raise ValueError( 'The value {!r} is not a valid text line measurement.' ' {}'.format(value, getFileInfo(self.context))) number, unit = match.groups() normalized = number if unit is not None: normalized += '*' + unit return normalized class ObjectRef(Text): """This field will return a Python object. The value is a Python path to the object which is being resolved. The sysntax is expected to be ``<path.to.module>.<name>``. """ pythonPath = re.compile(r'^([A-z_][0-9A-z_.]*)\.([A-z_][0-9A-z_]*)$') def __init__(self, doNotResolve=False, *args, **kw): super().__init__(*args, **kw) self.doNotResolve = doNotResolve def fromUnicode(self, value): result = self.pythonPath.match(value) if result is None: raise ValueError( 'The Python path you specified is incorrect. %s' % ( getFileInfo(self.context) ) ) if self.doNotResolve: return value modulePath, objectName = result.groups() try: module = import_module(modulePath) except ImportError: raise ValueError( 'The module you specified was not found: %s' % modulePath) try: object = getattr(module, objectName) except AttributeError: raise ValueError( 'The object you specified was not found: %s' % objectName) return object class File(Text): """This field will return a file object. The value itself can either be a relative or absolute path. Additionally the following syntax is supported: [path.to.python.mpackage]/path/to/file """ packageExtract = re.compile(r'^\[([0-9A-z_.]*)\]/(.*)$') doNotOpen = False doNotModify = False def __init__(self, doNotOpen=False, doNotModify=False, *args, **kw): super().__init__(*args, **kw) self.doNotOpen = doNotOpen self.doNotModify = doNotModify def fromUnicode(self, value): # Check whether the value is of the form: # [<module.path>]/rel/path/image.gif" if value.startswith('['): result = self.packageExtract.match(value) if result is None: raise ValueError( 'The package-path-pair you specified was incorrect. %s' % (getFileInfo(self.context)) ) modulepath, path = result.groups() module = import_module(modulepath) # PEP 420 namespace support means that a module can have # multiple paths for module_path in module.__path__: value = os.path.join(module_path, path) if os.path.exists(value): break # In some cases ReportLab has its own mechanisms for finding a # file. In those cases, the filename should not be modified beyond # module resolution. if self.doNotModify: return value # Under Python 3 all platforms need a protocol for local files if not urllib.parse.urlparse(value).scheme: value = 'file:///' + os.path.abspath(value) # If the file is not to be opened, simply return the path. if self.doNotOpen: return value # Open/Download the file fileObj = reportlab.lib.utils.open_for_read(value) sio = io.BytesIO(fileObj.read()) fileObj.close() sio.seek(0) return sio class Image(File): """Similar to the file File attribute, except that an image is internally expected.""" def __init__(self, onlyOpen=False, *args, **kw): super().__init__(*args, **kw) self.onlyOpen = onlyOpen def fromUnicode(self, value): if value.lower().endswith('.svg') or value.lower().endswith('.svgz'): return self._load_svg(value) fileObj = super().fromUnicode(value) if self.onlyOpen: return fileObj return reportlab.lib.utils.ImageReader(fileObj) def _load_svg(self, value): manager = getManager(self.context) width = self.context.element.get('width') if width is not None: width = Measurement().fromUnicode(width) height = self.context.element.get('height') if height is not None: height = Measurement().fromUnicode(height) preserve = self.context.element.get('preserveAspectRatio') if preserve is not None: preserve = Boolean().fromUnicode(preserve) cache_key = f'{value}-{width}x{height}-{preserve}' if cache_key in manager.svgs: return manager.svgs[cache_key] from gzip import GzipFile from xml.etree import cElementTree from reportlab.graphics import renderPM from svglib.svglib import SvgRenderer fileObj = super().fromUnicode(value) svg = fileObj.getvalue() if svg[:2] == b'\037\213': fileObj = GzipFile(fileobj=fileObj) parser = etree.XMLParser( remove_comments=True, recover=True, resolve_entities=False) svg = cElementTree.parse(fileObj, parser=parser).getroot() renderer = SvgRenderer(value) svg = renderer.render(svg) if preserve: if width is not None or height is not None: if width is not None and height is None: height = svg.height * width / svg.width elif height is not None and width is None: width = svg.width * height / svg.height elif float(width) / height > float(svg.width) / svg.height: width = svg.width * height / svg.height else: height = svg.height * width / svg.width else: if width is None: width = svg.width if height is None: height = svg.height svg.scale(width / svg.width, height / svg.height) svg.width = width svg.height = height svg = renderPM.drawToPIL(svg, dpi=300) svg = reportlab.lib.utils.ImageReader(svg) # A hack to getImageReader through as an open Image when used with # imageAndFlowables svg.read = True manager.svgs[cache_key] = svg return svg class Color(RMLAttribute): """Requires the input of a color. There are several supported formats. Three values in a row are interpreted as RGB value ranging from 0-255. A string is interpreted as a name to a pre-defined color. The 'CMYK()' wrapper around four values represents a CMYK color specification. """ def __init__(self, acceptNone=False, acceptAuto=False, *args, **kw): super().__init__(*args, **kw) self.acceptNone = acceptNone self.acceptAuto = acceptAuto def fromUnicode(self, value): if self.acceptNone and value.lower() == 'none': return None if self.acceptAuto and value.lower() == 'auto': return 'auto' manager = getManager(self.context) if value.startswith('rml:'): value = manager.get_name(value[4:], '#000000') if value in manager.colors: return manager.colors[value] try: return reportlab.lib.colors.toColor(value) except ValueError: raise ValueError( 'The color specification "{}" is not valid. {}'.format( value, getFileInfo(self.context) ) ) def _getStyle(context, value): manager = getManager(context) for styles in (manager.styles, SampleStyleSheet.byName): if value in styles: return styles[value] elif 'style.' + value in styles: return styles['style.' + value] elif value.startswith('style.') and value[6:] in styles: return styles[value[6:]] raise ValueError('Style {!r} could not be found. {}'.format( value, getFileInfo(context))) class Style(Text): """Requires a valid style to be entered. Whether the style is a paragraph, table or box style is irrelevant, except that it has to fit the tag. """ default = SampleStyleSheet.byName['Normal'] def fromUnicode(self, value): return _getStyle(self.context, value) class Padding(Sequence): """This attribute is specific for padding and will produce the proper length of the padding sequence.""" def __init__(self, *args, **kw): kw.update(dict(value_type=Integer(), min_length=1, max_length=4)) super().__init__(*args, **kw) def fromUnicode(self, value): seq = super().fromUnicode(value) # pdfgen does not like a single paddign value. if len(seq) == 1: seq.append(seq[0]) return seq class Symbol(Text): """This attribute should contain the text representation of a symbol to be used.""" def fromUnicode(self, value): return reportlab.graphics.widgets.markers.makeMarker(value) class PageSize(RMLAttribute): """A simple measurement pair that specifies the page size. Optionally you can also specify a the name of a page size, such as A4, letter, or legal. """ sizePair = Sequence(value_type=Measurement()) words = Sequence(value_type=Text()) def fromUnicode(self, value): # First try to get a pair try: return self.sizePair.bind(self.context).fromUnicode(value) except ValueError: pass # Now we try to lookup a name. The following type of combinations must # work: "Letter" "LETTER" "A4 landscape" "letter portrait" words = self.words.bind(self.context).fromUnicode(value) words = [word.lower() for word in words] # First look for the orientation orienter = None for orientation in ('landscape', 'portrait'): if orientation in words: orienter = getattr(reportlab.lib.pagesizes, orientation) words.remove(orientation) # We must have exactely one value left that matches a paper size pagesize = getattr(reportlab.lib.pagesizes, words[0].upper()) # Now do the final touches if orienter: pagesize = orienter(pagesize) return pagesize class TextNode(RMLAttribute): """Return the text content of an element.""" def get(self): if self.context.element.text is None: return '' return str(self.context.element.text).strip() class FirstLevelTextNode(TextNode): """Gets all the text content of an element without traversing into any child-elements.""" def get(self): text = self.context.element.text or '' for child in self.context.element.getchildren(): text += child.tail or '' return text.strip() class TextNodeSequence(Sequence, TextNode): """A sequence of values retrieved from the element's content.""" def get(self): return self.fromUnicode(self.context.element.text) class TextNodeGrid(TextNodeSequence): """A grid/matrix of values retrieved from the element's content. The number of columns is specified for every case, but the number of rows is dynamic. """ def __init__(self, columns=None, *args, **kw): super().__init__(*args, **kw) self.columns = columns def fromUnicode(self, ustr): result = super().fromUnicode(ustr) if len(result) % self.columns != 0: raise ValueError( 'Number of elements must be divisible by %i. %s' % ( self.columns, getFileInfo(self.context) ) ) return [result[i * self.columns:(i + 1) * self.columns] for i in range(len(result) // self.columns)] class RawXMLContent(RMLAttribute): """Retrieve the raw content of an element. Only some special element substitution will be made. """ def __init__(self, *args, **kw): super().__init__(*args, **kw) def get(self): # ReportLab's paragraph parser does not like attributes from other # namespaces; sigh. So we have to improvize. text = etree.tounicode(self.context.element, pretty_print=False) text = text[text.find('>') + 1:text.rfind('<')] return text class XMLContent(RawXMLContent): """Same as 'RawXMLContent', except that the whitespace is normalized.""" def get(self): text = super().get() return text.strip().replace('\t', ' ')
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/attr.py
attr.py
"""RML Reference Generator """ import os import re from xml.sax import saxutils import pygments.token import zope.schema import zope.schema.interfaces from lxml import etree from pygments.lexers import XmlLexer from z3c.rml import __version__ from z3c.rml import attr from z3c.rml import document from z3c.rml import interfaces from z3c.rml import pagetemplate INPUT_URL = ('https://github.com/zopefoundation/z3c.rml/blob/master/src/z3c/' 'rml/tests/input/%s') EXPECTED_URL = ( 'https://github.com/zopefoundation/z3c.rml/blob/master/src/z3c/' 'rml/tests/expected/%s?raw=true') EXAMPLES_DIRECTORY = os.path.join(os.path.dirname(__file__), 'tests', 'input') IGNORE_ATTRIBUTES = ('RMLAttribute', 'BaseChoice') CONTENT_FIELD_TYPES = ( attr.TextNode, attr.TextNodeSequence, attr.TextNodeGrid, attr.RawXMLContent, attr.XMLContent) STYLES_FORMATTING = { pygments.token.Name.Tag: ('<font textColor="red">', '</font>'), pygments.token.Literal.String: ('<font textColor="blue">', '</font>'), } EXAMPLE_NS = 'http://namespaces.zope.org/rml/doc' EXAMPLE_ATTR_NAME = '{%s}example' % EXAMPLE_NS def dedent(rml): spaces = re.findall('\n( *)<', rml) if not spaces: return rml least = min([len(s) for s in spaces if s != '']) return rml.replace('\n' + ' ' * least, '\n') def enforceColumns(rml, columns=80): result = [] for line in rml.split('\n'): if len(line) <= columns: result.append(line) continue # Determine the indentation for all other lines lineStart = re.findall('^( *<[a-zA-Z0-9]+ )', line) lineIndent = 0 if lineStart: lineIndent = len(lineStart[0]) # Create lines having at most the specified number of columns while len(line) > columns: end = line[:columns].rfind(' ') result.append(line[:end]) line = ' ' * lineIndent + line[end + 1:] result.append(line) return '\n'.join(result) def highlightRML(rml): lexer = XmlLexer() styledRml = '' for ttype, token in lexer.get_tokens(rml): start, end = STYLES_FORMATTING.get(ttype, ('', '')) styledRml += start + saxutils.escape(token) + end return styledRml def removeDocAttributes(elem): for name in elem.attrib.keys(): if name.startswith('{' + EXAMPLE_NS + '}'): del elem.attrib[name] for child in elem.getchildren(): removeDocAttributes(child) def getAttributeTypes(): types = [] candidates = sorted(attr.__dict__.items(), key=lambda e: e[0]) for name, candidate in candidates: if not (isinstance(candidate, type) and zope.schema.interfaces.IField.implementedBy(candidate) and name not in IGNORE_ATTRIBUTES): continue types.append({ 'name': name, 'description': candidate.__doc__ }) return types def formatField(field): return field.__class__.__name__ def formatChoice(field): choices = ', '.join([repr(choice) for choice in field.choices.keys()]) return '{} of ({})'.format(field.__class__.__name__, choices) def formatSequence(field): vtFormatter = typeFormatters.get(field.value_type.__class__, formatField) return '{} of {}'.format( field.__class__.__name__, vtFormatter(field.value_type)) def formatGrid(field): vtFormatter = typeFormatters.get(field.value_type.__class__, formatField) return '%s with %i cols of %s' % ( field.__class__.__name__, field.columns, vtFormatter(field.value_type)) def formatCombination(field): vts = [typeFormatters.get(vt.__class__, formatField)(vt) for vt in field.value_types] return '{} of {}'.format(field.__class__.__name__, ', '.join(vts)) typeFormatters = { attr.Choice: formatChoice, attr.Sequence: formatSequence, attr.Combination: formatCombination, attr.TextNodeSequence: formatSequence, attr.TextNodeGrid: formatGrid} def processSignature(name, signature, queue, examples, directives=None): if directives is None: directives = {} # Process this directive if signature not in directives: info = {'name': name, 'description': signature.getDoc(), 'id': str(hash(signature)), 'deprecated': False} # If directive is deprecated, then add some info if interfaces.IDeprecatedDirective.providedBy(signature): info['deprecated'] = True info['reason'] = signature.getTaggedValue('deprecatedReason') attrs = [] content = None for fname, field in zope.schema.getFieldsInOrder(signature): # Handle the case, where the field describes the content typeFormatter = typeFormatters.get(field.__class__, formatField) fieldInfo = { 'name': fname, 'type': typeFormatter(field), 'title': field.title, 'description': field.description, 'required': field.required, 'deprecated': False, } if field.__class__ in CONTENT_FIELD_TYPES: content = fieldInfo else: attrs.append(fieldInfo) # Add a separate entry for the deprecated field if interfaces.IDeprecated.providedBy(field): deprFieldInfo = fieldInfo.copy() deprFieldInfo['deprecated'] = True deprFieldInfo['name'] = field.deprecatedName deprFieldInfo['reason'] = field.deprecatedReason attrs.append(deprFieldInfo) info['attributes'] = attrs info['content'] = content # Examples can be either gotten by interface path or tag name ifacePath = signature.__module__ + '.' + signature.__name__ if ifacePath in examples: info['examples'] = examples[ifacePath] else: info['examples'] = examples.get(name, None) subs = [] for occurence in signature.queryTaggedValue('directives', ()): subs.append({ 'name': occurence.tag, 'occurence': occurence.__class__.__name__, 'deprecated': interfaces.IDeprecatedDirective.providedBy( occurence.signature), 'id': str(hash(occurence.signature)) }) info['sub-directives'] = subs directives[signature] = info # Process Children for occurence in signature.queryTaggedValue('directives', ()): queue.append((occurence.tag, occurence.signature)) def extractExamples(directory): examples = {} for filename in os.listdir(directory): if not filename.endswith('.rml'): continue rmlFile = open(os.path.join(directory, filename), 'rb') root = etree.parse(rmlFile).getroot() elements = root.xpath('//@doc:example/parent::*', namespaces={'doc': EXAMPLE_NS}) # Phase 1: Collect all elements for elem in elements: demoTag = elem.get(EXAMPLE_ATTR_NAME) or elem.tag elemExamples = examples.setdefault(demoTag, []) elemExamples.append({ 'filename': filename, 'line': elem.sourceline, 'element': elem, 'rmlurl': INPUT_URL % filename, 'pdfurl': EXPECTED_URL % (filename[:-4] + '.pdf') }) # Phase 2: Render all elements removeDocAttributes(root) for dirExamples in examples.values(): for example in dirExamples: xml = etree.tounicode(example['element']).strip() xml = re.sub( ' ?xmlns:doc="http://namespaces.zope.org/rml/doc"', '', xml ) xml = dedent(xml) xml = enforceColumns(xml, 80) xml = highlightRML(xml) example['code'] = xml rmlFile.close() return examples def main(outPath=None): examples = extractExamples(EXAMPLES_DIRECTORY) template = pagetemplate.RMLPageTemplateFile('reference.pt') directives = {} queue = [('document', document.IDocument)] while queue: tag, sig = queue.pop() processSignature(tag, sig, queue, examples, directives) directives = sorted(directives.values(), key=lambda d: d['name']) pdf = template( version=__version__, types=getAttributeTypes(), directives=directives) file_ = open(outPath or 'rml-reference.pdf', 'wb') file_.write(pdf) file_.close()
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/reference.py
reference.py
"""Paragraph-internal XML parser extensions. """ import sys import reportlab.lib.fonts import reportlab.lib.styles import reportlab.lib.utils import reportlab.platypus.paragraph import reportlab.platypus.paraparser class ParaFragWrapper(reportlab.platypus.paraparser.ParaFrag): @property def text(self): key = self._get_pass_key() if not hasattr(self, key): setattr(self, key, self._get_text()) return getattr(self, key) @text.setter def text(self, value): key = self._get_pass_key() setattr(self, key, value) def _get_pass_key(self): canvas = self._get_canvas() return '_text_{}_{}'.format( canvas._doctemplate.current_pass, canvas.getPageNumber() ) def _get_canvas(self): canvas = None i = 5 while canvas is None: try: frame = sys._getframe(i) except ValueError: raise Exception( "Can't use <%s> in this location." % self.__tag__) # Guess 1: We're in a paragraph in a story. canvas = frame.f_locals.get('canvas', None) if canvas is None: # Guess 2: We're in a template canvas = frame.f_locals.get('canv', None) if canvas is None: # Guess 3: We're in evalString or namedString canvas = getattr( frame.f_locals.get('self', None), 'canv', None) i += 1 return canvas class PageNumberFragment(ParaFragWrapper): """A fragment whose `text` is computed at access time.""" __tag__ = 'pageNumber' def __init__(self, **attributes): reportlab.platypus.paraparser.ParaFrag.__init__(self, **attributes) self.counting_from = attributes.get('countingFrom', 1) def _get_text(self): canvas = self._get_canvas() return str(canvas.getPageNumber() + int(self.counting_from) - 1) class GetNameFragment(ParaFragWrapper): """A fragment whose `text` is computed at access time.""" __tag__ = 'getName' def __init__(self, **attributes): reportlab.platypus.paraparser.ParaFrag.__init__(self, **attributes) self.id = attributes['id'] self.default = attributes.get('default') def _get_text(self): canvas = self._get_canvas() return canvas.manager.get_name(self.id, self.default) class EvalStringFragment(ParaFragWrapper): """A fragment whose `text` is evaluated at access time.""" __tag__ = 'evalString' def __init__(self, **attributes): reportlab.platypus.paraparser.ParaFrag.__init__(self, **attributes) self.frags = attributes.get('frags', []) def _get_text(self): text = '' for frag in self.frags: if isinstance(frag, str): text += frag else: text += frag.text from z3c.rml.special import do_eval return do_eval(text) class NameFragment(ParaFragWrapper): """A fragment whose attribute `value` is set to a variable.""" __tag__ = 'name' def __init__(self, **attributes): reportlab.platypus.paraparser.ParaFrag.__init__(self, **attributes) def _get_text(self): canvas = self._get_canvas() canvas.manager.names[self.id] = self.value return '' class SpanStyle(reportlab.lib.styles.PropertySet): # Do not specify defaults, so that all attributes can be inherited. defaults = {} class Z3CParagraphParser(reportlab.platypus.paraparser.ParaParser): """Extensions to paragraph-internal XML parsing.""" _lineAttrs = ('color', 'width', 'offset', 'gap', 'kind') def __init__(self, manager, *args, **kwargs): reportlab.platypus.paraparser.ParaParser.__init__( self, *args, **kwargs) self.manager = manager self.in_eval = False def findSpanStyle(self, style): from z3c.rml import attr return attr._getStyle(self.manager, style) def startDynamic(self, attributes, klass): frag = klass(**attributes) frag.__dict__.update(self._stack[-1].__dict__) frag.__tag__ = klass.__tag__ frag.fontName = reportlab.lib.fonts.tt2ps( frag.fontName, frag.bold, frag.italic) if self.in_eval: self._stack[-1].frags.append(frag) else: self.fragList.append(frag) self._stack.append(frag) def endDynamic(self): if not self.in_eval: self._stack.pop() def _apply_underline(self, style): if not getattr(style, 'underline', False): return frag = self._stack[-1] for name in self._lineAttrs: styleName = 'underline' + name.title() if hasattr(style, styleName): setattr(frag, styleName, getattr(style, styleName)) self._new_line('underline') def _apply_strike(self, style): if not getattr(style, 'strike', False): return frag = self._stack[-1] for name in self._lineAttrs: styleName = 'strike' + name.title() if hasattr(style, styleName): setattr(frag, styleName, getattr(style, styleName)) self._new_line('strike') def _apply_texttransform(self, style): if not getattr(style, 'textTransform', False): return frag = self._stack[-1] if hasattr(frag, 'text'): frag.textTransform = style.textTransform def start_span(self, attr): reportlab.platypus.paraparser.ParaParser.start_span(self, attr) self._stack[-1]._style = None attrs = self.getAttributes( attr, reportlab.platypus.paraparser._spanAttrMap) if 'style' not in attrs: return style = self.findSpanStyle(attrs.pop('style')) self._stack[-1]._style = style self._apply_underline(style) self._apply_strike(style) self._apply_texttransform(style) def start_para(self, attr): reportlab.platypus.paraparser.ParaParser.start_para(self, attr) self._apply_underline(self._style) self._apply_strike(self._style) def start_pagenumber(self, attributes): self.startDynamic(attributes, PageNumberFragment) def end_pagenumber(self): self.endDynamic() def start_getname(self, attributes): self.startDynamic(attributes, GetNameFragment) def end_getname(self): self.endDynamic() def start_name(self, attributes): self.startDynamic(attributes, NameFragment) def end_name(self): self.endDynamic() def start_evalstring(self, attributes): self.startDynamic(attributes, EvalStringFragment) self.in_eval = True def end_evalstring(self): self.in_eval = False self.endDynamic() def handle_data(self, data): if not self.in_eval: reportlab.platypus.paraparser.ParaParser.handle_data(self, data) else: self._stack[-1].frags.append(data) class Z3CParagraph(reportlab.platypus.paragraph.Paragraph): """Support for custom paraparser with sytles knowledge. Methods mostly copied from reportlab. """ def __init__(self, text, style, bulletText=None, frags=None, caseSensitive=1, encoding='utf8', manager=None): self.caseSensitive = caseSensitive self.encoding = encoding self._setup( text, style, bulletText or getattr(style, 'bulletText', None), frags, reportlab.platypus.paragraph.cleanBlockQuotedText, manager) def _setup(self, text, style, bulletText, frags, cleaner, manager): # This used to be a global parser to save overhead. In the interests # of thread safety it is being instantiated per paragraph. On the # next release, we'll replace with a cElementTree parser if frags is None: text = cleaner(text) _parser = Z3CParagraphParser(manager) _parser.caseSensitive = self.caseSensitive style, frags, bulletTextFrags = _parser.parse(text, style) if frags is None: raise ValueError( "xml parser error (%s) in paragraph beginning\n'%s'" % (_parser.errors[0], text[:min(30, len(text))])) # apply texttransform to paragraphs reportlab.platypus.paragraph.textTransformFrags(frags, style) # apply texttransform to paragraph fragments for frag in frags: if hasattr(frag, '_style') \ and hasattr(frag._style, 'textTransform'): reportlab.platypus.paragraph.textTransformFrags( [frag], frag._style) if bulletTextFrags: bulletText = bulletTextFrags # AR hack self.text = text self.frags = frags # either the parse fragments or frag word list self.style = style self.bulletText = bulletText self.debug = 0 def breakLines(self, *args, **kwargs): # ReportLab 3.4.0 introduced caching to Paragraph which breaks how # we've implemented lookaheads. To get around it we need to bust the # cache when dynamic tags are used. unprocessed_frags = self.frags bust_cache = any(isinstance(f, ParaFragWrapper) for f in self.frags) result = super().breakLines(*args, **kwargs) if bust_cache: self.frags = unprocessed_frags return result class ImageReader(reportlab.lib.utils.ImageReader): def __init__(self, fileName, ident=None): if isinstance(fileName, str): # Avoid circular imports. The filename resolutions hould be added # to a utility module. from z3c.rml import attr _srcAttr = attr.File(doNotOpen=True) fileName = _srcAttr.fromUnicode(fileName) return super().__init__(fileName, ident) # Monkey Patch reportlab image reader, so that <img> tags inside paragraphs # can also benefit from package-local file paths. reportlab.platypus.paraparser.ImageReader = ImageReader
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/paraparser.py
paraparser.py
========================= Reportlab Markup Language ========================= This package is a free implementation of the RML markup language developed by Reportlab. Unfortunately, full compliance cannot be immediately verified, since the RML User Guide is ambiguous, incomplete and even incorrect. This package can also not support the commercial extensions to Reportlab. In the course of implementing the specification, I made already some improvements for various tags and added others fully. I also tried hard to test all features. If you have any new sample RML files that you would like to share, please check them in. Why reimplement RML? The other free implementation of RML tinyRML is unfortunately pretty messy code and hard to debug. It makes it also hard to add additional tags. However, much thanks goes to their authors, since they have solved some of the very tricky issues.
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/README.txt
README.txt
"""Page Drawing Related Element Processing """ import io from z3c.rml import attr from z3c.rml import directive from z3c.rml import interfaces try: import pikepdf from pikepdf import Object # noqa: F401 imported but unused except ImportError: # We don't want to require pikepdf, if you do not want to use the features # in this module. pikepdf = None def mergePage(layerPage, mainPage, pdf, name) -> None: contentsForName = pdf.copy_foreign( pikepdf.Page(layerPage).as_form_xobject() ) newContents = b'q\n %s Do\nQ\n' % (name.encode()) if not mainPage.Resources.get("/XObject"): mainPage.Resources["/XObject"] = pikepdf.Dictionary({}) mainPage.Resources["/XObject"][name] = contentsForName # Use the MediaBox from the merged page mainPage.MediaBox = pikepdf.Array(layerPage.MediaBox) mainPage.contents_add( contents=pikepdf.Stream(pdf, newContents), prepend=True ) class MergePostProcessor: def __init__(self): self.operations = {} def process(self, inputFile1): input1 = pikepdf.open(inputFile1) count = 0 for (num, page) in enumerate(input1.pages): if num in self.operations: for mergeFile, mergeNumber in self.operations[num]: mergePdf = pikepdf.open(mergeFile) toMerge = mergePdf.pages[mergeNumber] name = f"/Fx{count}" mergePage(toMerge, page, input1, name) outputFile = io.BytesIO() input1.save(outputFile) return outputFile class IMergePage(interfaces.IRMLDirectiveSignature): """Merges an existing PDF Page into the one to be generated.""" filename = attr.File( title='File', description=('Reference to the PDF file to extract the page from.'), required=True) page = attr.Integer( title='Page Number', description='The page number of the PDF file that is used to merge..', required=True) class MergePage(directive.RMLDirective): signature = IMergePage def getProcessor(self): manager = attr.getManager(self, interfaces.IPostProcessorManager) procs = dict(manager.postProcessors) if 'MERGE' not in procs: proc = MergePostProcessor() manager.postProcessors.append(('MERGE', proc)) return proc return procs['MERGE'] def process(self): if pikepdf is None: raise Exception( 'pikepdf is not installed, so this feature is not available.') inputFile, inPage = self.getAttributeValues(valuesOnly=True) manager = attr.getManager(self, interfaces.ICanvasManager) outPage = manager.canvas.getPageNumber() - 1 proc = self.getProcessor() pageOperations = proc.operations.setdefault(outPage, []) pageOperations.append((inputFile, inPage)) class MergePageInPageTemplate(MergePage): def process(self): if pikepdf is None: raise Exception( 'pikepdf is not installed, so this feature is not available.') inputFile, inPage = self.getAttributeValues(valuesOnly=True) onPage = self.parent.pt.onPage def drawOnCanvas(canvas, doc): onPage(canvas, doc) outPage = canvas.getPageNumber() - 1 proc = self.getProcessor() pageOperations = proc.operations.setdefault(outPage, []) pageOperations.append((inputFile, inPage)) self.parent.pt.onPage = drawOnCanvas
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/page.py
page.py
"""Number to Words converter. """ __docformat__ = "reStructuredText" import math def toOrdinal(num): str_num = str(num) str_num += "tsnrhtdd"[(num / 10 % 10 != 1) * (num % 10 < 4) * num % 10::4] return str_num class Number2Words: units = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ] units_ordinal = [ "zeroth", "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth", "sixteenth", "seventeenth", "eighteenth", "nineteenth", ] tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] tens_ordinal = ["", "", "twentieth", "thirtieth", "fortieth", "fiftieth", "sixtieth", "seventieth", "eightieth", "ninetieth"] scales = ["", "", "hundred", "thousand", "", "", "million", "", "", "billion", "", "", "trillion"] def __call__(self, num, as_list=False, ordinal=False): num_str = str(num) num_left = num_str words = [] while num_left: if int(num_left) < 20: if int(num_left) != 0 or not len(words): words.append(self.units[int(num_left)]) break if int(num_left) < 100: words.append(self.tens[int(num_left[0])]) num_left = num_left[1:] elif int(num_left) < 1000: scale = self.scales[len(num_left) - 1] digit = int(num_left[0]) if digit != 0: words.append(self.units[digit]) words.append(scale) num_left = num_left[1:] else: mag = int(math.log10(int(num_left)) / 3) * 3 words += self(num_left[:-mag], True) + [self.scales[mag]] num_left = num_left[-mag:] if ordinal: if words[-1] in self.units: words[-1] = self.units_ordinal[self.units.index(words[-1])] elif words[-1] in self.tens: words[-1] = self.tens_ordinal[self.tens.index(words[-1])] elif words[-1] in self.scales: words[-1] += 'th' words = [w.title() for w in words if w != ''] if as_list: return words # two digit numbers require dashes if len(words) > 1: result = [] tens = {w.title() for w in self.tens} units = {w.title() for w in self.units + self.units_ordinal} while words: cur = words.pop(0) if cur in tens and words[0] in units: ones = words.pop(0) result.append(f'{cur}-{ones}') else: result.append(cur) words = result return ' '.join(words) num2words = Number2Words()
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/num2words.py
num2words.py
"""Condition Implementation """ import sys import reportlab import zope.interface import zope.schema from zope.schema import fieldproperty class ICondition(zope.interface.Interface): """Condition that is checked before a directive is available.""" __doc__ = zope.schema.TextLine( title='Description', description='The description of the condition.', required=True) def __call__(directive): """Check whether the condition is fulfilled for the given directive.""" class IOccurence(zope.interface.Interface): """Description of the occurence of a sub-directive.""" __doc__ = zope.schema.TextLine( title='Description', description='The description of the occurence.', required=True) tag = zope.schema.TextLine( title='Tag', description='The tag of the sub-directive within the directive', required=True) signature = zope.schema.Field( title='Signature', description='The signature of the sub-directive.', required=True) condition = zope.schema.Field( title='Condition', description='The condition that the directive is available.', required=False) @zope.interface.implementer(ICondition) def laterThanReportlab21(directive): """The directive is only available in Reportlab 2.1 and higher.""" return [int(num) for num in reportlab.Version.split('.')] >= (2, 0) def containing(*occurences): frame = sys._getframe(1) f_locals = frame.f_locals f_globals = frame.f_globals if not (f_locals is not f_globals and f_locals.get('__module__') and f_locals.get('__module__') == f_globals.get('__name__') ): raise TypeError("contains not called from signature interface") f_locals['__interface_tagged_values__'] = {'directives': occurences} @zope.interface.implementer(IOccurence) class Occurence: tag = fieldproperty.FieldProperty(IOccurence['tag']) signature = fieldproperty.FieldProperty(IOccurence['signature']) condition = fieldproperty.FieldProperty(IOccurence['condition']) def __init__(self, tag, signature, condition=None): self.tag = tag self.signature = signature self.condition = condition class ZeroOrMore(Occurence): """Zero or More This sub-directive can occur zero or more times. """ class ZeroOrOne(Occurence): """Zero or one This sub-directive can occur zero or one time. """ class OneOrMore(Occurence): """One or More This sub-directive can occur one or more times. """ class One(Occurence): """One This sub-directive must occur exactly one time. """
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/occurence.py
occurence.py
"""Style Related Element Processing """ import copy import reportlab.lib.enums import reportlab.lib.styles import reportlab.platypus from z3c.rml import SampleStyleSheet from z3c.rml import attr from z3c.rml import directive from z3c.rml import interfaces from z3c.rml import occurence from z3c.rml import paraparser from z3c.rml import special class IInitialize(interfaces.IRMLDirectiveSignature): """Do some RML processing initialization.""" occurence.containing( occurence.ZeroOrMore('name', special.IName), occurence.ZeroOrMore('alias', special.IAlias), ) class Initialize(directive.RMLDirective): signature = IInitialize factories = { 'name': special.Name, 'alias': special.Alias, } class ISpanStyle(interfaces.IRMLDirectiveSignature): """Defines a span style and gives it a name.""" name = attr.Text( title='Name', description='The name of the style.', required=True) alias = attr.Text( title='Alias', description='An alias under which the style will also be known as.', required=False) parent = attr.Style( title='Parent', description=('The apragraph style that will be used as a base for ' 'this one.'), required=False) fontName = attr.Text( title='Font Name', description='The name of the font for the span.', required=False) fontSize = attr.Measurement( title='Font Size', description='The font size for the text of the span.', required=False) textTransform = attr.Choice( title='Text Transform', description='Text transformation.', choices=interfaces.TEXT_TRANSFORM_CHOICES, required=False) underline = attr.Boolean( title='Underline Text', description='A flag, when set, causes text to be underlined.', required=False) underlineColor = attr.Color( title='Underline Color', description='The color in which the underline will appear.', required=False) underlineWidth = attr.FontSizeRelativeMeasurement( title='Underline Width', description=('The width/thickness of the underline.'), required=False) underlineOffset = attr.FontSizeRelativeMeasurement( title='Underline Offset', description=( 'The offset of the underline with respect to the baseline.'), required=False) underlineGap = attr.FontSizeRelativeMeasurement( title='Underline Gap', description='The gap between lines for double and triple underlines.', required=False) underlineKind = attr.Choice( title='Underline Kind', description=('The kind of the underline to use.'), choices=interfaces.UNDERLINE_KIND_CHOICES, default='single', required=False) strike = attr.Boolean( title='Strike-through Text', description='A flag, when set, causes text to be struck out.', required=False) strikeColor = attr.Color( title='Strike Color', description='The color in which the strike line will appear.', required=False) strikeWidth = attr.FontSizeRelativeMeasurement( title='Strike Width', description=('The width of the strike line.'), required=False) strikeOffset = attr.FontSizeRelativeMeasurement( title='Strike Offset', description=( 'The offset of the strike line with respect to the baseline.'), required=False) strikeGap = attr.FontSizeRelativeMeasurement( title='Strike Gap', description=( 'The gap between lines for double and triple strike lines.'), required=False) strikeKind = attr.Choice( title='Strike Kind', description=('The kind of the strike to use.'), choices=interfaces.STRIKE_KIND_CHOICES, default='single', required=False) textColor = attr.Color( title='Text Color', description='The color in which the text will appear.', required=False) backColor = attr.Color( title='Background Color', description='The background color of the span.', required=False) linkUnderline = attr.Boolean( title='Underline Links', description=( 'A flag, when set indicating that all links should be ' 'underlined.'), default=False, required=False) class SpanStyle(directive.RMLDirective): signature = ISpanStyle def process(self): kwargs = dict(self.getAttributeValues()) parent = kwargs.pop('parent', paraparser.SpanStyle('DefaultSpan')) name = kwargs.pop('name') style = copy.deepcopy(parent) style.name = name[6:] if name.startswith('style.') else name for name, value in kwargs.items(): setattr(style, name, value) manager = attr.getManager(self) manager.styles[style.name] = style class IBaseParagraphStyle(ISpanStyle): leading = attr.Measurement( title='Leading', description=('The height of a single paragraph line. It includes ' 'character height.'), required=False) leftIndent = attr.Measurement( title='Left Indentation', description='General indentation on the left side.', required=False) rightIndent = attr.Measurement( title='Right Indentation', description='General indentation on the right side.', required=False) firstLineIndent = attr.Measurement( title='First Line Indentation', description='The indentation of the first line in the paragraph.', required=False) alignment = attr.Choice( title='Alignment', description='The text alignment.', choices=interfaces.ALIGN_CHOICES, required=False) spaceBefore = attr.Measurement( title='Space Before', description='The vertical space before the paragraph.', required=False) spaceAfter = attr.Measurement( title='Space After', description='The vertical space after the paragraph.', required=False) bulletFontName = attr.Text( title='Bullet Font Name', description='The font in which the bullet character will be rendered.', required=False) bulletFontSize = attr.Measurement( title='Bullet Font Size', description='The font size of the bullet character.', required=False) bulletIndent = attr.Measurement( title='Bullet Indentation', description='The indentation that is kept for a bullet point.', required=False) bulletColor = attr.Color( title='Bullet Color', description='The color in which the bullet will appear.', required=False) wordWrap = attr.Choice( title='Word Wrap Method', description=( 'When set to "CJK", invoke CJK word wrapping. LTR RTL use ' 'left to right / right to left with support from pyfribi2 if ' 'available'), choices=interfaces.WORD_WRAP_CHOICES, required=False) borderWidth = attr.Measurement( title='Paragraph Border Width', description='The width of the paragraph border.', required=False) borderPadding = attr.Padding( title='Paragraph Border Padding', description='Padding of the paragraph.', required=False) borderColor = attr.Color( title='Border Color', description='The color in which the paragraph border will appear.', required=False) borderRadius = attr.Measurement( title='Paragraph Border Radius', description='The radius of the paragraph border.', required=False) allowWidows = attr.Boolean( title='Allow Widows', description=('Allow widows.'), required=False) allowOrphans = attr.Boolean( title='Allow Orphans', description=('Allow orphans.'), required=False) endDots = attr.Text( title='End Dots', description='Characters/Dots at the end of a paragraph.', required=False) splitLongWords = attr.Boolean( title='Split Long Words', description=('Try to split long words at the end of a line.'), default=True, required=False) justifyLastLine = attr.Integer( title='Justify Last Line', description=( 'Justify last line if there are more then this number of words. ' 'Otherwise, don\'t bother.'), default=0, required=False) justifyBreaks = attr.Boolean( title='Justify Breaks', description=( 'A flag, when set indicates that a line with a break should be ' 'justified as well.'), default=False, required=False) spaceShrinkage = attr.Float( title='Allowed Whitespace Shrinkage Fraction', description=( 'The fraction of the original whitespace by which the ' 'whitespace is allowed to shrink to fit content on the same ' 'line.'), required=False) bulletAnchor = attr.Choice( title='Bullet Anchor', description='The place at which the bullet is anchored.', choices=interfaces.BULLET_ANCHOR_CHOICES, default='start', required=False) # Attributes not part of the official style attributes, but are accessed # by the paragraph renderer. keepWithNext = attr.Boolean( title='Keep with Next', description=('When set, this paragraph will always be in the same ' 'frame as the following flowable.'), required=False) pageBreakBefore = attr.Boolean( title='Page Break Before', description=('Specifies whether a page break should be inserted ' 'before the directive.'), required=False) frameBreakBefore = attr.Boolean( title='Frame Break Before', description=('Specifies whether a frame break should be inserted ' 'before the directive.'), required=False) class IParagraphStyle(IBaseParagraphStyle): """Defines a paragraph style and gives it a name.""" name = attr.Text( title='Name', description='The name of the style.', required=True) alias = attr.Text( title='Alias', description='An alias under which the style will also be known as.', required=False) parent = attr.Style( title='Parent', description=('The apragraph style that will be used as a base for ' 'this one.'), required=False) class ParagraphStyle(directive.RMLDirective): signature = IParagraphStyle def process(self): kwargs = dict(self.getAttributeValues()) parent = kwargs.pop( 'parent', SampleStyleSheet['Normal']) name = kwargs.pop('name') style = copy.deepcopy(parent) style.name = name[6:] if name.startswith('style.') else name for name, value in kwargs.items(): setattr(style, name, value) manager = attr.getManager(self) manager.styles[style.name] = style class ITableStyleCommand(interfaces.IRMLDirectiveSignature): start = attr.Sequence( title='Start Coordinates', description='The start table coordinates for the style instruction', value_type=attr.Combination( value_types=(attr.Integer(), attr.Choice(choices=interfaces.SPLIT_CHOICES)) ), default=[0, 0], min_length=2, max_length=2, required=True) stop = attr.Sequence( title='End Coordinates', description='The end table coordinates for the style instruction', value_type=attr.Combination( value_types=(attr.Integer(), attr.Choice(choices=interfaces.SPLIT_CHOICES)) ), default=[-1, -1], min_length=2, max_length=2, required=True) class TableStyleCommand(directive.RMLDirective): name = None def process(self): args = [self.name] args += self.getAttributeValues(valuesOnly=True) self.parent.style.add(*args) class IBlockFont(ITableStyleCommand): """Set the font properties for the texts.""" name = attr.Text( title='Font Name', description='The name of the font for the cell.', required=False) size = attr.Measurement( title='Font Size', description='The font size for the text of the cell.', required=False) leading = attr.Measurement( title='Leading', description=('The height of a single text line. It includes ' 'character height.'), required=False) class BlockFont(TableStyleCommand): signature = IBlockFont name = 'FONT' class IBlockLeading(ITableStyleCommand): """Set the text leading.""" length = attr.Measurement( title='Length', description=('The height of a single text line. It includes ' 'character height.'), required=True) class BlockLeading(TableStyleCommand): signature = IBlockLeading name = 'LEADING' class IBlockTextColor(ITableStyleCommand): """Set the text color.""" colorName = attr.Color( title='Color Name', description='The color in which the text will appear.', required=True) class BlockTextColor(TableStyleCommand): signature = IBlockTextColor name = 'TEXTCOLOR' class IBlockAlignment(ITableStyleCommand): """Set the text alignment.""" value = attr.Choice( title='Text Alignment', description='The text alignment within the cell.', choices=interfaces.ALIGN_TEXT_CHOICES, required=True) class BlockAlignment(TableStyleCommand): signature = IBlockAlignment name = 'ALIGNMENT' class IBlockLeftPadding(ITableStyleCommand): """Set the left padding of the cells.""" length = attr.Measurement( title='Length', description='The size of the padding.', required=True) class BlockLeftPadding(TableStyleCommand): signature = IBlockLeftPadding name = 'LEFTPADDING' class IBlockRightPadding(ITableStyleCommand): """Set the right padding of the cells.""" length = attr.Measurement( title='Length', description='The size of the padding.', required=True) class BlockRightPadding(TableStyleCommand): signature = IBlockRightPadding name = 'RIGHTPADDING' class IBlockBottomPadding(ITableStyleCommand): """Set the bottom padding of the cells.""" length = attr.Measurement( title='Length', description='The size of the padding.', required=True) class BlockBottomPadding(TableStyleCommand): signature = IBlockBottomPadding name = 'BOTTOMPADDING' class IBlockTopPadding(ITableStyleCommand): """Set the top padding of the cells.""" length = attr.Measurement( title='Length', description='The size of the padding.', required=True) class BlockTopPadding(TableStyleCommand): signature = IBlockTopPadding name = 'TOPPADDING' class IBlockBackground(ITableStyleCommand): """Define the background color of the cells. It also supports alternating colors. """ colorName = attr.Color( title='Color Name', description='The color to use as the background for every cell.', required=False) colorsByRow = attr.Sequence( title='Colors By Row', description='A list of colors to be used circularly for rows.', value_type=attr.Color(acceptNone=True), required=False) colorsByCol = attr.Sequence( title='Colors By Column', description='A list of colors to be used circularly for columns.', value_type=attr.Color(acceptNone=True), required=False) class BlockBackground(TableStyleCommand): signature = IBlockBackground name = 'BACKGROUND' def process(self): args = [self.name] if 'colorsByRow' in self.element.keys(): args = [BlockRowBackground.name] elif 'colorsByCol' in self.element.keys(): args = [BlockColBackground.name] args += self.getAttributeValues(valuesOnly=True) self.parent.style.add(*args) class IBlockRowBackground(ITableStyleCommand): """Define the background colors for rows.""" colorNames = attr.Sequence( title='Colors By Row', description='A list of colors to be used circularly for rows.', value_type=attr.Color(), required=True) class BlockRowBackground(TableStyleCommand): signature = IBlockRowBackground name = 'ROWBACKGROUNDS' class IBlockColBackground(ITableStyleCommand): """Define the background colors for columns.""" colorNames = attr.Sequence( title='Colors By Row', description='A list of colors to be used circularly for rows.', value_type=attr.Color(), required=True) class BlockColBackground(TableStyleCommand): signature = IBlockColBackground name = 'COLBACKGROUNDS' class IBlockValign(ITableStyleCommand): """Define the vertical alignment of the cells.""" value = attr.Choice( title='Vertical Alignment', description='The vertical alignment of the text with the cells.', choices=interfaces.VALIGN_TEXT_CHOICES, required=True) class BlockValign(TableStyleCommand): signature = IBlockValign name = 'VALIGN' class IBlockSpan(ITableStyleCommand): """Define a span over multiple cells (rows and columns).""" class BlockSpan(TableStyleCommand): signature = IBlockSpan name = 'SPAN' class IBlockNosplit(ITableStyleCommand): """Define a nosplit over multiple cells (rows and columns).""" class BlockNosplit(TableStyleCommand): signature = IBlockNosplit name = 'NOSPLIT' class ILineStyle(ITableStyleCommand): """Define the border line style of each cell.""" kind = attr.Choice( title='Kind', description='The kind of line actions to be taken.', choices=('GRID', 'BOX', 'OUTLINE', 'INNERGRID', 'LINEBELOW', 'LINEABOVE', 'LINEBEFORE', 'LINEAFTER'), required=True) thickness = attr.Measurement( title='Thickness', description='Line Thickness', default=1, required=True) colorName = attr.Color( title='Color', description='The color of the border line.', default=None, required=True) cap = attr.Choice( title='Cap', description='The cap at the end of a border line.', choices=interfaces.CAP_CHOICES, default=1, required=True) dash = attr.Sequence( title='Dash-Pattern', description='The dash-pattern of a line.', value_type=attr.Measurement(), default=None, required=False) join = attr.Choice( title='Join', description='The way lines are joined together.', choices=interfaces.JOIN_CHOICES, default=1, required=False) count = attr.Integer( title='Count', description=('Describes whether the line is a single (1) or ' 'double (2) line.'), default=1, required=False) class LineStyle(TableStyleCommand): signature = ILineStyle def process(self): name = self.getAttributeValues(select=('kind',), valuesOnly=True)[0] args = [name] args += self.getAttributeValues(ignore=('kind',), valuesOnly=True, includeMissing=True) args = [val if val is not attr.MISSING else None for val in args] self.parent.style.add(*args) class IBlockTableStyle(interfaces.IRMLDirectiveSignature): """A style defining the look of a table.""" occurence.containing( occurence.ZeroOrMore('blockFont', IBlockFont), occurence.ZeroOrMore('blockLeading', IBlockLeading), occurence.ZeroOrMore('blockTextColor', IBlockTextColor), occurence.ZeroOrMore('blockAlignment', IBlockAlignment), occurence.ZeroOrMore('blockLeftPadding', IBlockLeftPadding), occurence.ZeroOrMore('blockRightPadding', IBlockRightPadding), occurence.ZeroOrMore('blockBottomPadding', IBlockBottomPadding), occurence.ZeroOrMore('blockTopPadding', IBlockTopPadding), occurence.ZeroOrMore('blockBackground', IBlockBackground), occurence.ZeroOrMore('blockRowBackground', IBlockRowBackground), occurence.ZeroOrMore('blockColBackground', IBlockColBackground), occurence.ZeroOrMore('blockValign', IBlockValign), occurence.ZeroOrMore('blockSpan', IBlockSpan), occurence.ZeroOrMore('blockNosplit', IBlockNosplit), occurence.ZeroOrMore('lineStyle', ILineStyle) ) id = attr.Text( title='Id', description='The name/id of the style.', required=True) keepWithNext = attr.Boolean( title='Keep with Next', description=('When set, this paragraph will always be in the same ' 'frame as the following flowable.'), required=False) class BlockTableStyle(directive.RMLDirective): signature = IBlockTableStyle factories = { 'blockFont': BlockFont, 'blockLeading': BlockLeading, 'blockTextColor': BlockTextColor, 'blockAlignment': BlockAlignment, 'blockLeftPadding': BlockLeftPadding, 'blockRightPadding': BlockRightPadding, 'blockBottomPadding': BlockBottomPadding, 'blockTopPadding': BlockTopPadding, 'blockBackground': BlockBackground, 'blockRowBackground': BlockRowBackground, 'blockColBackground': BlockColBackground, 'blockValign': BlockValign, 'blockSpan': BlockSpan, 'blockNosplit': BlockNosplit, 'lineStyle': LineStyle, } def process(self): kw = dict(self.getAttributeValues()) id = kw.pop('id') # Create Style self.style = reportlab.platypus.tables.TableStyle() for name, value in kw.items(): setattr(self.style, name, value) # Fill style self.processSubDirectives() # Add style to the manager manager = attr.getManager(self) manager.styles[id] = self.style class IMinimalListStyle(interfaces.IRMLDirectiveSignature): leftIndent = attr.Measurement( title='Left Indentation', description='General indentation on the left side.', required=False) rightIndent = attr.Measurement( title='Right Indentation', description='General indentation on the right side.', required=False) bulletColor = attr.Color( title='Bullet Color', description='The color in which the bullet will appear.', required=False) bulletFontName = attr.Text( title='Bullet Font Name', description='The font in which the bullet character will be rendered.', required=False) bulletFontSize = attr.Measurement( title='Bullet Font Size', description='The font size of the bullet character.', required=False) bulletOffsetY = attr.Measurement( title='Bullet Y-Offset', description='The vertical offset of the bullet.', required=False) bulletDedent = attr.StringOrInt( title='Bullet Dedent', description='Either pixels of dedent or auto (default).', required=False) bulletDir = attr.Choice( title='Bullet Layout Direction', description='The layout direction of the bullet.', choices=('ltr', 'rtl'), required=False) bulletFormat = attr.Text( title='Bullet Format', description='A formatting expression for the bullet text.', required=False) bulletType = attr.Choice( title='Bullet Type', description='The type of number to display.', choices=interfaces.ORDERED_LIST_TYPES + interfaces.UNORDERED_BULLET_VALUES, doLower=False, required=False) class IBaseListStyle(IMinimalListStyle): start = attr.Combination( title='Start Value', description='The counter start value.', value_types=( # Numeric start value. attr.Integer(), # Bullet types. attr.Choice(choices=interfaces.UNORDERED_BULLET_VALUES), # Arbitrary text. attr.Text(), ), required=False) class IListStyle(IBaseListStyle): """Defines a list style and gives it a name.""" name = attr.Text( title='Name', description='The name of the style.', required=True) parent = attr.Style( title='Parent', description=('The list style that will be used as a base for ' 'this one.'), required=False) class ListStyle(directive.RMLDirective): signature = IListStyle def process(self): kwargs = dict(self.getAttributeValues()) parent = kwargs.pop( 'parent', reportlab.lib.styles.ListStyle(name='List')) name = kwargs.pop('name') style = copy.deepcopy(parent) style.name = name[6:] if name.startswith('style.') else name for name, value in kwargs.items(): setattr(style, name, value) manager = attr.getManager(self) manager.styles[style.name] = style class IStylesheet(interfaces.IRMLDirectiveSignature): """A styleheet defines the styles that can be used in the document.""" occurence.containing( occurence.ZeroOrOne('initialize', IInitialize), occurence.ZeroOrMore('spanStyle', ISpanStyle), occurence.ZeroOrMore('paraStyle', IParagraphStyle), occurence.ZeroOrMore('blockTableStyle', IBlockTableStyle), occurence.ZeroOrMore('listStyle', IListStyle), # TODO: # occurence.ZeroOrMore('boxStyle', IBoxStyle), ) class Stylesheet(directive.RMLDirective): signature = IStylesheet factories = { 'initialize': Initialize, 'spanStyle': SpanStyle, 'paraStyle': ParagraphStyle, 'blockTableStyle': BlockTableStyle, 'listStyle': ListStyle, }
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/stylesheet.py
stylesheet.py
"""ReportLab fixups. """ from reportlab.lib.sequencer import _type2formatter from reportlab.platypus.flowables import LIIndenter from reportlab.platypus.flowables import ListFlowable from reportlab.platypus.flowables import _computeBulletWidth from reportlab.platypus.flowables import _LIParams from reportlab.rl_config import register_reset from z3c.rml import num2words __docformat__ = "reStructuredText" import copy from reportlab.graphics import testshapes from reportlab.lib import fonts from reportlab.pdfbase import pdfform from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase import ttfonts from reportlab.pdfbase.pdfpattern import PDFPattern _ps2tt_map_original = copy.deepcopy(fonts._ps2tt_map) _tt2ps_map_original = copy.deepcopy(fonts._tt2ps_map) def resetPdfForm(): pdfform.PDFDOCENC = PDFPattern(pdfform.PDFDocEncodingPattern) pdfform.ENCODING = PDFPattern( pdfform.EncodingPattern, PDFDocEncoding=pdfform.PDFDOCENC) pdfform.GLOBALFONTSDICTIONARY = pdfform.FormFontsDictionary() pdfform.GLOBALRESOURCES = pdfform.FormResources() pdfform.ZADB = PDFPattern(pdfform.ZaDbPattern) def resetFonts(): # testshapes._setup registers the Vera fonts every time which is a little # slow on all platforms. On Windows it lists the entire system font # directory and registers them all which is very slow. pdfmetrics.registerFont(ttfonts.TTFont("Vera", "Vera.ttf")) pdfmetrics.registerFont(ttfonts.TTFont("VeraBd", "VeraBd.ttf")) pdfmetrics.registerFont(ttfonts.TTFont("VeraIt", "VeraIt.ttf")) pdfmetrics.registerFont(ttfonts.TTFont("VeraBI", "VeraBI.ttf")) for f in ( 'Times-Roman', 'Courier', 'Helvetica', 'Vera', 'VeraBd', 'VeraIt', 'VeraBI'): if f not in testshapes._FONTS: testshapes._FONTS.append(f) fonts._ps2tt_map = copy.deepcopy(_ps2tt_map_original) fonts._tt2ps_map = copy.deepcopy(_tt2ps_map_original) def setSideLabels(): from reportlab.graphics.charts import piecharts piecharts.Pie3d.sideLabels = 0 setSideLabels() register_reset(resetPdfForm) register_reset(resetFonts) del register_reset # Support more enumeration formats. _type2formatter.update({ 'l': lambda v: num2words.num2words(v), 'L': lambda v: num2words.num2words(v).upper(), 'o': lambda v: num2words.num2words(v, ordinal=True), 'O': lambda v: num2words.num2words(v, ordinal=True).upper(), 'r': lambda v: num2words.toOrdinal(v), 'R': lambda v: num2words.toOrdinal(v).upper(), }) # Make sure that the counter gets increased for our new formatters as well. ListFlowable._numberStyles += ''.join(_type2formatter.keys()) def ListFlowable_getContent(self): bt = self._bulletType value = self._start if isinstance(value, (list, tuple)): values = value value = values[0] else: values = [value] autov = values[0] # FIX TO ALLOW ALL FORMATTERS!!! inc = int(bt in _type2formatter.keys()) if inc: try: value = int(value) except BaseException: value = 1 bd = self._bulletDedent if bd == 'auto': align = self._bulletAlign dir = self._bulletDir if dir == 'ltr' and align == 'left': bd = self._leftIndent elif align == 'right': bd = self._rightIndent else: # we need to work out the maximum width of any of the labels tvalue = value maxW = 0 for d, f in self._flowablesIter(): if d: maxW = max(maxW, _computeBulletWidth(self, tvalue)) if inc: tvalue += inc elif isinstance(f, LIIndenter): b = f._bullet if b: if b.bulletType == bt: maxW = max(maxW, _computeBulletWidth(b, b.value)) tvalue = int(b.value) else: maxW = max(maxW, _computeBulletWidth(self, tvalue)) if inc: tvalue += inc if dir == 'ltr': if align == 'right': bd = self._leftIndent - maxW else: bd = self._leftIndent - maxW * 0.5 elif align == 'left': bd = self._rightIndent - maxW else: bd = self._rightIndent - maxW * 0.5 self._calcBulletDedent = bd S = [] aS = S.append i = 0 for d, f in self._flowablesIter(): if isinstance(f, ListFlowable): fstart = f._start if isinstance(fstart, (list, tuple)): fstart = fstart[0] if fstart in values: # my kind of ListFlowable if f._auto: autov = values.index(autov) + 1 f._start = values[autov:] + values[:autov] autov = f._start[0] if inc: f._bulletType = autov else: autov = fstart fparams = {} if not i: i += 1 spaceBefore = getattr(self, 'spaceBefore', None) if spaceBefore is not None: fparams['spaceBefore'] = spaceBefore if d: aS(self._makeLIIndenter( f, bullet=self._makeBullet(value), params=fparams)) if inc: value += inc elif isinstance(f, LIIndenter): b = f._bullet if b: if b.bulletType != bt: raise ValueError( 'Included LIIndenter bulletType=%s != OrderedList' ' bulletType=%s' % (b.bulletType, bt)) value = int(b.value) else: f._bullet = self._makeBullet( value, params=getattr(f, 'params', None)) if fparams: f.__dict__['spaceBefore'] = max( f.__dict__.get('spaceBefore', 0), spaceBefore) aS(f) if inc: value += inc elif isinstance(f, _LIParams): fparams.update(f.params) z = self._makeLIIndenter(f.flowable, bullet=None, params=fparams) if f.first: if f.value is not None: value = f.value if inc: value = int(value) z._bullet = self._makeBullet(value, f.params) if inc: value += inc aS(z) else: aS(self._makeLIIndenter(f, bullet=None, params=fparams)) spaceAfter = getattr(self, 'spaceAfter', None) if spaceAfter is not None: f = S[-1] f.__dict__['spaceAfter'] = max( f.__dict__.get('spaceAfter', 0), spaceAfter) return S ListFlowable._getContent = ListFlowable_getContent
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/rlfix.py
rlfix.py
"""Style Related Element Processing """ import reportlab.platypus.flowables import reportlab.rl_config import zope.interface from reportlab.rl_config import overlapAttachedSpace from z3c.rml import interfaces # Fix problem with reportlab 3.1.44 class KeepInFrame(reportlab.platypus.flowables.KeepInFrame): pass def __init__(self, maxWidth, maxHeight, content=[], mergeSpace=1, mode='shrink', name='', hAlign='LEFT', vAlign='BOTTOM', fakeWidth=None): self.name = name self.maxWidth = maxWidth self.maxHeight = maxHeight self.mode = mode assert mode in ('error', 'overflow', 'shrink', 'truncate'), \ f'{self.identity()} invalid mode value {mode}' # This is an unnecessary check, since wrap() handles None just fine! # assert maxHeight>=0, \ # '%s invalid maxHeight value %s' % (self.identity(),maxHeight) if mergeSpace is None: mergeSpace = overlapAttachedSpace self.mergespace = mergeSpace self._content = content or [] self.vAlign = vAlign self.hAlign = hAlign self.fakeWidth = fakeWidth class BaseFlowable(reportlab.platypus.flowables.Flowable): def __init__(self, *args, **kw): reportlab.platypus.flowables.Flowable.__init__(self) self.args = args self.kw = kw def wrap(self, *args): return (0, 0) def draw(self): pass class Illustration(reportlab.platypus.flowables.Flowable): def __init__(self, processor, width, height): self.processor = processor self.width = width self.height = height def wrap(self, *args): return (self.width, self.height) def draw(self): # Import here to avoid recursive imports from z3c.rml import canvas self.canv.saveState() drawing = canvas.Drawing( self.processor.element, self.processor) zope.interface.alsoProvides(drawing, interfaces.ICanvasManager) drawing.canvas = self.canv drawing.process() self.canv.restoreState() class BookmarkPage(BaseFlowable): def draw(self): self.canv.bookmarkPage(*self.args, **self.kw) class Bookmark(BaseFlowable): def draw(self): self.canv.bookmarkHorizontal(*self.args, **self.kw) class OutlineAdd(BaseFlowable): def draw(self): if self.kw.get('key', None) is None: self.kw['key'] = str(hash(self)) self.canv.bookmarkPage(self.kw['key']) self.canv.addOutlineEntry(**self.kw) class Link(reportlab.platypus.flowables._Container, reportlab.platypus.flowables.Flowable): def __init__(self, content, **args): self._content = content self.args = args def wrap(self, availWidth, availHeight): self.width, self.height = reportlab.platypus.flowables._listWrapOn( self._content, availWidth, self.canv) return self.width, self.height def drawOn(self, canv, x, y, _sW=0, scale=1.0, content=None, aW=None): '''we simulate being added to a frame''' pS = 0 if aW is None: aW = self.width aW = scale * (aW + _sW) if content is None: content = self._content y += self.height * scale startX = x startY = y totalWidth = 0 totalHeight = 0 for c in content: w, h = c.wrapOn(canv, aW, 0xfffffff) if w < reportlab.rl_config._FUZZ or h < reportlab.rl_config._FUZZ: continue if c is not content[0]: h += max(c.getSpaceBefore() - pS, 0) y -= h c.drawOn(canv, x, y, _sW=aW - w) if c is not content[-1]: pS = c.getSpaceAfter() y -= pS totalWidth += w totalHeight += h rectangle = [startX, startY - totalHeight, startX + totalWidth, startY] if 'url' in self.args: canv.linkURL(rect=rectangle, **self.args) else: canv.linkAbsolute('', Rect=rectangle, **self.args)
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/platypus.py
platypus.py
import zope.interface from reportlab import platypus from z3c.rml import attr from z3c.rml import canvas from z3c.rml import directive from z3c.rml import flowable from z3c.rml import interfaces from z3c.rml import occurence from z3c.rml import page from z3c.rml import stylesheet # noqa: F401 imported but unused class IStory(flowable.IFlow): """The story of the PDF file.""" occurence.containing( occurence.ZeroOrMore('pto', flowable.IPTO), *flowable.IFlow.getTaggedValue('directives')) firstPageTemplate = attr.Text( title='First Page Template', description='The first page template to be used.', default=None, required=False) class Story(flowable.Flow): signature = IStory factories = dict( pto=flowable.PTO, **flowable.Flow.factories ) def process(self): self.parent.flowables = super().process() self.parent.doc._firstPageTemplateIndex = self.getFirstPTIndex() def getFirstPTIndex(self): args = dict(self.getAttributeValues(select=('firstPageTemplate',))) fpt = args.pop('firstPageTemplate', None) if fpt is None: return 0 for idx, pageTemplate in enumerate(self.parent.doc.pageTemplates): if pageTemplate.id == fpt: return idx raise ValueError('%r is not a correct page template id.' % fpt) class IFrame(interfaces.IRMLDirectiveSignature): """A frame on a page.""" x1 = attr.Measurement( title='X-Position', description='The X-Position of the lower-left corner of the frame.', allowPercentage=True, required=True) y1 = attr.Measurement( title='Y-Position', description='The Y-Position of the lower-left corner of the frame.', allowPercentage=True, required=True) width = attr.Measurement( title='Width', description='The width of the frame.', allowPercentage=True, required=True) height = attr.Measurement( title='Height', description='The height of the frame.', allowPercentage=True, required=True) id = attr.Text( title='Id', description='The id of the frame.', required=False) leftPadding = attr.Measurement( title='Left Padding', description='The left padding of the frame.', default=0, required=False) rightPadding = attr.Measurement( title='Right Padding', description='The right padding of the frame.', default=0, required=False) topPadding = attr.Measurement( title='Top Padding', description='The top padding of the frame.', default=0, required=False) bottomPadding = attr.Measurement( title='Bottom Padding', description='The bottom padding of the frame.', default=0, required=False) showBoundary = attr.Boolean( title='Show Boundary', description='A flag to show the boundary of the frame.', required=False) class Frame(directive.RMLDirective): signature = IFrame def process(self): # get the page size size = self.parent.pt.pagesize if size is None: size = self.parent.parent.parent.doc.pagesize # Get the arguments args = dict(self.getAttributeValues()) # Deal with percentages for name, dir in (('x1', 0), ('y1', 1), ('width', 0), ('height', 1)): if (isinstance(args[name], str) and args[name].endswith('%')): args[name] = float(args[name][:-1]) / 100 * size[dir] frame = platypus.Frame(**args) self.parent.frames.append(frame) class IPageGraphics(canvas.IDrawing): """Define the page graphics for the page template.""" @zope.interface.implementer(interfaces.ICanvasManager) class PageGraphics(directive.RMLDirective): signature = IPageGraphics def process(self): onPage = self.parent.pt.onPage def drawOnCanvas(canv, doc): onPage(canv, doc) canv.saveState() self.canvas = canv drawing = canvas.Drawing(self.element, self) drawing.process() canv.restoreState() self.parent.pt.onPage = drawOnCanvas class Header(PageGraphics): def process(self): onPage = self.parent.pt.onPage def drawOnCanvas(canv, doc): onPage(canv, doc) canv.saveState() self.canvas = canv place = canvas.Place(self.element, self) place.process() canv.restoreState() self.parent.pt.onPage = drawOnCanvas class Footer(Header): pass class IPageTemplate(interfaces.IRMLDirectiveSignature): """Define a page template.""" occurence.containing( occurence.OneOrMore('frame', IFrame), occurence.ZeroOrOne('pageGraphics', IPageGraphics), occurence.ZeroOrOne('mergePage', page.IMergePage), ) id = attr.Text( title='Id', description='The id of the template.', required=True) pagesize = attr.PageSize( title='Page Size', description='The Page Size.', required=False) autoNextTemplate = attr.Text( title='Auto Next Page Template', description='The page template to use automatically for the next' ' page.', required=False) class PageTemplate(directive.RMLDirective): signature = IPageTemplate attrMapping = {'autoNextTemplate': 'autoNextPageTemplate'} factories = { 'frame': Frame, 'pageGraphics': PageGraphics, 'mergePage': page.MergePageInPageTemplate, 'header': Header, 'footer': Footer, } def process(self): args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) pagesize = args.pop('pagesize', None) self.frames = [] self.pt = platypus.PageTemplate(**args) self.processSubDirectives() self.pt.frames = self.frames if pagesize: self.pt.pagesize = pagesize self.parent.parent.doc.addPageTemplates(self.pt) class ITemplate(interfaces.IRMLDirectiveSignature): """Define a page template.""" occurence.containing( occurence.OneOrMore('pageTemplate', IPageTemplate), ) pagesize = attr.PageSize( title='Page Size', description='The Page Size.', required=False) rotation = attr.Integer( title='Rotation', description='The rotation of the page in multiples of 90 degrees.', required=False) leftMargin = attr.Measurement( title='Left Margin', description='The left margin of the template.', default=0, required=False) rightMargin = attr.Measurement( title='Right Margin', description='The right margin of the template.', default=0, required=False) topMargin = attr.Measurement( title='Top Margin', description='The top margin of the template.', default=0, required=False) bottomMargin = attr.Measurement( title='Bottom Margin', description='The bottom margin of the template.', default=0, required=False) showBoundary = attr.Boolean( title='Show Boundary', description='A flag to show the boundary of the template.', required=False) allowSplitting = attr.Boolean( title='Allow Splitting', description='A flag to allow splitting over multiple templates.', required=False) title = attr.Text( title='Title', description='The title of the PDF document.', required=False) author = attr.Text( title='Author', description='The author of the PDF document.', required=False) class Template(directive.RMLDirective): signature = ITemplate factories = { 'pageTemplate': PageTemplate, } def process(self): args = self.getAttributeValues() args += self.parent.getAttributeValues( select=('debug', 'compression', 'invariant'), attrMapping={'debug': '_debug', 'compression': 'pageCompression'}) args += (('cropMarks', self.parent.cropMarks),) self.parent.doc = platypus.BaseDocTemplate( self.parent.outputFile, **dict(args)) self.processSubDirectives()
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/template.py
template.py
"""``pdfInclude`` Directive. """ __docformat__ = "reStructuredText" import io import logging import os import subprocess from backports import tempfile try: import pikepdf from pikepdf import Dictionary # noqa: F401 imported but unused except ImportError: pikepdf = None from reportlab.platypus import flowables from z3c.rml import attr from z3c.rml import flowable from z3c.rml import interfaces from z3c.rml import occurence log = logging.getLogger(__name__) # by default False to avoid burping on # PdfReadWarning: Multiple definitions in dictionary at byte xxx STRICT = False def _letter(val, base=ord('A'), radix=26): __traceback_info__ = val, base index = val - 1 if index < 0: raise ValueError('Value must be greater than 0.') s = '' while True: val, off = divmod(index, radix) index = val - 1 s = chr(base + off) + s if not val: return s def do(cmd, cwd=None, captureOutput=True, ignoreErrors=False): log.debug('Command: ' + cmd) if captureOutput: stdout = stderr = subprocess.PIPE else: stdout = stderr = None p = subprocess.Popen( cmd, stdout=stdout, stderr=stderr, shell=True, cwd=cwd) stdout, stderr = p.communicate() if stdout is None: stdout = "See output above" if stderr is None: stderr = "See output above" if p.returncode != 0 and not ignoreErrors: log.error(f'An error occurred while running command: {cmd}') log.error(f'Error Output: \n{stderr}') raise ValueError( f'Shell Process had non-zero error code: {p.returncode}. \n' f'Stdout: {stdout}\n' f'StdErr: {stderr}' ) log.debug(f'Output: \n{stdout}') return stdout class ConcatenationPostProcessor: def __init__(self): self.operations = [] def process(self, inputFile1): input1 = pikepdf.open(inputFile1) offset = 0 for ( start_page, inputFile2, page_ranges, num_pages, on_first_page ) in self.operations: sp = start_page + offset for page_range in page_ranges: prs, pre = page_range input2 = pikepdf.open(inputFile2) for i in range(num_pages): if on_first_page and i > 0: # The platypus pipeline doesn't insert blank pages if # we are including on the first page. So we need to # insert our additional pages between start_page and # the next. input1.pages.insert(sp + i, input2.pages[prs + i]) offset += 1 else: # Here, Platypus has added more blank pages, so we'll # emplace our pages. Doing this copy will preserve # references to the original pages if there is a # TOC/Bookmarks. input1.pages.append(input2.pages[prs + i]) input1.pages[sp + i].emplace(input1.pages[-1]) del input1.pages[-1] outputFile = io.BytesIO() input1.save(outputFile) return outputFile class PdfTkConcatenationPostProcessor: EXECUTABLE = 'pdftk' PRESERVE_OUTLINE = True def __init__(self): self.operations = [] def _process(self, inputFile1, dir): file_path = os.path.join(dir, 'A.pdf') with open(file_path, 'wb') as file: file.write(inputFile1.read()) file_map = {'A': file_path} file_id = 2 merges = [] curr_page = 0 for ( start_page, inputFile2, page_ranges, num_pages, on_first_page ) in self.operations: # Catch up with the main file. if curr_page < start_page: # Convert curr_page to human counting, start_page is okay, # since pdftk is upper-bound inclusive. merges.append('A%i-%i' % (curr_page + 1, start_page)) curr_page = start_page + num_pages # Store file. file_letter = _letter(file_id) file_path = os.path.join(dir, file_letter + '.pdf') inputFile2.seek(0) with open(file_path, 'wb') as file: file.write(inputFile2.read()) file_map[file_letter] = file_path file_id += 1 for (prs, pre) in page_ranges: # pdftk uses lower and upper bound inclusive. merges.append('%s%i-%i' % (file_letter, prs + 1, pre)) mergedFile = os.path.join(dir, 'merged.pdf') do('{} {} cat {} output {}'.format( self.EXECUTABLE, ' '.join(f'{l_}="{p}"' for l_, p in file_map.items()), ' '.join(merges), mergedFile)) if not self.PRESERVE_OUTLINE: with open(mergedFile, 'rb') as file: return io.BytesIO(file.read()) outputFile = os.path.join(dir, 'output.pdf') do('{} {}/A.pdf dump_data > {}/in.info'.format( self.EXECUTABLE, dir, dir)) do('{} {} update_info {}/in.info output {}'.format( self.EXECUTABLE, mergedFile, dir, outputFile)) with open(outputFile, 'rb') as file: return io.BytesIO(file.read()) def process(self, inputFile1): with tempfile.TemporaryDirectory() as tmpdirname: return self._process(inputFile1, tmpdirname) class IncludePdfPagesFlowable(flowables.Flowable): def __init__(self, pdf_file, pages, concatprocessor, included_on_first_page): flowables.Flowable.__init__(self) self.pdf_file = pdf_file self.proc = concatprocessor self.pages = pages self.included_on_first_page = included_on_first_page if self.included_on_first_page: self.width = 0 self.height = 0 else: self.width = 10 << 32 self.height = 10 << 32 def draw(self): if self.included_on_first_page: self.split(None, None) def split(self, availWidth, availheight): pages = self.pages if not pages: pdf = pikepdf.open(self.pdf_file) pages = [(0, len(pdf.pages))] num_pages = sum(pr[1] - pr[0] for pr in pages) start_page = self.canv.getPageNumber() if self.included_on_first_page: start_page -= 1 self.proc.operations.append( (start_page, self.pdf_file, pages, num_pages, self.included_on_first_page)) # Insert blank pages instead of pdf for now, to correctly number the # pages. We will replace these blank pages with included PDF in # ConcatenationPostProcessor. result = [] for i in range(num_pages): # Add empty spacer so platypus don't complain about too many empty # pages result.append(flowables.Spacer(0, 0)) result.append(flowables.PageBreak()) if start_page >= len(pages): # Make sure we get a flowable at the end of the document for the # last page. result.append(flowables.Spacer(0, 0)) return result class IIncludePdfPages(interfaces.IRMLDirectiveSignature): """Inserts a set of pages from a given PDF.""" filename = attr.File( title='Path to file', description='The pdf file to include.', required=True) pages = attr.IntegerSequence( title='Pages', description='A list of pages to insert.', numberingStartsAt=1, required=False) class IncludePdfPages(flowable.Flowable): signature = IIncludePdfPages ConcatenationPostProcessorFactory = ConcatenationPostProcessor def getProcessor(self): manager = attr.getManager(self, interfaces.IPostProcessorManager) procs = dict(manager.postProcessors) if 'CONCAT' not in procs: log.debug( 'Using concetation post-processor: %s', self.ConcatenationPostProcessorFactory) proc = self.ConcatenationPostProcessorFactory() manager.postProcessors.append(('CONCAT', proc)) return proc return procs['CONCAT'] def process(self): if pikepdf is None: raise Exception( 'pikepdf is not installed, so this feature is not available.') args = dict(self.getAttributeValues()) proc = self.getProcessor() self.parent.flow.append( IncludePdfPagesFlowable( args['filename'], args.get('pages'), proc, not self.parent.flow )) flowable.Flow.factories['includePdfPages'] = IncludePdfPages flowable.IFlow.setTaggedValue( 'directives', flowable.IFlow.getTaggedValue('directives') + (occurence.ZeroOrMore('includePdfPages', IIncludePdfPages),) )
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/pdfinclude.py
pdfinclude.py
import zope.schema from z3c.rml import attr from z3c.rml import document from z3c.rml import occurence occurence2Symbol = { occurence.ZeroOrMore: '*', occurence.ZeroOrOne: '?', occurence.OneOrMore: '+', } def generateElement(name, signature, seen): if signature is None: return '' subElementList = [] # Determine whether we have #PCDATA first. fields = zope.schema.getFieldsInOrder(signature) for attrName, field in fields: if isinstance(field, attr.TextNode): subElementList.append('#PCDATA') break # Create the list of sub-elements. occurence = '*' for occurence in signature.queryTaggedValue('directives', ()): if '#PCDATA' in subElementList: subElementList.append(occurence.tag) occurence = occurence2Symbol.get(occurence.__class__, '') else: subElementList.append( occurence.tag + occurence2Symbol.get(occurence.__class__, '') ) subElementList = ' | '.join(subElementList) if subElementList: subElementList = ' (' + subElementList + ')' if '#PCDATA' in subElementList: subElementList += occurence else: subElementList = ' EMPTY' text = '\n<!ELEMENT {}{}>'.format(name, subElementList) # Create a list of attributes for this element. for attrName, field in fields: # Ignore text nodes, since they are not attributes. if isinstance(field, attr.TextNode): continue # Create the type if isinstance(field, attr.Choice): type = '(' + ' | '.join(field.choices.keys()) + ')' else: type = 'CDATA' # Create required flag if field.required: required = '#REQUIRED' else: required = '#IMPLIED' # Put it all together text += f'\n<!ATTLIST {name} {attrName} {type} {required}>' text += '\n' # DTD does not support redefinition of an element type or have context # specific elements. if (name, signature) in seen: text = f'\n<!--{text}-->\n' seen.append((name, signature)) # Walk through all sub-elements, creating the DTD entries for them. for occurence in signature.queryTaggedValue('directives', ()): if (occurence.tag, occurence.signature) in seen: continue text += generateElement(occurence.tag, occurence.signature, seen) return text def generate(useWrapper=False): text = generateElement('document', document.Document.signature, []) if useWrapper: text = '<!DOCTYPE RML [\n%s]>\n' % text return text def main(): print(generate())
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/dtd.py
dtd.py
"""Page Drawing Related Element Processing """ import reportlab.pdfgen.canvas # noqa: F401 imported but unused from z3c.rml import attr from z3c.rml import chart from z3c.rml import directive from z3c.rml import flowable from z3c.rml import form from z3c.rml import interfaces from z3c.rml import occurence from z3c.rml import page from z3c.rml import special from z3c.rml import stylesheet # noqa: F401 imported but unused class IShape(interfaces.IRMLDirectiveSignature): """A shape to be drawn on the canvas.""" x = attr.Measurement( title='X-Coordinate', description=('The X-coordinate of the lower-left position of the ' 'shape.'), required=True) y = attr.Measurement( title='Y-Coordinate', description=('The Y-coordinate of the lower-left position of the ' 'shape.'), required=True) fill = attr.Boolean( title='Fill', description='A flag to specify whether the shape should be filled.', required=False) stroke = attr.Boolean( title='Stroke', description=("A flag to specify whether the shape's outline should " "be drawn."), required=False) class CanvasRMLDirective(directive.RMLDirective): callable = None attrMapping = None def process(self): kwargs = dict(self.getAttributeValues(attrMapping=self.attrMapping)) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas getattr(canvas, self.callable)(**kwargs) class ISaveState(interfaces.IRMLDirectiveSignature): """Saves the current canvas state.""" class SaveState(CanvasRMLDirective): signature = ISaveState callable = 'saveState' class IRestoreState(interfaces.IRMLDirectiveSignature): """Saves the current canvas state.""" class RestoreState(CanvasRMLDirective): signature = IRestoreState callable = 'restoreState' class IDrawString(interfaces.IRMLDirectiveSignature): """Draws a simple string (left aligned) onto the canvas at the specified location.""" x = attr.Measurement( title='X-Coordinate', description=('The X-coordinate of the lower-left position of the ' 'string.'), required=True) y = attr.Measurement( title='Y-Coordinate', description=('The Y-coordinate of the lower-left position of the ' 'string.'), required=True) text = attr.RawXMLContent( title='Text', description=('The string/text that is put onto the canvas.'), required=True) class DrawString(CanvasRMLDirective, special.TextFlowables): signature = IDrawString callable = 'drawString' def process(self): canvas = attr.getManager(self, interfaces.ICanvasManager).canvas kwargs = dict(self.getAttributeValues(attrMapping=self.attrMapping)) kwargs['text'] = self._getText(self.element, canvas).strip() getattr(canvas, self.callable)(**kwargs) class IDrawRightString(IDrawString): """Draws a simple string (right aligned) onto the canvas at the specified location.""" class DrawRightString(DrawString): signature = IDrawRightString callable = 'drawRightString' class IDrawCenteredString(IDrawString): """Draws a simple string (centered aligned) onto the canvas at the specified location.""" class DrawCenteredString(DrawString): signature = IDrawCenteredString callable = 'drawCentredString' class IDrawAlignedString(IDrawString): """Draws a simple string (aligned to the pivot character) onto the canvas at the specified location.""" pivotChar = attr.Text( title='Text', description=('The string/text that is put onto the canvas.'), min_length=1, max_length=1, default='.', required=True) class DrawAlignedString(DrawString): signature = IDrawAlignedString callable = 'drawAlignedString' class IEllipse(IShape): """Draws an ellipse on the canvas.""" width = attr.Measurement( title='Width', description='The width of the ellipse.', required=True) height = attr.Measurement( title='Height', description='The height of the ellipse.', required=True) class Ellipse(CanvasRMLDirective): signature = IEllipse callable = 'ellipse' attrMapping = {'x': 'x1', 'y': 'y1'} def process(self): kwargs = dict(self.getAttributeValues(attrMapping=self.attrMapping)) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas # Convert width and height to end locations kwargs['x2'] = kwargs['x1'] + kwargs['width'] del kwargs['width'] kwargs['y2'] = kwargs['y1'] + kwargs['height'] del kwargs['height'] getattr(canvas, self.callable)(**kwargs) class ICircle(IShape): """Draws a circle on the canvas.""" radius = attr.Measurement( title='Radius', description='The radius of the circle.', required=True) class Circle(CanvasRMLDirective): signature = ICircle callable = 'circle' attrMapping = {'x': 'x_cen', 'y': 'y_cen', 'radius': 'r'} class IRectangle(IShape): """Draws an ellipse on the canvas.""" width = attr.Measurement( title='Width', description='The width of the rectangle.', required=True) height = attr.Measurement( title='Height', description='The height of the rectangle.', required=True) round = attr.Measurement( title='Corner Radius', description='The radius of the rounded corners.', required=False) href = attr.Text( title='Link URL', description='When specified, the rectangle becomes a link to that' ' URL.', required=False) destination = attr.Text( title='Link Destination', description=('When specified, the rectangle becomes a link to that ' 'destination.'), required=False) class Rectangle(CanvasRMLDirective): signature = IRectangle callable = 'rect' attrMapping = {'round': 'radius'} def process(self): if 'round' in self.element.keys(): self.callable = 'roundRect' kwargs = dict(self.getAttributeValues(attrMapping=self.attrMapping)) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas # Create a link url = kwargs.pop('href', None) if url: canvas.linkURL( url, (kwargs['x'], kwargs['y'], kwargs['x'] + kwargs['width'], kwargs['y'] + kwargs['height'])) dest = kwargs.pop('destination', None) if dest: canvas.linkRect( '', dest, (kwargs['x'], kwargs['y'], kwargs['x'] + kwargs['width'], kwargs['y'] + kwargs['height'])) # Render the rectangle getattr(canvas, self.callable)(**kwargs) class IGrid(interfaces.IRMLDirectiveSignature): """A shape to be drawn on the canvas.""" xs = attr.Sequence( title='X-Coordinates', description=('A sequence x-coordinates that represent the vertical ' 'line positions.'), value_type=attr.Measurement(), required=True) ys = attr.Sequence( title='Y-Coordinates', description=('A sequence y-coordinates that represent the horizontal ' 'line positions.'), value_type=attr.Measurement(), required=True) class Grid(CanvasRMLDirective): signature = IGrid callable = 'grid' attrMapping = {'xs': 'xlist', 'ys': 'ylist'} class ILines(interfaces.IRMLDirectiveSignature): """A path of connected lines drawn on the canvas.""" linelist = attr.TextNodeGrid( title='Line List', description=('A list of lines coordinates to draw.'), value_type=attr.Measurement(), columns=4, required=True) class Lines(CanvasRMLDirective): signature = ILines callable = 'lines' class ICurves(interfaces.IRMLDirectiveSignature): """A path of connected bezier curves drawn on the canvas.""" curvelist = attr.TextNodeGrid( title='Curve List', description=('A list of curve coordinates to draw.'), value_type=attr.Measurement(), columns=8, required=True) class Curves(CanvasRMLDirective): signature = ICurves callable = 'bezier' def process(self): argset = self.getAttributeValues(valuesOnly=True)[0] canvas = attr.getManager(self, interfaces.ICanvasManager).canvas for args in argset: getattr(canvas, self.callable)(*args) class IImage(interfaces.IRMLDirectiveSignature): """Draws an external image on the canvas.""" file = attr.Image( title='File', description=('Reference to the external file of the iamge.'), required=True) x = attr.Measurement( title='X-Coordinate', description=('The X-coordinate of the lower-left position of the ' 'shape.'), required=True) y = attr.Measurement( title='Y-Coordinate', description=('The Y-coordinate of the lower-left position of the ' 'shape.'), required=True) width = attr.Measurement( title='Width', description='The width of the image.', required=False) height = attr.Measurement( title='Height', description='The height of the image.', required=False) showBoundary = attr.Boolean( title='Show Boundary', description=('A flag determining whether a border should be drawn ' 'around the image.'), default=False, required=False) preserveAspectRatio = attr.Boolean( title='Preserve Aspect Ratio', description=("A flag determining whether the image's aspect ration " "should be conserved under any circumstances."), default=False, required=False) mask = attr.Color( title='Mask', description='The color mask used to render the image, or "auto" to use' ' the alpha channel if available.', default='auto', required=False, acceptAuto=True) anchor = attr.Choice( title='Text Anchor', description='The position in the text to which the coordinates refer.', choices='''nw n ne w c e sw s se'''.split(), required=False) class Image(CanvasRMLDirective): signature = IImage callable = 'drawImage' attrMapping = {'file': 'image'} def process(self): kwargs = dict(self.getAttributeValues(attrMapping=self.attrMapping)) show = kwargs.pop('showBoundary') canvas = attr.getManager(self, interfaces.ICanvasManager).canvas getattr(canvas, self.callable)(**kwargs) if show: width = kwargs.get('width', kwargs['image'].getSize()[0]) height = kwargs.get('height', kwargs['image'].getSize()[1]) canvas.rect(kwargs['x'], kwargs['y'], width, height) class IPlace(interfaces.IRMLDirectiveSignature): """Draws a set of flowables on the canvas within a given region.""" x = attr.Measurement( title='X-Coordinate', description=('The X-coordinate of the lower-left position of the ' 'place.'), required=True) y = attr.Measurement( title='Y-Coordinate', description=('The Y-coordinate of the lower-left position of the ' 'place.'), required=True) width = attr.Measurement( title='Width', description='The width of the place.', required=False) height = attr.Measurement( title='Height', description='The height of the place.', required=False) class Place(CanvasRMLDirective): signature = IPlace def process(self): x, y, width, height = self.getAttributeValues( select=('x', 'y', 'width', 'height'), valuesOnly=True) y += height flows = flowable.Flow(self.element, self.parent) flows.process() canvas = attr.getManager(self, interfaces.ICanvasManager).canvas for flow in flows.flow: flow.canv = canvas flowWidth, flowHeight = flow.wrap(width, height) if flowWidth <= width and flowHeight <= height: y -= flowHeight flow.drawOn(canvas, x, y) height -= flowHeight else: raise ValueError("Not enough space") class IParam(interfaces.IRMLDirectiveSignature): """Sets one paramter for the text annotation.""" name = attr.Text( title='Name', description='The name of the paramter.', required=True) value = attr.TextNode( title='Value', description=('The parameter value.'), required=True) class Param(directive.RMLDirective): signature = IParam def process(self): args = dict(self.getAttributeValues()) self.parent.params[args['name']] = args['value'] class ITextAnnotation(interfaces.IRMLDirectiveSignature): """Writes a low-level text annotation into the PDF.""" occurence.containing( occurence.ZeroOrMore('param', IParam)) contents = attr.FirstLevelTextNode( title='Contents', description='The PDF commands that are inserted as annotation.', required=True) class TextAnnotation(CanvasRMLDirective): signature = ITextAnnotation factories = {'param': Param} paramTypes = {'escape': attr.Integer()} def process(self): contents = self.getAttributeValues(valuesOnly=True)[0] self.params = {} self.processSubDirectives() for name, type in self.paramTypes.items(): if name in self.params: bound = type.bind(self) self.params[name] = bound.fromUnicode(self.params[name]) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas canvas.textAnnotation(contents, **self.params) class IMoveTo(interfaces.IRMLDirectiveSignature): """Move the path cursor to the specified location.""" position = attr.TextNodeSequence( title='Position', description='Position to which the path pointer is moved to.', value_type=attr.Measurement(), min_length=2, max_length=2, required=True) class MoveTo(directive.RMLDirective): signature = IMoveTo def process(self): args = self.getAttributeValues(valuesOnly=True) self.parent.path.moveTo(*args[0]) class ICurveTo(interfaces.IRMLDirectiveSignature): """Create a bezier curve from the current location to the specified one.""" curvelist = attr.TextNodeGrid( title='Curve Specification', description='Describes the end position and the curve properties.', value_type=attr.Measurement(), columns=6, required=True) class CurveTo(directive.RMLDirective): signature = ICurveTo def process(self): argset = self.getAttributeValues(valuesOnly=True)[0] for args in argset: self.parent.path.curveTo(*args) class ICurvesTo(ICurveTo): pass directive.DeprecatedDirective( ICurvesTo, 'Available for ReportLab RML compatibility. Please use the "curveto" ' 'directive instead.') class IPath(IShape): """Create a line path.""" occurence.containing( occurence.ZeroOrMore('moveto', IMoveTo), occurence.ZeroOrMore('curveto', ICurveTo), occurence.ZeroOrMore('curvesto', ICurvesTo), ) points = attr.TextNodeGrid( title='Points', description=('A list of coordinate points that define th path.'), value_type=attr.Measurement(), columns=2, required=True) close = attr.Boolean( title='Close Path', description=("A flag specifying whether the path should be closed."), default=False, required=False) clip = attr.Boolean( title='Clip Path', description=("A flag specifying whether the path should clip " "overlapping elements."), default=False, required=False) class Path(CanvasRMLDirective): signature = IPath factories = { 'moveto': MoveTo, 'curveto': CurveTo, 'curvesto': CurveTo } def processPoints(self, text): if text.strip() == '': return bound = self.signature['points'].bind(self) for coords in bound.fromUnicode(text): self.path.lineTo(*coords) def process(self): kwargs = dict(self.getAttributeValues(ignore=('points',))) # Start the path and set the cursor to the start location. canvas = attr.getManager(self, interfaces.ICanvasManager).canvas self.path = canvas.beginPath() self.path.moveTo(kwargs.pop('x'), kwargs.pop('y')) # Process the text before the first sub-directive. if self.element.text is not None: self.processPoints(self.element.text) # Handle each sub-directive. for directive_ in self.element.getchildren(): if directive_.tag in self.factories: self.factories[directive_.tag](directive_, self).process() # If there is more text after sub-directive, process it. if directive_.tail is not None: self.processPoints(directive_.tail) if kwargs.pop('close', False): self.path.close() if kwargs.pop('clip', False): canvas.clipPath(self.path, **kwargs) else: canvas.drawPath(self.path, **kwargs) class IFill(interfaces.IRMLDirectiveSignature): """Set the fill color.""" color = attr.Color( title='Color', description=('The color value to be set.'), required=True) class Fill(CanvasRMLDirective): signature = IFill callable = 'setFillColor' attrMapping = {'color': 'aColor'} class IStroke(interfaces.IRMLDirectiveSignature): """Set the stroke/line color.""" color = attr.Color( title='Color', description=('The color value to be set.'), required=True) class Stroke(CanvasRMLDirective): signature = IStroke callable = 'setStrokeColor' attrMapping = {'color': 'aColor'} class ISetFont(interfaces.IRMLDirectiveSignature): """Set the font name and/or size.""" name = attr.Text( title='Font Name', description=('The name of the font as it was registered.'), required=True) size = attr.Measurement( title='Size', description=('The font size.'), required=True) leading = attr.Measurement( title='Leading', description=('The font leading.'), required=False) class SetFont(CanvasRMLDirective): signature = ISetFont callable = 'setFont' attrMapping = {'name': 'psfontname'} class ISetFontSize(interfaces.IRMLDirectiveSignature): """Set the font size.""" size = attr.Measurement( title='Size', description=('The font size.'), required=True) leading = attr.Measurement( title='Leading', description=('The font leading.'), required=False) class SetFontSize(CanvasRMLDirective): signature = ISetFontSize callable = 'setFontSize' class IScale(interfaces.IRMLDirectiveSignature): """Scale the drawing using x and y scaling factors.""" sx = attr.Float( title='X-Scaling-Factor', description=('The scaling factor applied on x-coordinates.'), default=1, required=False) sy = attr.Float( title='Y-Scaling-Factor', description=('The scaling factor applied on y-coordinates.'), default=1, required=False) class Scale(CanvasRMLDirective): signature = IScale callable = 'scale' attrMapping = {'sx': 'x', 'sy': 'y'} class ITranslate(interfaces.IRMLDirectiveSignature): """Translate the drawing coordinates by the specified x and y offset.""" dx = attr.Measurement( title='X-Offset', description=('The amount to move the drawing to the right.'), required=True) dy = attr.Measurement( title='Y-Offset', description=('The amount to move the drawing upward.'), required=True) class Translate(CanvasRMLDirective): signature = ITranslate callable = 'translate' class IRotate(interfaces.IRMLDirectiveSignature): """Rotate the drawing counterclockwise.""" degrees = attr.Measurement( title='Angle', description=('The angle in degrees.'), required=True) class Rotate(CanvasRMLDirective): signature = IRotate callable = 'rotate' attrMapping = {'degrees': 'theta'} class ISkew(interfaces.IRMLDirectiveSignature): """Skew the drawing.""" alpha = attr.Measurement( title='Alpha', description=('The amount to skew the drawing in the horizontal.'), required=True) beta = attr.Measurement( title='Beta', description=('The amount to skew the drawing in the vertical.'), required=True) class Skew(CanvasRMLDirective): signature = ISkew callable = 'skew' class ITransform(interfaces.IRMLDirectiveSignature): """A full 2-D matrix transformation""" matrix = attr.TextNodeSequence( title='Matrix', description='The transformation matrix.', value_type=attr.Float(), min_length=6, max_length=6, required=True) class Transform(CanvasRMLDirective): signature = ITransform def process(self): args = self.getAttributeValues(valuesOnly=True) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas canvas.transform(*args[0]) class ILineMode(interfaces.IRMLDirectiveSignature): """Set the line mode for the following graphics elements.""" width = attr.Measurement( title='Width', description=('The line width.'), required=False) dash = attr.Sequence( title='Dash-Pattern', description=('The dash-pattern of a line.'), value_type=attr.Measurement(), required=False) miterLimit = attr.Measurement( title='Miter Limit', description=('The ???.'), required=False) join = attr.Choice( title='Join', description='The way lines are joined together.', choices=interfaces.JOIN_CHOICES, required=False) cap = attr.Choice( title='Cap', description='The cap is the desciption of how the line-endings look.', choices=interfaces.CAP_CHOICES, required=False) class LineMode(CanvasRMLDirective): signature = ILineMode def process(self): kw = dict(self.getAttributeValues()) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas if 'width' in kw: canvas.setLineWidth(kw['width']) if 'join' in kw: canvas.setLineJoin(kw['join']) if 'cap' in kw: canvas.setLineCap(kw['cap']) if 'miterLimit' in kw: canvas.setMiterLimit(kw['miterLimit']) if 'dash' in kw: canvas.setDash(kw['dash']) class IBookmark(interfaces.IRMLDirectiveSignature): """ This creates a bookmark to the current page which can be referred to with the given key elsewhere. (Used inside a page drawing.) """ name = attr.Text( title='Name', description='The name of the bookmark.', required=True) fit = attr.Choice( title='Fit', description='The Fit Type.', choices=('XYZ', 'Fit', 'FitH', 'FitV', 'FitR'), required=False) zoom = attr.Float( title='Zoom', description='The zoom level when clicking on the bookmark.', required=False) x = attr.Measurement( title='X-Position', description='The x-position.', required=False) y = attr.Measurement( title='Y-Position', description='The y-position.', required=False) class Bookmark(CanvasRMLDirective): signature = IBookmark def process(self): args = dict(self.getAttributeValues()) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas args['left'], args['top'] = canvas.absolutePosition( args['x'], args['y']) canvas.bookmarkPage(**args) class IPlugInGraphic(interfaces.IRMLDirectiveSignature): """Inserts a custom graphic developed in Python.""" module = attr.Text( title='Module', description='The Python module in which the flowable is located.', required=True) function = attr.Text( title='Function', description=('The name of the factory function within the module ' 'that returns the custom flowable.'), required=True) params = attr.TextNode( title='Parameters', description=('A list of parameters encoded as a long string.'), required=False) class PlugInGraphic(CanvasRMLDirective): signature = IPlugInGraphic def process(self): modulePath, functionName, params = self.getAttributeValues( valuesOnly=True) module = __import__(modulePath, {}, {}, [modulePath]) function = getattr(module, functionName) canvas = attr.getManager(self, interfaces.ICanvasManager).canvas function(canvas, params) class IDrawing(interfaces.IRMLDirectiveSignature): """A container directive for all directives that draw directly on the cnavas.""" occurence.containing( # State Manipulation occurence.ZeroOrMore('saveState', ISaveState), occurence.ZeroOrMore('restoreState', IRestoreState), # String Drawing occurence.ZeroOrMore('drawString', IDrawString), occurence.ZeroOrMore('drawRightString', IDrawRightString), occurence.ZeroOrMore('drawCenteredString', IDrawCenteredString), occurence.ZeroOrMore('drawCentredString', IDrawCenteredString), occurence.ZeroOrMore('drawAlignedString', IDrawAlignedString), # Drawing Operations occurence.ZeroOrMore('ellipse', IEllipse), occurence.ZeroOrMore('circle', ICircle), occurence.ZeroOrMore('rect', IRectangle), occurence.ZeroOrMore('grid', IGrid), occurence.ZeroOrMore('lines', ILines), occurence.ZeroOrMore('curves', ICurves), occurence.ZeroOrMore('image', IImage), occurence.ZeroOrMore('place', IPlace), occurence.ZeroOrMore('textAnnotation', ITextAnnotation), occurence.ZeroOrMore('path', IPath), # State Change Operations occurence.ZeroOrMore('fill', IFill), occurence.ZeroOrMore('stroke', IStroke), occurence.ZeroOrMore('setFont', ISetFont), occurence.ZeroOrMore('setFontSize', ISetFontSize), occurence.ZeroOrMore('scale', IScale), occurence.ZeroOrMore('translate', ITranslate), occurence.ZeroOrMore('rotate', IRotate), occurence.ZeroOrMore('skew', ISkew), occurence.ZeroOrMore('transform', ITransform), occurence.ZeroOrMore('lineMode', ILineMode), # Form Field Elements occurence.ZeroOrMore('barCode', form.IBarCode), occurence.ZeroOrMore('textField', form.ITextField), occurence.ZeroOrMore('buttonField', form.IButtonField), occurence.ZeroOrMore('selectField', form.ISelectField), # Charts occurence.ZeroOrMore('barChart', chart.IBarChart), occurence.ZeroOrMore('barChart3D', chart.IBarChart3D), occurence.ZeroOrMore('linePlot', chart.ILinePlot), occurence.ZeroOrMore('linePlot3D', chart.ILinePlot3D), occurence.ZeroOrMore('pieChart', chart.IPieChart), occurence.ZeroOrMore('pieChart3D', chart.IPieChart3D), occurence.ZeroOrMore('spiderChart', chart.ISpiderChart), # Misc occurence.ZeroOrMore('bookmark', IBookmark), occurence.ZeroOrMore('plugInGraphic', IPlugInGraphic), ) class Drawing(directive.RMLDirective): signature = IDrawing factories = { # State Management 'saveState': SaveState, 'restoreState': RestoreState, # Drawing Strings 'drawString': DrawString, 'drawRightString': DrawRightString, 'drawCenteredString': DrawCenteredString, 'drawCentredString': DrawCenteredString, 'drawAlignedString': DrawAlignedString, # Drawing Operations 'ellipse': Ellipse, 'circle': Circle, 'rect': Rectangle, 'grid': Grid, 'lines': Lines, 'curves': Curves, 'image': Image, 'place': Place, 'textAnnotation': TextAnnotation, 'path': Path, # Form Field Elements 'barCode': form.BarCode, 'textField': form.TextField, 'buttonField': form.ButtonField, 'selectField': form.SelectField, # State Change Operations 'fill': Fill, 'stroke': Stroke, 'setFont': SetFont, 'setFontSize': SetFontSize, 'scale': Scale, 'translate': Translate, 'rotate': Rotate, 'skew': Skew, 'transform': Transform, 'lineMode': LineMode, # Charts 'barChart': chart.BarChart, 'barChart3D': chart.BarChart3D, 'linePlot': chart.LinePlot, 'linePlot3D': chart.LinePlot3D, 'pieChart': chart.PieChart, 'pieChart3D': chart.PieChart3D, 'spiderChart': chart.SpiderChart, # Misc 'bookmark': Bookmark, 'plugInGraphic': PlugInGraphic, } class IPageDrawing(IDrawing): """Draws directly on the content of one page's canvas. Every call of this directive creates a new page.""" occurence.containing( # 'mergePage': IMergePage, *IDrawing.getTaggedValue('directives')) class PageDrawing(Drawing): signature = IDrawing factories = Drawing.factories.copy() factories.update({ 'mergePage': page.MergePage }) def process(self): super(Drawing, self).process() canvas = attr.getManager(self, interfaces.ICanvasManager).canvas canvas.showPage() class IPageInfo(interfaces.IRMLDirectiveSignature): """Set's up page-global settings.""" pageSize = attr.PageSize( title='Page Size', description=('The page size of all pages within this document.'), required=True) class PageInfo(CanvasRMLDirective): signature = IPageInfo callable = 'setPageSize' attrMapping = {'pageSize': 'size'}
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/canvas.py
canvas.py
"""Special Element Processing """ from z3c.rml import attr from z3c.rml import directive from z3c.rml import interfaces class IName(interfaces.IRMLDirectiveSignature): """Defines a name for a string.""" id = attr.Text( title='Id', description='The id under which the value will be known.', required=True) value = attr.Text( title='Value', description='The text that is displayed if the id is called.', required=True) class Name(directive.RMLDirective): signature = IName def process(self): id, value = self.getAttributeValues(valuesOnly=True) manager = attr.getManager(self) manager.names[id] = value class IAlias(interfaces.IRMLDirectiveSignature): """Defines an alias for a given style.""" id = attr.Text( title='Id', description='The id as which the style will be known.', required=True) value = attr.Style( title='Value', description='The style that is represented.', required=True) class Alias(directive.RMLDirective): signature = IAlias def process(self): id, value = self.getAttributeValues(valuesOnly=True) manager = attr.getManager(self) manager.styles[id] = value class TextFlowables: def _getManager(self): if hasattr(self, 'manager'): return self.manager else: return attr.getManager(self) def getPageNumber(self, elem, canvas): return str( canvas.getPageNumber() + int(elem.get('countingFrom', 1)) - 1 ) def getName(self, elem, canvas): return self._getManager().get_name( elem.get('id'), elem.get('default') ) def evalString(self, elem, canvas): return do_eval(self._getText(elem, canvas, False)) def namedString(self, elem, canvas): self._getManager().names[elem.get('id')] = self._getText( elem, canvas, include_final_tail=False ) return '' def name(self, elem, canvas): self._getManager().names[elem.get('id')] = elem.get('value') return '' handleElements = {'pageNumber': getPageNumber, 'getName': getName, 'evalString': evalString, 'namedString': namedString, 'name': name} def _getText(self, node, canvas, include_final_tail=True): text = node.text or '' for sub in node.getchildren(): if sub.tag in self.handleElements: text += self.handleElements[sub.tag](self, sub, canvas) else: self._getText(sub, canvas) text += sub.tail or '' if include_final_tail: text += node.tail or '' return text def do_eval(value): # Maybe still not safe value = value.strip() if value: return str(eval(value.strip(), {'__builtins__': None}, {})) return ''
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/special.py
special.py
"""Flowable Element Processing """ import copy import logging import re from xml.sax.saxutils import unescape import reportlab.lib.styles import reportlab.platypus import reportlab.platypus.doctemplate import reportlab.platypus.flowables import reportlab.platypus.tables import zope.schema from reportlab.lib import styles # noqa: F401 imported but unused from reportlab.lib import utils from z3c.rml import SampleStyleSheet from z3c.rml import attr from z3c.rml import directive from z3c.rml import form from z3c.rml import interfaces from z3c.rml import occurence from z3c.rml import paraparser from z3c.rml import platypus from z3c.rml import special from z3c.rml import stylesheet try: import reportlab.graphics.barcode except ImportError: # barcode package has not been installed import types import reportlab.graphics reportlab.graphics.barcode = types.ModuleType('barcode') reportlab.graphics.barcode.createBarcodeDrawing = None # XXX:Copy of reportlab.lib.pygments2xpre.pygments2xpre to fix bug in Python 2. def pygments2xpre(s, language="python"): "Return markup suitable for XPreformatted" try: from pygments import highlight from pygments.formatters import HtmlFormatter except ImportError: return s from pygments.lexers import get_lexer_by_name l_ = get_lexer_by_name(language) h = HtmlFormatter() from io import StringIO out = StringIO() highlight(s, l_, h, out) styles_ = [(cls, style.split(';')[0].split(':')[1].strip()) for cls, (style, ttype, level) in h.class2style.items() if cls and style and style.startswith('color:')] from reportlab.lib.pygments2xpre import _2xpre return _2xpre(out.getvalue(), styles_) class Flowable(directive.RMLDirective): klass = None attrMapping = None def process(self): args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) self.parent.flow.append(self.klass(**args)) class ISpacer(interfaces.IRMLDirectiveSignature): """Creates a vertical space in the flow.""" width = attr.Measurement( title='Width', description='The width of the spacer. Currently not implemented.', default=100, required=False) length = attr.Measurement( title='Length', description='The height of the spacer.', required=True) class Spacer(Flowable): signature = ISpacer klass = reportlab.platypus.Spacer attrMapping = {'length': 'height'} class IIllustration(interfaces.IRMLDirectiveSignature): """Inserts an illustration with graphics elements.""" width = attr.Measurement( title='Width', description='The width of the illustration.', required=True) height = attr.Measurement( title='Height', description='The height of the illustration.', default=100, required=True) class Illustration(Flowable): signature = IIllustration klass = platypus.Illustration def process(self): args = dict(self.getAttributeValues()) self.parent.flow.append(self.klass(self, **args)) class IBarCodeFlowable(form.IBarCodeBase): """Creates a bar code as a flowable.""" value = attr.Text( title='Value', description='The value represented by the code.', required=True) class BarCodeFlowable(Flowable): signature = IBarCodeFlowable klass = staticmethod(reportlab.graphics.barcode.createBarcodeDrawing) attrMapping = {'code': 'codeName'} class IPluginFlowable(interfaces.IRMLDirectiveSignature): """Inserts a custom flowable developed in Python.""" module = attr.Text( title='Module', description='The Python module in which the flowable is located.', required=True) function = attr.Text( title='Function', description=('The name of the factory function within the module ' 'that returns the custom flowable.'), required=True) params = attr.TextNode( title='Parameters', description=('A list of parameters encoded as a long string.'), required=False) class PluginFlowable(Flowable): signature = IPluginFlowable def process(self): modulePath, functionName, text = self.getAttributeValues( valuesOnly=True) module = __import__(modulePath, {}, {}, [modulePath]) function = getattr(module, functionName) flowables = function(text) if not isinstance(flowables, (tuple, list)): flowables = [flowables] self.parent.flow += list(flowables) class IMinimalParagraphBase(interfaces.IRMLDirectiveSignature): style = attr.Style( title='Style', description=('The paragraph style that is applied to the paragraph. ' 'See the ``paraStyle`` tag for creating a paragraph ' 'style.'), required=False) bulletText = attr.Text( title='Bullet Character', description=('The bullet character is the ASCII representation of ' 'the symbol making up the bullet in a listing.'), required=False) dedent = attr.Integer( title='Dedent', description=('Number of characters to be removed in front of every ' 'line of the text.'), required=False) class IBold(interfaces.IRMLDirectiveSignature): """Renders the text inside as bold.""" class IItalic(interfaces.IRMLDirectiveSignature): """Renders the text inside as italic.""" class IUnderLine(interfaces.IRMLDirectiveSignature): """Underlines the contained text.""" class IBreak(interfaces.IRMLDirectiveSignature): """Inserts a line break in the paragraph.""" class IPageNumber(interfaces.IRMLDirectiveSignature): """Inserts the current page number into the text.""" class IParagraphBase(IMinimalParagraphBase): occurence.containing( occurence.ZeroOrMore('b', IBold), occurence.ZeroOrMore('i', IItalic), occurence.ZeroOrMore('u', IUnderLine), occurence.ZeroOrMore('br', IBreak, condition=occurence.laterThanReportlab21), occurence.ZeroOrMore('pageNumber', IPageNumber) ) class IPreformatted(IMinimalParagraphBase): """A preformatted text, similar to the <pre> tag in HTML.""" style = attr.Style( title='Style', description=('The paragraph style that is applied to the paragraph. ' 'See the ``paraStyle`` tag for creating a paragraph ' 'style.'), default=SampleStyleSheet['Code'], required=False) text = attr.RawXMLContent( title='Text', description=('The text that will be layed out.'), required=True) maxLineLength = attr.Integer( title='Max Line Length', description=('The maximum number of characters on one line.'), required=False) newLineChars = attr.Text( title='New Line Characters', description='The characters placed at the beginning of a wrapped line', required=False) class Preformatted(Flowable): signature = IPreformatted klass = reportlab.platypus.Preformatted class IXPreformatted(IParagraphBase): """A preformatted text that allows paragraph markup.""" style = attr.Style( title='Style', description=('The paragraph style that is applied to the paragraph. ' 'See the ``paraStyle`` tag for creating a paragraph ' 'style.'), default=SampleStyleSheet['Normal'], required=False) text = attr.RawXMLContent( title='Text', description=('The text that will be layed out.'), required=True) class XPreformatted(Flowable): signature = IXPreformatted klass = reportlab.platypus.XPreformatted class ICodeSnippet(IXPreformatted): """A code snippet with text highlighting.""" style = attr.Style( title='Style', description=('The paragraph style that is applied to the paragraph. ' 'See the ``paraStyle`` tag for creating a paragraph ' 'style.'), required=False) language = attr.Text( title='Language', description='The language the code snippet is written in.', required=False) class CodeSnippet(XPreformatted): signature = ICodeSnippet def process(self): args = dict(self.getAttributeValues()) lang = args.pop('language', None) args['text'] = unescape(args['text']) if lang is not None: args['text'] = pygments2xpre(args['text'], lang.lower()) if 'style' not in args: args['style'] = attr._getStyle(self, 'Code') self.parent.flow.append(self.klass(**args)) class IParagraph(IParagraphBase, stylesheet.IBaseParagraphStyle): """Lays out an entire paragraph.""" text = attr.XMLContent( title='Text', description=('The text that will be layed out.'), required=True) class Paragraph(Flowable): signature = IParagraph klass = paraparser.Z3CParagraph defaultStyle = 'Normal' styleAttributes = zope.schema.getFieldNames(stylesheet.IBaseParagraphStyle) def processStyle(self, style): attrs = [] for attrName in self.styleAttributes: if self.element.get(attrName) is not None: attrs.append(attrName) attrs = self.getAttributeValues(select=attrs) if attrs: style = copy.deepcopy(style) for name, value in attrs: setattr(style, name, value) return style def process(self): args = dict(self.getAttributeValues(ignore=self.styleAttributes)) if 'style' not in args: args['style'] = attr._getStyle(self, self.defaultStyle) args['style'] = self.processStyle(args['style']) args['manager'] = attr.getManager(self) self.parent.flow.append(self.klass(**args)) class ITitle(IParagraph): """The title is a simple paragraph with a special title style.""" class Title(Paragraph): signature = ITitle defaultStyle = 'Title' class IHeading1(IParagraph): """Heading 1 is a simple paragraph with a special heading 1 style.""" class Heading1(Paragraph): signature = IHeading1 defaultStyle = 'Heading1' class IHeading2(IParagraph): """Heading 2 is a simple paragraph with a special heading 2 style.""" class Heading2(Paragraph): signature = IHeading2 defaultStyle = 'Heading2' class IHeading3(IParagraph): """Heading 3 is a simple paragraph with a special heading 3 style.""" class Heading3(Paragraph): signature = IHeading3 defaultStyle = 'Heading3' class IHeading4(IParagraph): """Heading 4 is a simple paragraph with a special heading 4 style.""" class Heading4(Paragraph): signature = IHeading4 defaultStyle = 'Heading4' class IHeading5(IParagraph): """Heading 5 is a simple paragraph with a special heading 5 style.""" class Heading5(Paragraph): signature = IHeading5 defaultStyle = 'Heading5' class IHeading6(IParagraph): """Heading 6 is a simple paragraph with a special heading 6 style.""" class Heading6(Paragraph): signature = IHeading6 defaultStyle = 'Heading6' class ITableCell(interfaces.IRMLDirectiveSignature): """A table cell within a table.""" content = attr.RawXMLContent( title='Content', description=('The content of the cell; can be text or any flowable.'), required=True) fontName = attr.Text( title='Font Name', description='The name of the font for the cell.', required=False) fontSize = attr.Measurement( title='Font Size', description='The font size for the text of the cell.', required=False) leading = attr.Measurement( title='Leading', description=('The height of a single text line. It includes ' 'character height.'), required=False) fontColor = attr.Color( title='Font Color', description='The color in which the text will appear.', required=False) leftPadding = attr.Measurement( title='Left Padding', description='The size of the padding on the left side.', required=False) rightPadding = attr.Measurement( title='Right Padding', description='The size of the padding on the right side.', required=False) topPadding = attr.Measurement( title='Top Padding', description='The size of the padding on the top.', required=False) bottomPadding = attr.Measurement( title='Bottom Padding', description='The size of the padding on the bottom.', required=False) background = attr.Color( title='Background Color', description='The color to use as the background for the cell.', required=False) align = attr.Choice( title='Text Alignment', description='The text alignment within the cell.', choices=interfaces.ALIGN_TEXT_CHOICES, required=False) vAlign = attr.Choice( title='Vertical Alignment', description='The vertical alignment of the text within the cell.', choices=interfaces.VALIGN_TEXT_CHOICES, required=False) lineBelowThickness = attr.Measurement( title='Line Below Thickness', description='The thickness of the line below the cell.', required=False) lineBelowColor = attr.Color( title='Line Below Color', description='The color of the line below the cell.', required=False) lineBelowCap = attr.Choice( title='Line Below Cap', description='The cap at the end of the line below the cell.', choices=interfaces.CAP_CHOICES, required=False) lineBelowCount = attr.Integer( title='Line Below Count', description=('Describes whether the line below is a single (1) or ' 'double (2) line.'), required=False) lineBelowDash = attr.Sequence( title='Line Below Dash', description='The dash-pattern of a line.', value_type=attr.Measurement(), default=None, required=False) lineBelowSpace = attr.Measurement( title='Line Below Space', description='The space of the line below the cell.', required=False) lineAboveThickness = attr.Measurement( title='Line Above Thickness', description='The thickness of the line above the cell.', required=False) lineAboveColor = attr.Color( title='Line Above Color', description='The color of the line above the cell.', required=False) lineAboveCap = attr.Choice( title='Line Above Cap', description='The cap at the end of the line above the cell.', choices=interfaces.CAP_CHOICES, required=False) lineAboveCount = attr.Integer( title='Line Above Count', description=('Describes whether the line above is a single (1) or ' 'double (2) line.'), required=False) lineAboveDash = attr.Sequence( title='Line Above Dash', description='The dash-pattern of a line.', value_type=attr.Measurement(), default=None, required=False) lineAboveSpace = attr.Measurement( title='Line Above Space', description='The space of the line above the cell.', required=False) lineLeftThickness = attr.Measurement( title='Left Line Thickness', description='The thickness of the line left of the cell.', required=False) lineLeftColor = attr.Color( title='Left Line Color', description='The color of the line left of the cell.', required=False) lineLeftCap = attr.Choice( title='Line Left Cap', description='The cap at the end of the line left of the cell.', choices=interfaces.CAP_CHOICES, required=False) lineLeftCount = attr.Integer( title='Line Left Count', description=('Describes whether the left line is a single (1) or ' 'double (2) line.'), required=False) lineLeftDash = attr.Sequence( title='Line Left Dash', description='The dash-pattern of a line.', value_type=attr.Measurement(), default=None, required=False) lineLeftSpace = attr.Measurement( title='Line Left Space', description='The space of the line left of the cell.', required=False) lineRightThickness = attr.Measurement( title='Right Line Thickness', description='The thickness of the line right of the cell.', required=False) lineRightColor = attr.Color( title='Right Line Color', description='The color of the line right of the cell.', required=False) lineRightCap = attr.Choice( title='Line Right Cap', description='The cap at the end of the line right of the cell.', choices=interfaces.CAP_CHOICES, required=False) lineRightCount = attr.Integer( title='Line Right Count', description=('Describes whether the right line is a single (1) or ' 'double (2) line.'), required=False) lineRightDash = attr.Sequence( title='Line Right Dash', description='The dash-pattern of a line.', value_type=attr.Measurement(), default=None, required=False) lineRightSpace = attr.Measurement( title='Line Right Space', description='The space of the line right of the cell.', required=False) href = attr.Text( title='Link URL', description='When specified, the cell becomes a link to that URL.', required=False) destination = attr.Text( title='Link Destination', description=('When specified, the cell becomes a link to that ' 'destination.'), required=False) class TableCell(directive.RMLDirective): signature = ITableCell styleAttributesMapping = ( ('FONTNAME', ('fontName',)), ('FONTSIZE', ('fontSize',)), ('TEXTCOLOR', ('fontColor',)), ('LEADING', ('leading',)), ('LEFTPADDING', ('leftPadding',)), ('RIGHTPADDING', ('rightPadding',)), ('TOPPADDING', ('topPadding',)), ('BOTTOMPADDING', ('bottomPadding',)), ('BACKGROUND', ('background',)), ('ALIGNMENT', ('align',)), ('VALIGN', ('vAlign',)), ('LINEBELOW', ('lineBelowThickness', 'lineBelowColor', 'lineBelowCap', 'lineBelowCount', 'lineBelowDash', 'lineBelowSpace')), ('LINEABOVE', ('lineAboveThickness', 'lineAboveColor', 'lineAboveCap', 'lineAboveCount', 'lineAboveDash', 'lineAboveSpace')), ('LINEBEFORE', ('lineLeftThickness', 'lineLeftColor', 'lineLeftCap', 'lineLeftCount', 'lineLeftDash', 'lineLeftSpace')), ('LINEAFTER', ('lineRightThickness', 'lineRightColor', 'lineRightCap', 'lineRightCount', 'lineRightDash', 'lineRightSpace')), ('HREF', ('href',)), ('DESTINATION', ('destination',)), ) def processStyle(self): row = len(self.parent.parent.rows) col = len(self.parent.cols) for styleAction, attrNames in self.styleAttributesMapping: attrs = [] for attrName in attrNames: if self.element.get(attrName) is not None: attrs.append(attrName) if not attrs: continue args = self.getAttributeValues(select=attrs, valuesOnly=True) if args: self.parent.parent.style.add( styleAction, [col, row], [col, row], *args) def process(self): # Produce style self.processStyle() # Produce cell data flow = Flow(self.element, self.parent) flow.process() content = flow.flow if len(content) == 0: content = self.getAttributeValues( select=('content',), valuesOnly=True)[0] self.parent.cols.append(content) class ITableRow(interfaces.IRMLDirectiveSignature): """A table row in the block table.""" occurence.containing( occurence.OneOrMore('td', ITableCell), ) class TableRow(directive.RMLDirective): signature = ITableRow factories = {'td': TableCell} def process(self): self.cols = [] self.processSubDirectives() self.parent.rows.append(self.cols) class ITableBulkData(interfaces.IRMLDirectiveSignature): """Bulk Data allows one to quickly create a table.""" content = attr.TextNodeSequence( title='Content', description='The bulk data.', splitre=re.compile('\n'), value_type=attr.Sequence(splitre=re.compile(','), value_type=attr.Text()) ) class TableBulkData(directive.RMLDirective): signature = ITableBulkData def process(self): self.parent.rows = self.getAttributeValues(valuesOnly=True)[0] class BlockTableStyle(stylesheet.BlockTableStyle): def process(self): self.style = copy.deepcopy(self.parent.style) attrs = self.getAttributeValues() for name, value in attrs: setattr(self.style, name, value) self.processSubDirectives() self.parent.style = self.style class IBlockTable(interfaces.IRMLDirectiveSignature): """A typical block table.""" occurence.containing( occurence.ZeroOrMore('tr', ITableRow), occurence.ZeroOrOne('bulkData', ITableBulkData), occurence.ZeroOrMore('blockTableStyle', stylesheet.IBlockTableStyle), ) style = attr.Style( title='Style', description=('The table style that is applied to the table. '), required=False) rowHeights = attr.Sequence( title='Row Heights', description='A list of row heights in the table.', value_type=attr.Measurement(), required=False) colWidths = attr.Sequence( title='Column Widths', description='A list of column widths in the table.', value_type=attr.Measurement(allowPercentage=True, allowStar=True), required=False) repeatRows = attr.Integer( title='Repeat Rows', description='A flag to repeat rows upon table splits.', required=False) alignment = attr.Choice( title='Alignment', description='The alignment of whole table.', choices=interfaces.ALIGN_TEXT_CHOICES, required=False) splitByRow = attr.Boolean( title='Split table between rows', description='Allow tables to span multiple pages', required=False) splitInRow = attr.Boolean( title='Split table in rows', description='Allow table rows to span multiple pages', required=False) class BlockTable(Flowable): signature = IBlockTable klass = reportlab.platypus.Table factories = { 'tr': TableRow, 'bulkData': TableBulkData, 'blockTableStyle': BlockTableStyle} def process(self): attrs = dict(self.getAttributeValues()) # Get the table style; create a new one, if none is found style = attrs.pop('style', None) if style is None: self.style = reportlab.platypus.tables.TableStyle() else: self.style = copy.deepcopy(style) hAlign = attrs.pop('alignment', None) # Extract all table rows and cells self.rows = [] self.processSubDirectives(None) # Create the table repeatRows = attrs.pop('repeatRows', None) table = self.klass(self.rows, style=self.style, **attrs) if repeatRows: table.repeatRows = repeatRows if hAlign: table.hAlign = hAlign # Must set keepWithNext on table, since the style is not stored corr. if hasattr(self.style, 'keepWithNext'): table.keepWithNext = self.style.keepWithNext self.parent.flow.append(table) class INextFrame(interfaces.IRMLDirectiveSignature): """Switch to the next frame.""" name = attr.StringOrInt( title='Name', description=('The name or index of the next frame.'), required=False) class NextFrame(Flowable): signature = INextFrame klass = reportlab.platypus.doctemplate.FrameBreak attrMapping = {'name': 'ix'} class ISetNextFrame(interfaces.IRMLDirectiveSignature): """Define the next frame to switch to.""" name = attr.StringOrInt( title='Name', description=('The name or index of the next frame.'), required=True) class SetNextFrame(Flowable): signature = INextFrame klass = reportlab.platypus.doctemplate.NextFrameFlowable attrMapping = {'name': 'ix'} class INextPage(interfaces.IRMLDirectiveSignature): """Switch to the next page.""" class NextPage(Flowable): signature = INextPage klass = reportlab.platypus.PageBreak class ISetNextTemplate(interfaces.IRMLDirectiveSignature): """Define the next page template to use.""" name = attr.StringOrInt( title='Name', description='The name or index of the next page template.', required=True) class SetNextTemplate(Flowable): signature = ISetNextTemplate klass = reportlab.platypus.doctemplate.NextPageTemplate attrMapping = {'name': 'pt'} class IConditionalPageBreak(interfaces.IRMLDirectiveSignature): """Switch to the next page if not enough vertical space is available.""" height = attr.Measurement( title='height', description='The minimal height that must be remaining on the page.', required=True) class ConditionalPageBreak(Flowable): signature = IConditionalPageBreak klass = reportlab.platypus.CondPageBreak class IKeepInFrame(interfaces.IRMLDirectiveSignature): """Ask a flowable to stay within the frame.""" maxWidth = attr.Measurement( title='Maximum Width', description='The maximum width the flowables are allotted.', default=None, required=False) maxHeight = attr.Measurement( title='Maximum Height', description='The maximum height the flowables are allotted.', default=None, required=False) mergeSpace = attr.Boolean( title='Merge Space', description='A flag to set whether the space should be merged.', required=False) onOverflow = attr.Choice( title='On Overflow', description='Defines what has to be done, if an overflow is detected.', choices=('error', 'overflow', 'shrink', 'truncate'), required=False) id = attr.Text( title='Name/Id', description='The name/id of the flowable.', required=False) frame = attr.StringOrInt( title='Frame', description='The frame to which the flowable should be fitted.', required=False) class KeepInFrame(Flowable): signature = IKeepInFrame klass = platypus.KeepInFrame attrMapping = {'onOverflow': 'mode', 'id': 'name'} def process(self): args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) # Circumvent broken-ness in zope.schema args['maxWidth'] = args.get('maxWidth', None) args['maxHeight'] = args.get('maxHeight', None) # If the frame was specifed, get us there frame = args.pop('frame', None) if frame: self.parent.flow.append( reportlab.platypus.doctemplate.FrameBreak(frame)) # Create the content of the container flow = Flow(self.element, self.parent) flow.process() args['content'] = flow.flow # Create the keep in frame container frame = self.klass(**args) self.parent.flow.append(frame) class IKeepTogether(interfaces.IRMLDirectiveSignature): """Keep the child flowables in the same frame. Add frame break when necessary.""" maxHeight = attr.Measurement( title='Maximum Height', description='The maximum height the flowables are allotted.', default=None, required=False) class KeepTogether(Flowable): signature = IKeepTogether klass = reportlab.platypus.flowables.KeepTogether def process(self): args = dict(self.getAttributeValues()) # Create the content of the container flow = Flow(self.element, self.parent) flow.process() # Create the keep in frame container frame = self.klass(flow.flow, **args) self.parent.flow.append(frame) class IImage(interfaces.IRMLDirectiveSignature): """An image.""" src = attr.Image( title='Image Source', description='The file that is used to extract the image data.', onlyOpen=True, required=True) width = attr.Measurement( title='Image Width', description='The width of the image.', required=False) height = attr.Measurement( title='Image Height', description='The height the image.', required=False) preserveAspectRatio = attr.Boolean( title='Preserve Aspect Ratio', description=('If set, the aspect ratio of the image is kept. When ' 'both, width and height, are specified, the image ' 'will be fitted into that bounding box.'), default=False, required=False) mask = attr.Color( title='Mask', description='The color mask used to render the image, or "auto" to use' ' the alpha channel if available.', default='auto', required=False, acceptAuto=True) align = attr.Choice( title='Alignment', description='The alignment of the image within the frame.', choices=interfaces.ALIGN_TEXT_CHOICES, required=False) vAlign = attr.Choice( title='Vertical Alignment', description='The vertical alignment of the image.', choices=interfaces.VALIGN_TEXT_CHOICES, required=False) class Image(Flowable): signature = IImage klass = reportlab.platypus.flowables.Image attrMapping = {'src': 'filename', 'align': 'hAlign'} def process(self): args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) preserveAspectRatio = args.pop('preserveAspectRatio', False) if preserveAspectRatio: img = utils.ImageReader(args['filename']) args['filename'].seek(0) iw, ih = img.getSize() if 'width' in args and 'height' not in args: args['height'] = args['width'] * ih / iw elif 'width' not in args and 'height' in args: args['width'] = args['height'] * iw / ih elif 'width' in args and 'height' in args: # In this case, the width and height specify a bounding box # and the size of the image within that box is maximized. if args['width'] * ih / iw <= args['height']: args['height'] = args['width'] * ih / iw elif args['height'] * iw / ih < args['width']: args['width'] = args['height'] * iw / ih else: # This should not happen. raise ValueError('Cannot keep image in bounding box.') else: # No size was specified, so do nothing. pass vAlign = args.pop('vAlign', None) hAlign = args.pop('hAlign', None) img = self.klass(**args) if hAlign: img.hAlign = hAlign if vAlign: img.vAlign = vAlign self.parent.flow.append(img) class IImageAndFlowables(interfaces.IRMLDirectiveSignature): """An image with flowables around it.""" imageName = attr.Image( title='Image', description='The file that is used to extract the image data.', onlyOpen=True, required=True) imageWidth = attr.Measurement( title='Image Width', description='The width of the image.', required=False) imageHeight = attr.Measurement( title='Image Height', description='The height the image.', required=False) imageMask = attr.Color( title='Mask', description='The color mask used to render the image, or "auto" to use' ' the alpha channel if available.', default='auto', required=False, acceptAuto=True) imageLeftPadding = attr.Measurement( title='Image Left Padding', description='The padding on the left side of the image.', required=False) imageRightPadding = attr.Measurement( title='Image Right Padding', description='The padding on the right side of the image.', required=False) imageTopPadding = attr.Measurement( title='Image Top Padding', description='The padding on the top of the image.', required=False) imageBottomPadding = attr.Measurement( title='Image Bottom Padding', description='The padding on the bottom of the image.', required=False) imageSide = attr.Choice( title='Image Side', description='The side at which the image will be placed.', choices=('left', 'right'), required=False) class ImageAndFlowables(Flowable): signature = IImageAndFlowables klass = reportlab.platypus.flowables.ImageAndFlowables attrMapping = {'imageWidth': 'width', 'imageHeight': 'height', 'imageMask': 'mask', 'imageName': 'filename'} def process(self): flow = Flow(self.element, self.parent) flow.process() # Create the image args = dict(self.getAttributeValues( select=('imageName', 'imageWidth', 'imageHeight', 'imageMask'), attrMapping=self.attrMapping)) img = reportlab.platypus.flowables.Image(**args) # Create the flowable and add it args = dict(self.getAttributeValues( ignore=('imageName', 'imageWidth', 'imageHeight', 'imageMask'), attrMapping=self.attrMapping)) self.parent.flow.append( self.klass(img, flow.flow, **args)) class IIndent(interfaces.IRMLDirectiveSignature): """Indent the contained flowables.""" left = attr.Measurement( title='Left', description='The indentation to the left.', required=False) right = attr.Measurement( title='Right', description='The indentation to the right.', required=False) class Indent(Flowable): signature = IIndent def process(self): kw = dict(self.getAttributeValues()) # Indent self.parent.flow.append(reportlab.platypus.doctemplate.Indenter(**kw)) # Add Content flow = Flow(self.element, self.parent) flow.process() self.parent.flow += flow.flow # Dedent for name, value in kw.items(): kw[name] = -value self.parent.flow.append(reportlab.platypus.doctemplate.Indenter(**kw)) class IFixedSize(interfaces.IRMLDirectiveSignature): """Create a container flowable of a fixed size.""" width = attr.Measurement( title='Width', description='The width the flowables are allotted.', required=True) height = attr.Measurement( title='Height', description='The height the flowables are allotted.', required=True) class FixedSize(Flowable): signature = IFixedSize klass = reportlab.platypus.flowables.KeepInFrame attrMapping = {'width': 'maxWidth', 'height': 'maxHeight'} def process(self): flow = Flow(self.element, self.parent) flow.process() args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) frame = self.klass(content=flow.flow, mode='shrink', **args) self.parent.flow.append(frame) class IBookmarkPage(interfaces.IRMLDirectiveSignature): """ This creates a bookmark to the current page which can be referred to with the given key elsewhere. PDF offers very fine grained control over how Acrobat reader is zoomed when people link to this. The default is to keep the user's current zoom settings. the last arguments may or may not be needed depending on the choice of 'fitType'. """ name = attr.Text( title='Name', description='The name of the bookmark.', required=True) fit = attr.Choice( title='Fit', description='The Fit Type.', choices=('XYZ', 'Fit', 'FitH', 'FitV', 'FitR'), required=False) top = attr.Measurement( title='Top', description='The top position.', required=False) bottom = attr.Measurement( title='Bottom', description='The bottom position.', required=False) left = attr.Measurement( title='Left', description='The left position.', required=False) right = attr.Measurement( title='Right', description='The right position.', required=False) zoom = attr.Float( title='Zoom', description='The zoom level when clicking on the bookmark.', required=False) class BookmarkPage(Flowable): signature = IBookmarkPage klass = platypus.BookmarkPage attrMapping = {'name': 'key', 'fitType': 'fit'} class IBookmark(interfaces.IRMLDirectiveSignature): """ This creates a bookmark to the current page which can be referred to with the given key elsewhere. (Used inside a story.) """ name = attr.Text( title='Name', description='The name of the bookmark.', required=True) x = attr.Measurement( title='X Coordinate', description='The x-position of the bookmark.', default=0, required=False) y = attr.Measurement( title='Y Coordinate', description='The y-position of the bookmark.', default=0, required=False) class Bookmark(Flowable): signature = IBookmark klass = platypus.Bookmark attrMapping = {'name': 'key', 'x': 'relativeX', 'y': 'relativeY'} class ILink(interfaces.IRMLDirectiveSignature): """Place an internal link around a set of flowables.""" destination = attr.Text( title='Destination', description='The name of the destination to link to.', required=False) url = attr.Text( title='URL', description='The URL to link to.', required=False) boxStrokeWidth = attr.Measurement( title='Box Stroke Width', description='The width of the box border line.', required=False) boxStrokeDashArray = attr.Sequence( title='Box Stroke Dash Array', description='The dash array of the box border line.', value_type=attr.Float(), required=False) boxStrokeColor = attr.Color( title='Box Stroke Color', description=('The color in which the box border is drawn.'), required=False) class Link(Flowable): signature = ILink attrMapping = {'destination': 'destinationname', 'boxStrokeWidth': 'thickness', 'boxStrokeDashArray': 'dashArray', 'boxStrokeColor': 'color'} def process(self): flow = Flow(self.element, self.parent) flow.process() args = dict(self.getAttributeValues(attrMapping=self.attrMapping)) self.parent.flow.append(platypus.Link(flow.flow, **args)) class IHorizontalRow(interfaces.IRMLDirectiveSignature): """Create a horizontal line on the page.""" width = attr.Measurement( title='Width', description='The width of the line on the page.', allowPercentage=True, required=False) thickness = attr.Measurement( title='Thickness', description='Line Thickness', required=False) color = attr.Color( title='Color', description='The color of the line.', required=False) lineCap = attr.Choice( title='Cap', description='The cap at the end of the line.', choices=interfaces.CAP_CHOICES.keys(), required=False) spaceBefore = attr.Measurement( title='Space Before', description='The vertical space before the line.', required=False) spaceAfter = attr.Measurement( title='Space After', description='The vertical space after the line.', required=False) align = attr.Choice( title='Alignment', description='The alignment of the line within the frame.', choices=interfaces.ALIGN_TEXT_CHOICES, required=False) valign = attr.Choice( title='Vertical Alignment', description='The vertical alignment of the line.', choices=interfaces.VALIGN_TEXT_CHOICES, required=False) dash = attr.Sequence( title='Dash-Pattern', description='The dash-pattern of a line.', value_type=attr.Measurement(), default=None, required=False) class HorizontalRow(Flowable): signature = IHorizontalRow klass = reportlab.platypus.flowables.HRFlowable attrMapping = {'align': 'hAlign'} class IOutlineAdd(interfaces.IRMLDirectiveSignature): """Add a new entry to the outline of the PDF.""" title = attr.TextNode( title='Title', description='The text displayed for this item.', required=True) key = attr.Text( title='Key', description='The unique key of the item.', required=False) level = attr.Integer( title='Level', description='The level in the outline tree.', required=False) closed = attr.Boolean( title='Closed', description=('A flag to determine whether the sub-tree is closed ' 'by default.'), required=False) class OutlineAdd(Flowable): signature = IOutlineAdd klass = platypus.OutlineAdd class NamedStringFlowable(reportlab.platypus.flowables.Flowable, special.TextFlowables): def __init__(self, manager, id, value): reportlab.platypus.flowables.Flowable.__init__(self) self.manager = manager self.id = id self._value = value self.value = '' def wrap(self, *args): return (0, 0) def draw(self): text = self._getText(self._value, self.manager.canvas, include_final_tail=False) self.manager.names[self.id] = text class INamedString(interfaces.IRMLDirectiveSignature): """Defines a name for a string.""" id = attr.Text( title='Id', description='The id under which the value will be known.', required=True) value = attr.XMLContent( title='Value', description='The text that is displayed if the id is called.', required=True) class NamedString(directive.RMLDirective): signature = INamedString def process(self): id, value = self.getAttributeValues(valuesOnly=True) manager = attr.getManager(self) # We have to delay assigning values, otherwise the last one wins. self.parent.flow.append(NamedStringFlowable(manager, id, self.element)) class IShowIndex(interfaces.IRMLDirectiveSignature): """Creates an index in the document.""" name = attr.Text( title='Name', description='The name of the index.', default='index', required=False) dot = attr.Text( title='Dot', description='The character to use as a dot.', required=False) style = attr.Style( title='Style', description='The paragraph style that is applied to the index. ', required=False) tableStyle = attr.Style( title='Table Style', description='The table style that is applied to the index layout. ', required=False) class ShowIndex(directive.RMLDirective): signature = IShowIndex def process(self): args = dict(self.getAttributeValues()) manager = attr.getManager(self) index = manager.indexes[args['name']] args['format'] = index.formatFunc.__name__[8:] args['offset'] = index.offset index.setup(**args) self.parent.flow.append(index) class IBaseLogCall(interfaces.IRMLDirectiveSignature): message = attr.RawXMLContent( title='Message', description='The message to be logged.', required=True) class LogCallFlowable(reportlab.platypus.flowables.Flowable): def __init__(self, logger, level, message): self.logger = logger self.level = level self.message = message def wrap(self, *args): return (0, 0) def draw(self): self.logger.log(self.level, self.message) class BaseLogCall(directive.RMLDirective): signature = IBaseLogCall level = None def process(self): message = self.getAttributeValues( select=('message',), valuesOnly=True)[0] manager = attr.getManager(self) self.parent.flow.append( LogCallFlowable(manager.logger, self.level, message)) class ILog(IBaseLogCall): """Log message at DEBUG level.""" level = attr.Choice( title='Level', description='The default log level.', choices=interfaces.LOG_LEVELS, doLower=False, default=logging.INFO, required=True) class Log(BaseLogCall): signature = ILog @property def level(self): return self.getAttributeValues(select=('level',), valuesOnly=True)[0] class IDebug(IBaseLogCall): """Log message at DEBUG level.""" class Debug(BaseLogCall): signature = IDebug level = logging.DEBUG class IInfo(IBaseLogCall): """Log message at INFO level.""" class Info(BaseLogCall): signature = IInfo level = logging.INFO class IWarning(IBaseLogCall): """Log message at WARNING level.""" class Warning(BaseLogCall): signature = IWarning level = logging.WARNING class IError(IBaseLogCall): """Log message at ERROR level.""" class Error(BaseLogCall): signature = IError level = logging.ERROR class ICritical(IBaseLogCall): """Log message at CRITICAL level.""" class Critical(BaseLogCall): signature = ICritical level = logging.CRITICAL class IFlow(interfaces.IRMLDirectiveSignature): """A list of flowables.""" occurence.containing( occurence.ZeroOrMore('spacer', ISpacer), occurence.ZeroOrMore('illustration', IIllustration), occurence.ZeroOrMore('pre', IPreformatted), occurence.ZeroOrMore('xpre', IXPreformatted), occurence.ZeroOrMore('codesnippet', ICodeSnippet), occurence.ZeroOrMore('plugInFlowable', IPluginFlowable), occurence.ZeroOrMore('barCodeFlowable', IBarCodeFlowable), occurence.ZeroOrMore('outlineAdd', IOutlineAdd), occurence.ZeroOrMore('title', ITitle), occurence.ZeroOrMore('h1', IHeading1), occurence.ZeroOrMore('h2', IHeading2), occurence.ZeroOrMore('h3', IHeading3), occurence.ZeroOrMore('h4', IHeading4), occurence.ZeroOrMore('h5', IHeading5), occurence.ZeroOrMore('h6', IHeading6), occurence.ZeroOrMore('para', IParagraph), occurence.ZeroOrMore('blockTable', IBlockTable), occurence.ZeroOrMore('nextFrame', INextFrame), occurence.ZeroOrMore('setNextFrame', ISetNextFrame), occurence.ZeroOrMore('nextPage', INextPage), occurence.ZeroOrMore('setNextTemplate', ISetNextTemplate), occurence.ZeroOrMore('condPageBreak', IConditionalPageBreak), occurence.ZeroOrMore('keepInFrame', IKeepInFrame), occurence.ZeroOrMore('keepTogether', IKeepTogether), occurence.ZeroOrMore('img', IImage), occurence.ZeroOrMore('imageAndFlowables', IImageAndFlowables), occurence.ZeroOrMore('indent', IIndent), occurence.ZeroOrMore('fixedSize', IFixedSize), occurence.ZeroOrMore('bookmarkPage', IBookmarkPage), occurence.ZeroOrMore('bookmark', IBookmark), occurence.ZeroOrMore('link', ILink), occurence.ZeroOrMore('hr', IHorizontalRow), occurence.ZeroOrMore('showIndex', IShowIndex), occurence.ZeroOrMore('name', special.IName), occurence.ZeroOrMore('namedString', INamedString), occurence.ZeroOrMore('log', ILog), occurence.ZeroOrMore('debug', IDebug), occurence.ZeroOrMore('info', IInfo), occurence.ZeroOrMore('warning', IWarning), occurence.ZeroOrMore('error', IError), occurence.ZeroOrMore('critical', ICritical), ) class ITopPadder(interfaces.IRMLDirectiveSignature): """ TopPadder """ class TopPadder(Flowable): signature = ITopPadder klass = reportlab.platypus.flowables.TopPadder attrMapping = {} def process(self): flow = Flow(self.element, self.parent) flow.process() frame = self.klass(flow.flow[0]) self.parent.flow.append(frame) class Flow(directive.RMLDirective): factories = { # Generic Flowables 'spacer': Spacer, 'illustration': Illustration, 'pre': Preformatted, 'xpre': XPreformatted, 'codesnippet': CodeSnippet, 'plugInFlowable': PluginFlowable, 'barCodeFlowable': BarCodeFlowable, 'outlineAdd': OutlineAdd, # Paragraph-Like Flowables 'title': Title, 'h1': Heading1, 'h2': Heading2, 'h3': Heading3, 'h4': Heading4, 'h5': Heading5, 'h6': Heading6, 'para': Paragraph, # Table Flowable 'blockTable': BlockTable, # Page-level Flowables 'nextFrame': NextFrame, 'setNextFrame': SetNextFrame, 'nextPage': NextPage, 'setNextTemplate': SetNextTemplate, 'condPageBreak': ConditionalPageBreak, 'keepInFrame': KeepInFrame, 'keepTogether': KeepTogether, 'img': Image, 'imageAndFlowables': ImageAndFlowables, 'indent': Indent, 'fixedSize': FixedSize, 'bookmarkPage': BookmarkPage, 'bookmark': Bookmark, 'link': Link, 'hr': HorizontalRow, 'showIndex': ShowIndex, # Special Elements 'name': special.Name, 'namedString': NamedString, # Logging 'log': Log, 'debug': Debug, 'info': Info, 'warning': Warning, 'error': Error, 'critical': Critical, 'topPadder': TopPadder, } def __init__(self, *args, **kw): super().__init__(*args, **kw) self.flow = [] def process(self): self.processSubDirectives() return self.flow class IPTOHeader(IFlow): """A container for flowables used at the beginning of a frame. """ class PTOHeader(Flow): def process(self): self.parent.header = super().process() class IPTOTrailer(IFlow): """A container for flowables used at the end of a frame. """ class PTOTrailer(Flow): def process(self): self.parent.trailer = super().process() class IPTO(IFlow): """A container for flowables decorated with trailer & header lists. If the split operation would be called then the trailer and header lists are injected before and after the split. This allows specialist "please turn over" and "continued from previous" like behaviours. """ occurence.containing( occurence.ZeroOrOne('pto_header', IPTOHeader), occurence.ZeroOrOne('pto_trailer', IPTOTrailer), ) class PTO(Flow): signature = IPTO klass = reportlab.platypus.flowables.PTOContainer factories = dict( pto_header=PTOHeader, pto_trailer=PTOTrailer, **Flow.factories ) header = None trailer = None def process(self): flow = super().process() self.parent.flow.append( self.klass(flow, self.trailer, self.header))
z3c.rml
/z3c.rml-4.4.0.tar.gz/z3c.rml-4.4.0/src/z3c/rml/flowable.py
flowable.py
import lxml.etree import sys import z3c.rml.rml2pdf import z3c.rmldocument.interfaces import zope.interface import zope.pagetemplate.pagetemplatefile class DocumentPageTemplateFile( zope.pagetemplate.pagetemplatefile.PageTemplateFile): def __init__(self, *args, **kw): super(DocumentPageTemplateFile, self).__init__(*args, **kw) self.content_type = 'text/xml' def get_path_from_prefix(self, _prefix): # Had to copy this because of fixed _getframe implementation in the # base class. if isinstance(_prefix, str): path = _prefix else: if _prefix is None: _prefix = sys._getframe(3).f_globals path = zope.pagetemplate.pagetemplatefile.package_home(_prefix) return path def pt_getContext(self, args, kwargs): document = args[0] context = dict( document=document, fields=document.fields, blocks=document.blocks) return context def preprocess_block(block, data): """Preprocess a given block of para-RML to RML. """ if block is None: return '' root = lxml.etree.fromstring('<rmlblock xmlns:doc="http://xml.gocept.com/namespaces/rmldoc">'+block+'</rmlblock>') # Process all value substitutions for element in root.getiterator(): if element.tag != "{http://xml.gocept.com/namespaces/rmldoc}data": continue value = getattr(data, element.get('field')) text = str(value) + (element.tail or '') previous = element.getprevious() parent = element.getparent() if previous is not None: previous.tail = (previous.tail or '') + text else: parent.text = (parent.text or '') + text parent.remove(element) # Remove artificial <rmlblock> tags xml = lxml.etree.tostring(root) xml = xml[xml.find('>')+1:] xml = xml[:xml.rfind('<')] return xml class Bag(object): """An attribute bag.""" pass class Document(object): """An RML document definition.""" zope.interface.implements(z3c.rmldocument.interfaces.IDocument) encoding = 'utf-8' field_schema = zope.interface.Interface block_schema = zope.interface.Interface def __init__(self, context): self.context = context self.fields = self.field_schema(context) self._setup_blocks() def _setup_blocks(self): raw_blocks = self.block_schema(self.context) self.blocks = Bag() for block_name in self.block_schema: block_text = getattr(raw_blocks, block_name) block_text = preprocess_block(block_text, self.fields) setattr(self.blocks, block_name, block_text) def __call__(self, raw=False): rml = self.template(self).encode(self.encoding) if raw: return rml return z3c.rml.rml2pdf.parseString(rml).getvalue()
z3c.rmldocument
/z3c.rmldocument-1.0.tar.gz/z3c.rmldocument-1.0/src/z3c/rmldocument/document.py
document.py
Defining documents ================== A document represents a specific document that a user might request from the system. This can be e.g. the terms and conditions of a service, a contract, an invoice, etc. The developer provides a basic page template that renders RML and that can include other blocks of RML given by the application. This can be used to allow administrators to locally adjust the developer templates with additional text that are specific to the installation. Additionally the developer provides a set of fields that can be used to customize the document on a per-document basis, e.g. with the client's name. >>> from z3c.rmldocument.document import Document, DocumentPageTemplateFile >>> import zope.interface >>> import zope.schema >>> class IContractBlocks(zope.interface.Interface): ... introduction = zope.schema.Text(title=u"Introductory text") >>> class IContractData(zope.interface.Interface): ... salutation = zope.schema.TextLine(title=u"Salutation") ... years = zope.schema.Int(title=u"Years to go") >>> class Contract(object): ... zope.interface.implements(IContractBlocks, IContractData) ... introduction = """<para> ... Everything will be fine in <doc:data field="years">Jahre seit Foo</doc:data> years. ... </para>""" ... salutation = u"Mr. Steve" ... years = 4 >>> class ServiceContract(Document): ... ... template = DocumentPageTemplateFile(EXAMPLE % 1) ... ... block_schema = IContractBlocks ... data_schema = IContractData Out of this document, we can produce RML that can be rendered into PDF later: >>> theuni = Contract() >>> contract_theuni = ServiceContract(theuni) >>> print contract_theuni(raw=True) <?xml version="1.0" encoding="utf-8" standalone="no"?> <!DOCTYPE document SYSTEM "rml.dtd"> <document filename="service-contract.pdf"> <template> <pageTemplate id="main"> <frame id="first" x1="1cm" y1="1cm" width="19cm" height="26cm"/> </pageTemplate> </template> <story> <heading>Mr. Steve</heading> <para> Everything will be fine in 4 years. </para> <para>Best regards,<br/>Peter</para> </story> </document>
z3c.rmldocument
/z3c.rmldocument-1.0.tar.gz/z3c.rmldocument-1.0/src/z3c/rmldocument/README.txt
README.txt
Introduction ============ This skin is a derivative of the zope.app.rotterdam.Rotterdam skin, which supports pagelets, forms and javascript forms. Usage ===== z3c.rotterdam includes the information needed to configure itself. To add it to your configuration; 1. Add it to your buildout... eggs=... z3c.rotterdam 2. To use the skin, you can use a traversal adapter: http://localhost:8080/++skin++z3c_rotterdam/index.html 3. To configure this as your default skin, add this line to your site.zcml file: &lt;includeOverrides package="z3c.rotterdam" file="default_skin.zcml" /&gt;
z3c.rotterdam
/z3c.rotterdam-1.0.2.tar.gz/z3c.rotterdam-1.0.2/README.txt
README.txt
z3c.rotterdam.Rotterdam ======================== This skin is a derivative of the zope.app.rotterdam.Rotterdam skin, which supports pagelets, forms and javascript forms. It includes the information needed to configure itself. To add it to your configuration; 1. Add it to your buildout... eggs=... z3c.rotterdam 2. To use the skin, you can use a traversal adapter: http://localhost:8080/++skin++z3c_rotterdam/index.html 3. To configure this as your default skin, add this line to your site.zcml file: <includeOverrides package="z3c.rotterdam" file="default_skin.zcml" /> ---------------------------------------------------------------------------- >>> from zope.testbrowser.testing import Browser >>> browser = Browser() >>> browser.addHeader('Authorization', 'Basic mgr:mgrpw') >>> browser.handleErrors = False Verify that a standard view works with the z3c.rotterdam skin >>> browser.open('http://localhost/++skin++z3c_rotterdam/@@contents.html') >>> browser.url 'http://localhost/++skin++z3c_rotterdam/@@contents.html' Make sure the edit form "works": >>> browser.open( ... 'http://localhost/++skin++z3c_rotterdam/+/zope.app.dtmlpage.DTMLPage=') A demo pagelet is defined in demo.py. Load the pagelet. >>> browser.open('http://localhost/++skin++z3c_rotterdam/@@demo.html') >>> browser.contents '...PAGELET CONTENT...' Verify standard viewlets >>> browser.open('http://localhost/++skin++z3c_rotterdam/@@demo.html') >>> browser.contents '...demo.css...' >>> browser.contents '...demo.js...' Verify that the CSS for forms is included >>> browser.open('http://localhost/++skin++z3c_rotterdam/@@demo_form.html') >>> browser.contents '...div-form.css...' Verify that formjs works >>> browser.open('http://localhost/++skin++z3c_rotterdam/@@demo_formjs.html') >>> browser.contents '...div-form.css...' >>> browser.contents '...jquery.js...' >>> browser.contents '...alert...'
z3c.rotterdam
/z3c.rotterdam-1.0.2.tar.gz/z3c.rotterdam-1.0.2/z3c/rotterdam/README.txt
README.txt
z3c.saconfig ************ 1.0 (2023-06-13) ================ - Add support for Python 3.9, 3.10, 3.11. - Drop support for Python 2.7, 3.5, 3.6. - Update tests to run with SQLAlchemy 2. (There are no guaranties that they still run with older versions.) - Ignore ``convert_unicode`` parameter in ZCML ``engine`` directive, as it is no longer supported by SQLAlchemy 2. 0.16.0 (2020-04-03) =================== - Added support for Python 3.7 [nazrulworld] - Added support for Python 3.8 [icemac] - Added support for zope.sqlalchemy >= 1.2 [cklinger] - Updated local bootstrap.py [cklinger] - Use newer SQLAlchemy for tests [cklinger] 0.15 (2018-11-30) ================= - Added Python 3.5 and 3.6 compatibility [nazrulworld] - fix: `Issue with python3 compatibility, on zope interface implementation <https://github.com/zopefoundation/z3c.saconfig/issues/4>`_ [nazrulworld] 0.14 (2015-06-29) ================= - Drop support for sqlalchemy < 0.5 [oggers] 0.13 (2011-07-26) ================= - Register engine factory setup using a zcml action 0.12 (2010-09-28) ================= - EngineCreatedEvent also gets ``engine_args`` and ``engine_kw`` as attributes, so that event handlers can potentially differentiate between engines. 0.11 (2010-07-05) ================= - Add pool_size, max_overflow, pool_recycle and pool_timeout options to the <engine /> directive. This allows connection pooling options to be defined in ZCML. - works with sqlalchemy >= 0.5 (wouldn't work with sqlalchemy > 5 prior) 0.10 (2010-01-18) ================= - Support current ZTK code - engine.echo must default to None for SQLAlchemy to honor logging.getLogger("sqlalchemy.engine").setLevel(...) - Do not enable convert_unicode by default. This option changes standard SQLAlchemy behaviour by making String type columns return unicode data. This can be especially painful in Zope2 environments where unicode is not always accepted. - Add a convert_unicode option to the zcml engine statement, allowing people who need convert_unicode to enable it. 0.9.1 (2009-08-14) ================== - Include documentation on PyPI. - Small documentation tweaks. 0.9 (2009-08-14) ================ - Initial public release.
z3c.saconfig
/z3c.saconfig-1.0.tar.gz/z3c.saconfig-1.0/CHANGES.rst
CHANGES.rst
Installation ************ Introduction ============ Normally this code would be set up an as egg. If you want help with development, you can install it as a buildout. Installation ============ This package can be checked out from https://github.com/zopefoundation/z3c.saconfig. You can then execute the buildout to download and install the requirements and install the test runner. Using your desired python run:: $ python3 -m venv . $ bin/pip install -r requirements.txt If installation configuration changes later, you need to run:: $ bin/buildout Running the tests ================= After running the buildout, you can run the test script like this:: $ bin/test By default, the tests are run against an in-memory SQLite database. To enable testing with your own database set the ``TEST_DSN`` and ``TEST_DSN2`` environment variables to your sqlalchemy database dsn:: $ export TEST_DSN=postgres://test:test@localhost/test Since the tests also need access to a second, independent database, you also need to define a TEST_DSN2 that points to a different database:: $ export TEST_DSN2=postgres://test:test@localhost/test2 Two-phase commit behaviour may be tested by setting the TEST_TWOPHASE variable to a non empty string. e.g:: $ export TEST_TWOPHASE=True bin/test
z3c.saconfig
/z3c.saconfig-1.0.tar.gz/z3c.saconfig-1.0/INSTALL.rst
INSTALL.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.
z3c.saconfig
/z3c.saconfig-1.0.tar.gz/z3c.saconfig-1.0/LICENSE.rst
LICENSE.rst
z3c.saconfig ************ Introduction ============ This aim of this package is to offer a simple but flexible way to configure SQLAlchemy's scoped session support using the Zope component architecture. This package is based on ``zope.sqlalchemy``, which offers transaction integration between Zope and SQLAlchemy. We sketch out two main scenarios here: * one database per Zope instance. * one database per site (or Grok application) in a Zope instance (and thus multiple databases per Zope instance). GloballyScopedSession (one database per Zope instance) ====================================================== The simplest way to set up SQLAlchemy for Zope is to have a single thread-scoped session that's global to your entire Zope instance. Multiple applications will all share this session. The engine is set up with a global utility. We use the SQLAlchemy ``sqlalchemy.ext.declarative`` extension to define some tables and classes:: >>> from sqlalchemy import * >>> from sqlalchemy.orm import declarative_base >>> from sqlalchemy.orm import relationship >>> Base = declarative_base() >>> class User(Base): ... __tablename__ = 'test_users' ... id = Column('id', Integer, primary_key=True) ... name = Column('name', String(50)) ... addresses = relationship("Address", backref="user") >>> class Address(Base): ... __tablename__ = 'test_addresses' ... id = Column('id', Integer, primary_key=True) ... email = Column('email', String(50)) ... user_id = Column('user_id', Integer, ForeignKey('test_users.id')) So far this doesn't differ from the ``zope.sqlalchemy`` example. We now arrive at the first difference. Instead of making the engine directly, we can set up the engine factory as a (global) utility. This utility makes sure an engine is created and cached for us. >>> from z3c.saconfig import EngineFactory >>> engine_factory = EngineFactory(TEST_DSN) You can pass the parameters you'd normally pass to ``sqlalchemy.create_engine`` to ``EngineFactory``. We now register the engine factory as a global utility using ``zope.component``. Normally you'd use either ZCML or Grok to do this confirmation, but we'll do it manually here:::: >>> from zope import component >>> from z3c.saconfig.interfaces import IEngineFactory >>> component.provideUtility(engine_factory, provides=IEngineFactory) Note that setting up an engine factory is not actually necessary in the globally scoped use case. You could also just create the engine as a global and pass it as ``bind`` when you create the ``GloballyScopedSession`` later. Let's look up the engine by calling the factory and create the tables in our test database:: >>> engine = engine_factory() >>> Base.metadata.create_all(engine) Now as for the second difference from ``zope.sqlalchemy``: how the session is set up and used. We'll use the ``GloballyScopedSession`` utility to implement our session creation:: >>> from z3c.saconfig import GloballyScopedSession We give the constructor to ``GloballyScopedSession`` the parameters you'd normally give to ``sqlalchemy.orm.create_session``, or ``sqlalchemy.orm.sessionmaker``:: >>> utility = GloballyScopedSession(twophase=TEST_TWOPHASE) ``GlobalScopedSession`` looks up the engine using ``IEngineFactory`` if you don't supply your own ``bind`` argument. ``GloballyScopedSession`` also automatically sets up the ``autocommit``, ``autoflush`` and ``extension`` parameters to be the right ones for Zope integration, so normally you wouldn't need to supply these, but you could pass in your own if you do need it. We now register this as an ``IScopedSession`` utility:: >>> from z3c.saconfig.interfaces import IScopedSession >>> component.provideUtility(utility, provides=IScopedSession) We are done with configuration now. As you have seen it involves setting up two utilities, ``IEngineFactory`` and ``IScopedSession``, where only the latter is really needed in this globally shared session use case. After the ``IScopedSession`` utility is registered, one can import the ``Session`` class from z3c.saconfig. This ``Session`` class is like the one you'd produce with ``sessionmaker`` from SQLAlchemy. `z3c.saconfig.Session`` is intended to be the only ``Session`` class you'll ever need, as all configuration and Zope integration is done automatically for you by ``z3c.saconfig``, appropriate the context in Zope where you use it. There is no need to create ``Session`` classes yourself with ``sessionmaker`` or ``scoped_sesion`` anymore. We can now use the ``Session`` class to create a session which will behave according to the utility we provided:: >>> from z3c.saconfig import Session >>> session = Session() Now things go the usual ``zope.sqlalchemy`` way, which is like ``SQLAlchemy`` except you can use Zope's ``transaction`` module:: >>> session.query(User).all() [] >>> import transaction >>> session.add(User(name='bob')) >>> transaction.commit() >>> session = Session() >>> bob = session.query(User).all()[0] >>> bob.name == 'bob' True >>> bob.addresses [] Events ====== When a new engine is created by an ``EngineFactory``, an ``IEngineCreatedEvent`` is fired. This event has an attribute ``engine`` that contains the engine that was just created:: >>> from z3c.saconfig.interfaces import IEngineCreatedEvent >>> @component.adapter(IEngineCreatedEvent) ... def createdHandler(event): ... print("created engine") ... print("args: {0}".format(event.engine_args)) ... print("kw: {0}".format(event.engine_kw)) >>> component.provideHandler(createdHandler) >>> event_engine_factory = EngineFactory(TEST_DSN1) >>> engine = event_engine_factory() created engine args: ('sqlite:///:memory:',) kw: {} Let's get rid of the event handler again:: >>> sm = component.getSiteManager() >>> sm.unregisterHandler(None, ... required=[IEngineCreatedEvent]) True SiteScopedSession (one database per site) ========================================= In the example above we have set up SQLAlchemy with Zope using utilities, but it did not gain us very much, except that you can just use ``zope.sqlalchemy.Session`` to get the correct session. Now we'll see how we can set up different engines per site by registering the engine factory as a local utility for each one. In order to make this work, we'll set up ``SiteScopedSession`` instead of ``GloballyScopedSession``. We need to subclass ``SiteScopedSession`` first because we need to implement its ``siteScopeFunc`` method, which should return a unique ID per site (such as a path retrieved by ``zope.traversing.api.getPath``). We need to implement it here, as ``z3c.saconfig`` leaves this policy up to the application or a higher-level framework:: >>> from z3c.saconfig import SiteScopedSession >>> class OurSiteScopedSession(SiteScopedSession): ... def siteScopeFunc(self): ... return getSite().id # the dummy site has a unique id >>> utility = OurSiteScopedSession() >>> component.provideUtility(utility, provides=IScopedSession) We want to register two engine factories, each in a different site:: >>> engine_factory1 = EngineFactory(TEST_DSN1) >>> engine_factory2 = EngineFactory(TEST_DSN2) We need to set up the database in both new engines:: >>> Base.metadata.create_all(engine_factory1()) >>> Base.metadata.create_all(engine_factory2()) Let's now create two sites, each of which will be connected to another engine:: >>> site1 = DummySite(id=1) >>> site2 = DummySite(id=2) We set the local engine factories for each site: >>> sm1 = site1.getSiteManager() >>> sm1.registerUtility(engine_factory1, provided=IEngineFactory) >>> sm2 = site2.getSiteManager() >>> sm2.registerUtility(engine_factory2, provided=IEngineFactory) Just so we don't accidentally get it, we'll disable our global engine factory:: >>> component.provideUtility(None, provides=IEngineFactory) When we set the site to ``site1``, a lookup of ``IEngineFactory`` gets us engine factory 1:: >>> setSite(site1) >>> component.getUtility(IEngineFactory) is engine_factory1 True And when we set it to ``site2``, we'll get engine factory 2:: >>> setSite(site2) >>> component.getUtility(IEngineFactory) is engine_factory2 True We can look up our global utility even if we're in a site:: >>> component.getUtility(IScopedSession) is utility True Phew. That was a lot of set up, but basically this is actually just straightforward utility setup code; you should use the APIs or Grok's ``grok.local_utility`` directive to set up local utilities. Now all that is out of the way, we can create a session for ``site1``:: >>> setSite(site1) >>> session = Session() The database is still empty:: >>> session.query(User).all() [] We'll add something to this database now:: >>> session.add(User(name='bob')) >>> transaction.commit() ``bob`` is now there:: >>> session = Session() >>> session.query(User).all()[0].name == 'bob' True Now we'll switch to ``site2``:: >>> setSite(site2) If we create a new session now, we should now be working with a different database, which should still be empty:: >>> session = Session() >>> session.query(User).all() [] We'll add ``fred`` to this database:: >>> session.add(User(name='fred')) >>> transaction.commit() Now ``fred`` is indeed there:: >>> session = Session() >>> users = session.query(User).all() >>> len(users) 1 >>> users[0].name == 'fred' True And ``bob`` is still in ``site1``:: >>> setSite(site1) >>> session = Session() >>> users = session.query(User).all() >>> len(users) 1 >>> users[0].name == 'bob' True Engines and Threading ===================== >>> engine = None >>> def setEngine(): ... global engine ... engine = engine_factory1() Engine factories must produce the same engine: >>> setEngine() >>> engine is engine_factory1() True Even if you call it in a different thread: >>> import threading >>> engine = None >>> t = threading.Thread(target=setEngine) >>> t.start() >>> t.join() >>> engine is engine_factory1() True Unless they are reset: >>> engine_factory1.reset() >>> engine is engine_factory1() False Even engine factories with the same parameters created at (almost) the same time should produce different engines: >>> EngineFactory(TEST_DSN1)() is EngineFactory(TEST_DSN1)() False Configuration using ZCML ======================== A configuration directive is provided to register a database engine factory using ZCML. >>> from io import BytesIO >>> from zope.configuration import xmlconfig >>> import z3c.saconfig >>> xmlconfig.XMLConfig('meta.zcml', z3c.saconfig)() Let's try registering the directory again. >>> xmlconfig.xmlconfig(BytesIO(b""" ... <configure xmlns="http://namespaces.zope.org/db"> ... <engine name="dummy" url="sqlite:///:memory:" /> ... </configure>""")) >>> component.getUtility(IEngineFactory, name="dummy") <z3c.saconfig.utility.EngineFactory object at ...> This time with a setup call. >>> xmlconfig.xmlconfig(BytesIO(b""" ... <configure xmlns="http://namespaces.zope.org/db"> ... <engine name="dummy2" url="sqlite:///:memory:" ... setup="z3c.saconfig.tests.engine_subscriber" /> ... </configure>""")) got: Engine(sqlite:///:memory:) It's also possible to specify connection pooling options: >>> xmlconfig.xmlconfig(BytesIO(b""" ... <configure xmlns="http://namespaces.zope.org/db"> ... <engine name="dummy" url="sqlite:///:memory:" ... pool_size="1" ... max_overflow="2" ... pool_recycle="3" ... pool_timeout="4" ... /> ... </configure>""")) >>> engineFactory = component.getUtility(IEngineFactory, name="dummy") >>> engineFactory._kw == {'echo': None, 'pool_size': 1, 'max_overflow': 2, 'pool_recycle': 3, 'pool_timeout': 4} True (See the SQLAlchemy documentation on connection pooling for details on how these arguments are used.) The session directive is provided to register a scoped session utility: >>> xmlconfig.xmlconfig(BytesIO(b""" ... <configure xmlns="http://namespaces.zope.org/db"> ... <session name="dummy" engine="dummy2" /> ... </configure>""")) >>> component.getUtility(IScopedSession, name="dummy") <z3c.saconfig.utility.GloballyScopedSession object at ...> >>> from z3c.saconfig import named_scoped_session >>> factory = component.getUtility(IEngineFactory, name="dummy2") >>> Session = named_scoped_session('dummy') >>> Session().bind is factory() True
z3c.saconfig
/z3c.saconfig-1.0.tar.gz/z3c.saconfig-1.0/src/z3c/saconfig/README.rst
README.rst
import warnings import zope.component.zcml import zope.interface import zope.schema from zope.component.security import PublicPermission from zope.configuration.name import resolve from .interfaces import IEngineFactory from .interfaces import IScopedSession from .utility import EngineFactory class IEngineDirective(zope.interface.Interface): """Registers a database engine factory.""" url = zope.schema.URI( title='Database URL', description="e.g. 'sqlite:///:memory:'.", required=True) name = zope.schema.Text( title="Engine name", description="Empty if this is the default engine.", required=False, default='') convert_unicode = zope.schema.Bool( title='Convert all string columns to unicode', description='This setting makes the SQLAlchemy String column type ' 'equivalent to UnicodeString. Do not use this unless ' 'there is a good reason not to use standard ' 'UnicodeString columns', required=False, default=False) echo = zope.schema.Bool( title='Echo SQL statements', description='Enable logging statements for debugging.', required=False, default=None) setup = zope.schema.BytesLine( title='After engine creation hook', description='Callback for creating mappers etc. ' 'One argument is passed, the engine', required=False, default=None) # Connection pooling options - probably only works on SQLAlchemy 0.5 and up pool_size = zope.schema.Int( title="The size of the pool to be maintained", description="Defaults to 5 in SQLAlchemy.", required=False) max_overflow = zope.schema.Int( title="The maximum overflow size of the pool.", description="When the number of checked-out connections " "reaches the size set in pool_size, additional " "connections will be returned up to this limit. " "Defaults to 10 in SQLAlchemy", required=False) pool_recycle = zope.schema.Int( title="Number of seconds between connection recycling", description="Upon checkout, if this timeout is " "surpassed the connection will be closed and " "replaced with a newly opened connection", required=False) pool_timeout = zope.schema.Int( title="The number of seconds to wait before giving up on " "returning a connection.", description="Defaults to 30 in SQLAlchemy if not set", required=False) class ISessionDirective(zope.interface.Interface): """Registers a database scoped session""" name = zope.schema.Text( title="Scoped session name", description="Empty if this is the default session.", required=False, default="") twophase = zope.schema.Bool( title='Use two-phase commit', description='Session should use two-phase commit', required=False, default=False) engine = zope.schema.Text( title="Engine name", description="Empty if this is to use the default engine.", required=False, default="") factory = zope.schema.DottedName( title='Scoped Session utility factory', description='GloballyScopedSession by default', required=False, default="z3c.saconfig.utility.GloballyScopedSession") def engine(_context, url, name="", convert_unicode=False, echo=None, setup=None, twophase=False, pool_size=None, max_overflow=None, pool_recycle=None, pool_timeout=None): if convert_unicode: # pragma: no cover warnings.warn( '`convert_unicode` is no longer suported by SQLAlchemy, so it is' ' ignored here.', DeprecationWarning) kwargs = { 'echo': echo, } # Only add these if they're actually set, since we want to let SQLAlchemy # control the defaults if pool_size is not None: kwargs['pool_size'] = pool_size if max_overflow is not None: kwargs['max_overflow'] = max_overflow if pool_recycle is not None: kwargs['pool_recycle'] = pool_recycle if pool_timeout is not None: kwargs['pool_timeout'] = pool_timeout factory = EngineFactory(url, **kwargs) zope.component.zcml.utility( _context, provides=IEngineFactory, component=factory, permission=PublicPermission, name=name) if setup: if isinstance(setup, bytes): setup = setup.decode() if _context.package is None: callback = resolve(setup) else: callback = resolve(setup, package=_context.package.__name__) _context.action( discriminator=(IEngineFactory, name), callable=callback, args=(factory(), ), order=9999) def session(_context, name="", engine="", twophase=False, factory="z3c.saconfig.utility.GloballyScopedSession"): if _context.package is None: ScopedSession = resolve(factory) else: ScopedSession = resolve(factory, package=_context.package.__name__) scoped_session = ScopedSession(engine=engine, twophase=twophase) zope.component.zcml.utility( _context, provides=IScopedSession, component=scoped_session, permission=PublicPermission, name=name)
z3c.saconfig
/z3c.saconfig-1.0.tar.gz/z3c.saconfig-1.0/src/z3c/saconfig/zcml.py
zcml.py
from zope.interface import Attribute from zope.interface import Interface from zope.interface import implementer class IScopedSession(Interface): """A utility that plugs into SQLAlchemy's scoped session machinery. The idea is that you'd either register a IScopedSession utility globally, for simple configurations, or locally, if you want to have the ability to transparently use a different engine and session configuration per database. """ def sessionFactory(): """Create a SQLAlchemy session. Typically you'd use sqlalchemy.orm.create_session to create the session here. """ def scopeFunc(): """Determine the scope of the session. This can be used to scope the session per thread, per Zope 3 site, or otherwise. Return an immutable value to scope the session, like a thread id, or a tuple with thread id and application id. """ class ISiteScopedSession(IScopedSession): """A utility that makes sessions be scoped by site. """ def siteScopeFunc(): """Returns a unique id per site. """ class IEngineFactory(Interface): """A utility that maintains an SQLAlchemy engine. If the engine isn't created yet, it will create it. Otherwise the engine will be cached. """ def __call__(): """Get the engine. This creates the engine if this factory was not used before, otherwise returns a cached version. """ def configuration(): """Returns the engine configuration in the form of an args, kw tuple. Return the parameters used to create an engine as a tuple with an args list and a kw dictionary. """ def reset(): """Reset the cached engine (if any). This causes the engine to be recreated on next use. """ class IEngineCreatedEvent(Interface): """An SQLAlchemy engine has been created. Hook into this event to do setup that can only be performed with an active engine. """ engine = Attribute("The engine that was just created.") engine_args = Attribute("List of arguments given to SQLAlchemy " "create_engine") engine_kw = Attribute("Dictionary of keyword attributes given to " "SQLAlchemy create_engine") @implementer(IEngineCreatedEvent) class EngineCreatedEvent: def __init__(self, engine, engine_args, engine_kw): self.engine = engine self.engine_args = engine_args self.engine_kw = engine_kw
z3c.saconfig
/z3c.saconfig-1.0.tar.gz/z3c.saconfig-1.0/src/z3c/saconfig/interfaces.py
interfaces.py
import threading import time from threading import get_ident import sqlalchemy from zope import component from zope.event import notify from zope.interface import implementer from zope.sqlalchemy import register from z3c.saconfig.interfaces import EngineCreatedEvent from z3c.saconfig.interfaces import IEngineFactory from z3c.saconfig.interfaces import IScopedSession from z3c.saconfig.interfaces import ISiteScopedSession SESSION_DEFAULTS = dict( autocommit=False, autoflush=True, ) @implementer(IScopedSession) class GloballyScopedSession: """A globally scoped session. Register this as a global utility to have just one kind of session per Zope instance. All applications in this instance will share the same session. To register as a global utility you may need to register it with a custom factory, or alternatively subclass it and override __init__ to pass the right arguments to the superclasses __init__. """ def __init__(self, engine='', **kw): """Pass keywords arguments for sqlalchemy.orm.create_session. The `engine` argument is the name of a utility implementing IEngineFactory. Note that GloballyScopedSesssion does have different defaults than ``create_session`` for various parameters where it makes sense for Zope integration, namely: autocommit = False autoflush = True extension = ZopeTransactionExtension() Normally you wouldn't pass these in, but if you have the need to override them, you could. """ self.engine = engine self.kw = _zope_session_defaults(kw) def sessionFactory(self): kw = self.kw.copy() if 'bind' not in kw: engine_factory = component.getUtility(IEngineFactory, name=self.engine) kw['bind'] = engine_factory() session = sqlalchemy.orm.create_session(**kw) register(session) return session def scopeFunc(self): return get_ident() def _zope_session_defaults(kw): """Adjust keyword parameters with proper defaults for Zope. """ d = SESSION_DEFAULTS.copy() d.update(kw) return d @implementer(ISiteScopedSession) class SiteScopedSession: """A session that is scoped per site. Even though this makes the sessions scoped per site, the utility can be registered globally to make this work. Creation arguments as for GloballyScopedSession, except that no ``bind`` parameter should be passed. This means it is possible to create a SiteScopedSession utility without passing parameters to its constructor. """ def __init__(self, engine='', **kw): assert 'bind' not in kw self.engine = engine self.kw = _zope_session_defaults(kw) def sessionFactory(self): engine_factory = component.getUtility(IEngineFactory, name=self.engine) kw = self.kw.copy() kw['bind'] = engine_factory() session = sqlalchemy.orm.create_session(**kw) register(session) return session def scopeFunc(self): return (get_ident(), self.siteScopeFunc()) def siteScopeFunc(self): raise NotImplementedError # Credits: This method of storing engines lifted from zope.app.cache.ram _COUNTER = 0 _COUNTER_LOCK = threading.Lock() _ENGINES = {} _ENGINES_LOCK = threading.Lock() @implementer(IEngineFactory) class EngineFactory: """An engine factory. If you need engine connection parameters to be different per site, EngineFactory should be registered as a local utility in that site. If you want this utility to be persistent, you should subclass it and mixin Persistent. You could then manage the parameters differently than is done in this __init__, for instance as attributes, which is nicer if you are using Persistent (or Zope 3 schema). In this case you need to override the configuration method. """ def __init__(self, *args, **kw): self._args = args self._kw = kw self._key = self._getKey() def _getKey(self): """Get a unique key""" global _COUNTER _COUNTER_LOCK.acquire() try: _COUNTER += 1 return "%s_%f_%d" % (id(self), time.time(), _COUNTER) finally: _COUNTER_LOCK.release() def __call__(self): # optimistically try get without lock engine = _ENGINES.get(self._key, None) if engine is not None: return engine # no engine, lock and redo _ENGINES_LOCK.acquire() try: # need to check, another thread may have got there first if self._key not in _ENGINES: args, kw = self.configuration() _ENGINES[self._key] = engine = sqlalchemy.create_engine( *args, **kw) notify(EngineCreatedEvent(engine, args, kw)) return _ENGINES[self._key] finally: _ENGINES_LOCK.release() def configuration(self): """Returns engine parameters. This can be overridden in a subclass to retrieve the parameters from some other place. """ return self._args, self._kw def reset(self): _ENGINES_LOCK.acquire() try: if self._key not in _ENGINES: return # XXX is disposing the right thing to do? _ENGINES[self._key].dispose() del _ENGINES[self._key] finally: _ENGINES_LOCK.release()
z3c.saconfig
/z3c.saconfig-1.0.tar.gz/z3c.saconfig-1.0/src/z3c/saconfig/utility.py
utility.py
import os, shutil, sys, tempfile from optparse import OptionParser tmpeggs = tempfile.mkdtemp() 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 --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", help="use a specific zc.buildout 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")) options, args = parser.parse_args() ###################################################################### # load/install distribute to_reload = False try: import pkg_resources, setuptools if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen exec(urlopen('http://python-distribute.org/distribute_setup.py').read(), ez) setup_args = dict(to_dir=tmpeggs, download_delay=0, no_fake=True) ez['use_setuptools'](**setup_args) if to_reload: reload(pkg_resources) 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 cmd = [sys.executable, '-c', '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]) distribute_path = ws.find( pkg_resources.Requirement.parse('distribute')).location requirement = 'zc.buildout' version = options.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): 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=[distribute_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, env=dict(os.environ, PYTHONPATH=distribute_path)) != 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)
z3c.sampledata
/z3c.sampledata-2.0.0a1.zip/z3c.sampledata-2.0.0a1/bootstrap.py
bootstrap.py
import os import transaction from ZODB.FileStorage import FileStorage from zope import component from zope import schema from zope.app.appsetup import database from zope.app.testing import functional from zope.app.publication.zopepublication import ZopePublication from z3c.sampledata.interfaces import ISampleManager class BufferedDatabaseTestLayer(object): """A test layer which creates a sample database. The created database is later used without the need to run through the sample generation again. This speeds up functional tests. """ __name__ = "BufferedTestLayer" __bases__ = (functional.Functional,) sampleManager = 'samplesite' seed = 'Seed' path = None def setUp(self): deleteSet = ' /\\,' name = ''.join([c for c in self.sampleManager if c not in deleteSet]) dbpath = self.path dbDirName = 'var_%s' % name if dbDirName not in os.listdir(dbpath): os.mkdir(os.path.join(dbpath, dbDirName)) filename = os.path.join(dbpath, dbDirName, 'TestData.fs') fsetup = functional.FunctionalTestSetup() self.original = fsetup.base_storage if not os.path.exists(filename): # Generate a new database from scratch and fill it with sample data db = database(filename) connection = db.open() root = connection.root() app = root[ZopePublication.root_name] # get the sample data manager manager = component.getUtility(ISampleManager, name=self.sampleManager) # create the parameters needed param = self._createParam(manager) # generate the sample data manager.generate(app, param, self.seed) transaction.commit() connection.close() db.close() # sets up the db stuff normal fsetup.setUp() # replace the storage with our filestorage fsetup.base_storage = FileStorage(filename) # override close on this instance, so files dont get closed on # setup/teardown of functionsetup fsetup.base_storage.close = lambda : None def tearDown(self): fsetup = functional.FunctionalTestSetup() # close the filestorage files now by calling the original # close on our storage instance FileStorage.close(fsetup.base_storage) fsetup.base_storage = self.original fsetup.tearDown() fsetup.tearDownCompletely() def _createParam(self, manager): # create the neccessary parameters from the schemas ret = {} plugins = manager.orderedPlugins() for plugin in plugins: ret[plugin.name] = data = {} iface = plugin.generator.schema if iface is not None: for name, field in schema.getFieldsInOrder(iface): data[name] = field.default or field.missing_value return ret
z3c.sampledata
/z3c.sampledata-2.0.0a1.zip/z3c.sampledata-2.0.0a1/src/z3c/sampledata/layer.py
layer.py
"""Interfaces """ import zope.interface import zope.schema from z3c.sampledata import _ class ISampleDataPlugin(zope.interface.Interface): """A plugin that generates some sample data. These plugins may depend on other sample data plugins. Say, calendar event generators depend on person generators. All plugins have unique names and other plugins reference their dependencies by these names. """ dependencies = zope.schema.List( title=u"A list of dependenies", value_type=zope.schema.Id(title=u"Sample data generator name"), description=u""" A list of names of sample data generators this one depends on. """) schema = zope.schema.InterfaceField( title=u"Parameters", description=u"The schema which provides the parameters.", ) def generate(context, param={}, dataSource=None, seed=None): """Generate sample data of this plugin. This method assumes the sample data this plugin depends on has been created. """ class ISampleManager(zope.interface.Interface): """A sample manager manages the generation of sample data. The manager uses a list of sample generators. """ name = zope.schema.TextLine( title = _(u'Name'), description = _(u'The unique name of the sample manager'), ) def addSource(name, data): """Add a new data source to the manager. A data source can be assigned to generator plugins. """ def add(generator, param={}, dataSource=None, dependsOn=[], contextFrom=None): """Add a generator to the manager. generator: The name of a utility providing 'ISampleDataPlugin'. dataSource The name of the data source for the generator. dependsOn: The names of generators this generator depends on. This is used in addition to the dependencies defined in the generator. contextFrom: The context for the plugin is the output of this plugin. This plugin is automatically used as a dependent plugin. """ def generate(context=None, param={}, seed=None): """Generate the sample data. Runs the generate functions of all plugins in an order such that the dependencies are all generated before the dependents. In essence, this function performs a topological sort in a directed acyclic graph. Raises a CyclicDependencyError if the dependency graph has a cycle. Returns a dict with names of plugins run as keys and CPU times as values. context: The context to be used to generate the sample data. param: A mapping containing the parameters for the generator plugins. The key is the name of the plugin. """ class CyclicDependencyError(ValueError): """Cyclic dependency of sample data plugins"""
z3c.sampledata
/z3c.sampledata-2.0.0a1.zip/z3c.sampledata-2.0.0a1/src/z3c/sampledata/interfaces.py
interfaces.py
=============================== Pluggable sample data framework =============================== Creating a good testing environment is the most important way to create high quality software. But most of the time it is a pain ! This package tries to do the best to support the development of sample data generators. A sample data generator is a pluggable tool to create data needed for tests. There are several goals to this framework: - provide the developers with an automatic setup that is close to real-world use. - provide the users with an easy setup for evaluation with plausible data - provide the user a management interface for different sample generators The framework is pluggable and allows the creators of generator extensions to provide their own plugins that generate sample data for those extensions. Generators ---------- A generator generates sample data. >>> from zope import interface >>> from zope import component >>> from z3c.sampledata.interfaces import ISampleDataPlugin >>> @interface.implementer(ISampleDataPlugin) ... class GeneratePrincipals(object): ... dependencies = [] ... schema = None ... def generate(self, context, param={}, dataSource=None, seed=None): ... print(self.__class__.__name__) ... if dataSource is not None: ... for data in dataSource: ... print('- %s'%data['login']) >>> principalPlugin = GeneratePrincipals() For our tests we provide another generator : >>> @interface.implementer(ISampleDataPlugin) ... class GenerateSite(object): ... dependencies = [] ... schema = None ... def generate(self, context, param={}, dataSource=None, seed=None): ... if 'sitename' in param: ... print('This is site %r'%param['sitename']) ... else: ... print(self.__class__.__name__) ... return 'I am from the site' >>> sitePlugin = GenerateSite() Generator Manager ----------------- A generator manager groups a collection of generators. The manager allows to : - define dependencies between generators - define data connections between dependent generators - provide default configuration data >>> from z3c.sampledata import Manager >>> manager = Manager('manager', '') Generator Plugin ~~~~~~~~~~~~~~~~ For the manager our sample generators must be registered as named utilities. >>> component.provideUtility(sitePlugin, ... ISampleDataPlugin,'z3c.sampledata.site') >>> component.provideUtility(principalPlugin, ... ISampleDataPlugin,'z3c.sampledata.principals') Generating Sample Data ~~~~~~~~~~~~~~~~~~~~~~ Now we can add generators to the manager. >>> manager.add('z3c.sampledata.principals', ... dependsOn=['z3c.sampledata.site',], ... contextFrom='z3c.sampledata.site') In addition to the "hardwired" dependencies defined by the dependencies property in each generator it is possible to add dependencies in the generator manager. A manager provides it's generators. >>> list(manager.generators.keys()) ['z3c.sampledata.principals'] We can tell the manager to generate all samples. There is no need to add the sample generator 'z3c.sampledata.site', it is added automatically because of the dependency of 'z3c.sampledata.principals'. >>> infos = manager.generate(context=None, param={}, seed='something') GenerateSite GeneratePrincipals >>> [info.name for info in infos] ['z3c.sampledata.site', 'z3c.sampledata.principals'] Parameters for the sample generators ------------------------------------ To have more control over the sample generation process it is possible to setup parameters for the generators. >>> manager = Manager('manager', '') >>> manager.add('z3c.sampledata.site', ... param={'sitename':'samplesite'}) >>> manager.add('z3c.sampledata.principals', ... dependsOn=['z3c.sampledata.site',], ... contextFrom='z3c.sampledata.site') >>> infos = manager.generate(context=None, param={}, seed='something') This is site 'samplesite' GeneratePrincipals It is also possible to overwrite the parameters from the configuration. >>> infos = manager.generate(context=None, ... param={'z3c.sampledata.site': ... {'sitename':'managers site'}}, ... seed='something') This is site 'managers site' GeneratePrincipals Cycles in the generator definition ---------------------------------- >>> manager = Manager('manager', '') >>> manager.add('z3c.sampledata.principals', ... dependsOn=['z3c.sampledata.site',], ... contextFrom='z3c.sampledata.site') >>> manager.add('z3c.sampledata.site', ... dependsOn=['z3c.sampledata.principals',]) >>> infos = manager.generate(context=None, param={}, seed='something') Traceback (most recent call last): ... CyclicDependencyError: cyclic dependency at 'z3c.sampledata.principals' A test for a complex dependency. >>> @interface.implementer(ISampleDataPlugin) ... class Generator(object): ... name = 'generator' ... dependencies = [] ... schema = None ... def generate(self, context, param={}, dataSource=None, seed=None): ... return 'I am a generator' >>> component.provideUtility(Generator(), ISampleDataPlugin,'g.1') >>> component.provideUtility(Generator(), ISampleDataPlugin,'g.2') >>> component.provideUtility(Generator(), ISampleDataPlugin,'g.3') >>> manager = Manager('manager', '') >>> manager.add('g.1') >>> manager.add('g.2', contextFrom='g.1') >>> manager.add('g.3', dependsOn=['g.2', 'g.1'], contextFrom='g.1') >>> infos = manager.generate(context=None, param={}, seed=None) >>> [info.name for info in infos] ['g.1', 'g.2', 'g.3'] Sample Data Source ------------------ A sample data generator usually gets its sample data from a data source. Mostly it is necessary to have different data sources for different uses. As an example, it is always a pain if the sample data for the tests use the same data as the UI uses later to provide data for the customer to click around. >>> manager = Manager('manager', '') >>> manager.addSource('z3c.datasource.principals', ... data=[{'login':'jukart', 'password':'trakuj'}, ... {'login':'srichter', 'password':'rethcirs'}]) >>> manager.add('z3c.sampledata.principals', ... dataSource='z3c.datasource.principals', ... dependsOn=['z3c.sampledata.site',], ... contextFrom='z3c.sampledata.site') >>> infos = manager.generate(context=None, param={}, seed='something') GenerateSite GeneratePrincipals - jukart - srichter It is also possible to use adapters to act as a data source. >>> manager = Manager('manager', '') >>> class IPrincipalDataSource(interface.Interface): ... pass >>> def principalDataFactory(object): ... return [{'login':'jukart', 'password':'trakuj'}, ... {'login':'srichter', 'password':'rethcirs'}] >>> component.provideAdapter( ... factory=principalDataFactory, ... adapts=(ISampleDataPlugin,), ... provides=IPrincipalDataSource, ... name='testprincipals') >>> manager.addSource('z3c.datasource.principals', ... adapterName='testprincipals', ... adaptTo=IPrincipalDataSource) >>> manager.add('z3c.sampledata.principals', ... dataSource='z3c.datasource.principals', ... dependsOn=['z3c.sampledata.site',], ... contextFrom='z3c.sampledata.site') >>> infos = manager.generate(context=None, param={}, seed='something') GenerateSite GeneratePrincipals - jukart - srichter How to setup configuration for the generator manager ---------------------------------------------------- Configuration can be done using ZCML:: <configure xmlns="http://namespaces.zope.org/zope"> <configure xmlns:zcml="http://namespaces.zope.org/zcml" zcml:condition="have devmode"> <utility factory=".SampleSite" provides="z3c.sampledata.interfaces.ISampleDataPlugin" name="z3c.site" /> <utility factory=".SamplePrincipals" provides="z3c.sampledata.interfaces.ISampleDataPlugin" name="z3c.principals" /> <SampleManager name="Site with principals" > <generator name="z3c.site" /> <generator name="z3c.principal" dependsOn="z3c.site" contextFrom="z3c.site" /> </SampleManager> </configure> </configure> Data Sources ------------ This package implements the base functionality for data generators. A data generator is used to provide the raw data for a sample generator. Raw data can be read from text files in different ways. >>> from z3c.sampledata.data import DataGenerator >>> generator = DataGenerator(55) The generator can read data lines from files. >>> generator.readLines('testlines.txt') [u'Line 1', u'Another line'] The generator can read data from CSV files. >>> generator.readCSV('testlines.csv') [['Line 1', 'Col 2'], ['Another line', 'Another Col']] The generator can read a list of files from a path : >>> import os >>> generator.files(os.path.dirname(__file__)) ['...README.txt', ...]
z3c.sampledata
/z3c.sampledata-2.0.0a1.zip/z3c.sampledata-2.0.0a1/src/z3c/sampledata/README.txt
README.txt
from zope import interface from zope import schema from zope.configuration.fields import GlobalInterface from z3c.sampledata import _ class ISampleManagerDirective(interface.Interface): """Parameters for the sample manager.""" name = schema.TextLine( title = _(u"Name"), description = _(u'The unique name of the sample manager'), ) seed = schema.TextLine( title = _(u'Seed'), description = _(u'The seed for the random generator'), required = False, default = u'' ) class IGeneratorSubDirective(interface.Interface): """Parameters for the 'generator' subdirective.""" name = schema.TextLine( title = _(u"Name"), description = _(u'The unique name of the sample manager'), ) dependsOn = schema.TextLine( title = _(u"Dependencies"), description = _(u'The generators this generator depends on.\n' u'As space separated list.'), default = u'', required = False, ) contextFrom = schema.TextLine( title = _(u"Context from"), description = _(u'Context for the generator is taken from this' u' generator.'), default = u'', required = False, ) dataSource = schema.TextLine( title = _(u"Datasource"), description = _(u'The data source for the generator'), default = u'', required = False, ) class IDataSourceSubDirective(interface.Interface): """Parameters for the 'datasource' subdirective.""" name = schema.TextLine( title = _(u"Name"), description = _(u'The unique name of the datasource'), ) adapterInterface = GlobalInterface( title = _(u"Interface"), description = _(u'The interface to adapt to'), required = True ) adapterName = schema.TextLine( title = _(u"Adapter"), description = _(u'The name of the adapter providing the data.'), required = False, default = u'' )
z3c.sampledata
/z3c.sampledata-2.0.0a1.zip/z3c.sampledata-2.0.0a1/src/z3c/sampledata/metadirectives.py
metadirectives.py
"""A manager for sample generation. """ import time from zope import interface from zope import component from z3c.sampledata.interfaces import ISampleDataPlugin, ISampleManager from z3c.sampledata.interfaces import CyclicDependencyError @interface.implementer(ISampleManager) class Manager(object): def __init__(self, name, seed): self.name = name self.seed = seed self.generators = {} self.sources = {} def addSource(self, name, data=None, adaptTo=None, adapterName=u''): self.sources[name] = (data, adaptTo, adapterName) def add(self, generator, param={}, dataSource=None, dependsOn=[], contextFrom=None): info = self.generators.setdefault(generator, {}) info['param'] = param info['dataSource'] = dataSource info['dependsOn'] = dependsOn info['contextFrom'] = contextFrom def orderedPlugins(self): # status is a dict plugin names as keys and statuses as values. # Statuses can be as follows: # # new -- not yet visited # closed -- already processed # open -- being processed # # Stumbling over an 'open' node means there is a cyclic dependency new = 'new' open = 'open' closed = 'closed' status = {} # plugins contains all plugins to be used including dependent plugins. plugins = [] callstack = [] def insertPlugin(name): """Insert the plugin into plugins including all dependent plugins. Builds a calling list of all plugins in the correct order. """ if name in callstack: raise CyclicDependencyError("cyclic dependency at '%s'" % name) callstack.append(name) if name not in status: status[name] = new if status[name] == new: status[name] = open info = PluginInfo(name) if name in self.generators: pluginInfo = self.generators[name] info.addDependents(pluginInfo['dependsOn']) info.contextFrom = pluginInfo['contextFrom'] info.param = pluginInfo['param'] info.dataSource = pluginInfo['dataSource'] if info.contextFrom is not None: info.addDependents([info.contextFrom]) generator = component.getUtility(ISampleDataPlugin, name) info.generator = generator info.addDependents(generator.dependencies) for depName in info.dependencies: if depName not in status or status[depName] is not closed: insertPlugin(depName) plugins.append(info) status[name] = closed callstack.pop(-1) for name in self.generators.keys(): insertPlugin(name) return plugins def generate(self, context=None, param={}, seed=None): plugins = self.orderedPlugins() # contextFrom contains the return values of the plugins contextFrom = {} for info in plugins: genContext = context if info.contextFrom is not None: genContext = contextFrom[info.contextFrom] start = time.clock() data, adapterInterface, adapterName = \ self.sources.get(info.dataSource, (None, None, None)) if data is None and adapterInterface is not None: data = component.getAdapter(info.generator, adapterInterface, name=adapterName) generatorParam = param.get(info.name, None) if generatorParam is None: generatorParam = info.param contextFrom[info.name] = info.generator.generate( genContext, param=generatorParam, dataSource=data, seed=seed) info.time = time.clock() - start return plugins class PluginInfo(object): def __init__(self, name): self.name = name self.param = {} self.dataSource = None self.dependencies = [] self.contextFrom = None self.generator = None self.time = 0.0 def addDependents(self, dependsOn): for dependent in dependsOn: if dependent not in self.dependencies: self.dependencies.append(dependent)
z3c.sampledata
/z3c.sampledata-2.0.0a1.zip/z3c.sampledata-2.0.0a1/src/z3c/sampledata/manager.py
manager.py
"""Sample generator to create principals """ import zope.interface import zope.component import zope.event import zope.schema import zope.lifecycleevent from zope.interface import implementer from zope.pluggableauth.plugins import principalfolder from zope.site import hooks from z3c.sampledata import _ from z3c.sampledata._compat import toUnicode from z3c.sampledata.interfaces import ISampleDataPlugin class IPrincipalDataSource(zope.interface.Interface): """A marker interface for principal data source adapters""" def defaultPrincipalDataFactory(object): return [['batlogg', 'Jodok Batlogg', 'bJB'], ['jukart', 'Juergen Kartnaller', 'jJK'], ['dobee', 'Bernd Dorn', 'dBD'], ['srichter', 'Stephan Richter', 'sSR'], ['byzo', 'Michael Breidenbruecker', 'bMB'], ['oli', 'Oliver Ruhm', 'oOR']] class ISamplePrincipalParameters(zope.interface.Interface): """The parameters for the sample principal generator.""" minPrincipals = zope.schema.Int( title = _(u'Min principals'), description = _(u'Create at least this number of pricipals from' u' the principals file.\n' u'This has higher priority than maxPricipals.\n' u'-1 : create all principals from the datasource.' ), required = False, default = -1, ) maxPrincipals = zope.schema.Int( title = _(u'Max principals'), description = _(u'The maximum number of principals to create.\n' u'Uses the first principals from the datasource.' ), required = False, default = -1, ) pauLocation = zope.schema.TextLine( title = _(u'PAU location'), description = _(u'Path to the PAU inside the site manager.'), required = False, default = u'default/pau', ) passwordManager = zope.schema.TextLine( title = _(u'Password Manager'), description = _(u'The password manager to use.'), required = False, default = u'SHA1', ) @implementer(ISampleDataPlugin) class SamplePrincipals(object): """Create principals inside a site manager. context : site return : pau in which the principals where created """ dependencies = [] schema = ISamplePrincipalParameters maxPrincipals = None minPrincipals = None def generate(self, context, param={}, dataSource=[], seed=None): """Generate sample pricipals""" if 'omit' in param or context is None: return None self.minPrincipals = int(param['minPrincipals']) if self.minPrincipals<0: self.minPrincipals = None self.maxPrincipals = int(param['maxPrincipals']) if self.maxPrincipals<0: self.maxPrincipals = None originalSite = hooks.getSite() hooks.setSite(context) sm = zope.component.getSiteManager(context) self.pau = self._getPAU(sm, param) self.passwordManagerName = param['passwordManager'] numCreated = 0 self.logins = [] if dataSource: for info in dataSource: if ( self.maxPrincipals is not None and numCreated>=self.maxPrincipals): break login = toUnicode(info[0]) if login in self.logins: # ignore duplicate principals continue self._createPrincipal(context, info) numCreated+=1 if ( self.minPrincipals is not None and numCreated<self.minPrincipals): for i in range(self.minPrincipals-numCreated): info = self._createDummyPrincipalInfo(context, i) self._createPrincipal(context, info) hooks.setSite(originalSite) return self.pau def _getPAU(self, sm, param): pau = sm for loc in param['pauLocation'].split('/'): pau = pau[loc] return pau def _createPrincipal(self, site, info): login = toUnicode(info[0]) self.logins.append(login) if login in self.pau['members']: return name = toUnicode(info[1]) password = toUnicode(info[2]) principal = principalfolder.InternalPrincipal( login, password, name, passwordManagerName=self.passwordManagerName) zope.event.notify( zope.lifecycleevent.ObjectCreatedEvent(principal)) self.pau['members'][login] = principal def _createDummyPrincipalInfo(self, site, i): return ['login%i'%i, 'name%i'%i, '%i'%i]
z3c.sampledata
/z3c.sampledata-2.0.0a1.zip/z3c.sampledata-2.0.0a1/src/z3c/sampledata/generator/principals.py
principals.py
================ Date Selection ================ The date selection field was designed to support the UI requirement of allowing users to select a date using multi-select input fields. The ``DateSelect`` field extends the :class:`zope.schema.Date` field merely by a few additional attributes. >>> from z3c.schema.dateselect import field the first attribute is the range of years that will be offered to the user: >>> birthday = field.DateSelect( ... title=u'Birthday', ... yearRange=list(range(1920, 2007))) In this case the user will be offered all years from 1920 to 2007. >>> birthday.yearRange [1920, ..., 2006] The second attribute allows you to specify an initial date for the selection: >>> import datetime >>> birthday = field.DateSelect( ... title=u'Birthday', ... yearRange=range(1920, 2007), ... initialDate=datetime.date(2000, 1, 1)) >>> birthday.initialDate datetime.date(2000, 1, 1) And this is really it. Please read the documentation on the :class:`~zope.schema.Date` for more information.
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/dateselect/README.txt
README.txt
====== URLs ====== BaseURL ======= A base url field is useful if you need to append view names to a url and doesn't like to check every time if the url ends with a backslash before you append the view name. Let's first create the BaseURL field: >>> from z3c.schema.baseurl import BaseURL >>> baseURL = BaseURL() Let's first check the validation of some common base urls. >>> baseURL.validate("http://www.python.org/") >>> baseURL.validate("http://www.python.org/foo/") >>> baseURL.validate("http://123.123.123.123/") >>> baseURL.validate("http://123.123.123.123/foo/") A port specification is also allowed: >>> baseURL.validate("http://www.python.org:389/") >>> baseURL.validate("http://www.python.org:389/foo/") However, a missing backslash is not permitted: >>> baseURL.validate("http://www.python.org/foo") Traceback (most recent call last): ... InvalidBaseURL: http://www.python.org/foo And a missing protocol is also not permitted: >>> baseURL.validate("www.python.org/foo/") Traceback (most recent call last): ... InvalidBaseURL: www.python.org/foo/ Let's check some other invalid forms: >>> baseURL.validate("$www.python.org/") Traceback (most recent call last): ... InvalidBaseURL: $www.python.org/ >>> baseURL.validate("333.123.123.123/") Traceback (most recent call last): ... InvalidBaseURL: 333.123.123.123/ Let's also ensure that we can convert to base urls from unicode: >>> baseURL.fromUnicode("http://www.python.org:389/") 'http://www.python.org:389/' >>> baseURL.fromUnicode(" http://www.python.org:389/") 'http://www.python.org:389/' >>> baseURL.fromUnicode(" \n http://www.python.org:389/\n") 'http://www.python.org:389/' >>> baseURL.fromUnicode("http://www.pyt hon.org:389/") Traceback (most recent call last): ... InvalidBaseURL: http://www.pyt hon.org:389/
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/baseurl/README.txt
README.txt
============== IP Addresses ============== This module provides a field for IP addresses. Let's first generate an IP field: >>> from z3c.schema import ip >>> myip = ip.IPAddress() Now make sure the IP addresses validate: >>> myip.validate(10) Traceback (most recent call last): ... WrongType: (10, <type 'str'>, '') >>> myip.validate('12.123.231.wee') Traceback (most recent call last): ... NotValidIPAdress: 12.123.231.wee >>> myip.validate('10.0.0.1') Since the field uses a simple function to validate its IP addresses, it is easier to use it for the tests: >>> from z3c.schema.ip import isValidIPAddress >>> isValidIPAddress('0.0.0.0') True >>> isValidIPAddress('255.255.255.255') True * Number of pieces failures >>> isValidIPAddress('12.3.1') False >>> isValidIPAddress('1.0.0.0.0') False >>> isValidIPAddress('1.0.0.0.') False * Not integers failures >>> isValidIPAddress('x.0.0.0') False >>> isValidIPAddress('0x8.0.0.0') False * Not in range failures >>> isValidIPAddress('-1.0.0.0') False >>> isValidIPAddress('256.0.0.0') False >>> isValidIPAddress('1.-1.256.0') False
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/ip/README.txt
README.txt
======== Hostname ======== Let's first create the hostname field: >>> from z3c.schema.hostname import HostName >>> hostname = HostName() Let's first check the validation of some common hostnames. Hostnames can be either domain or IP addresses. >>> hostname.validate("www.python.org") >>> hostname.validate("123.123.123.123") A port specification is also allowed: >>> hostname.validate("www.python.org:389") However, the protocol is not permitted: >>> hostname.validate("http://www.python.org") Traceback (most recent call last): ... InvalidHostName: http://www.python.org >>> hostname.validate("ldap://www.python.org/foo") Traceback (most recent call last): ... InvalidHostName: ldap://www.python.org/foo Let's check some other invalid forms: >>> hostname.validate("$www.python.org") Traceback (most recent call last): ... InvalidHostName: $www.python.org >>> hostname.validate("333.123.123.123") Traceback (most recent call last): ... InvalidHostName: 333.123.123.123 Let's also ensure that we can convert to hostnames from unicode: >>> hostname.fromUnicode("www.python.org:389") 'www.python.org:389' >>> hostname.fromUnicode(" www.python.org:389") 'www.python.org:389' >>> hostname.fromUnicode(" \n www.python.org:389\n") 'www.python.org:389' >>> hostname.fromUnicode("www.pyt hon.org:389") Traceback (most recent call last): ... InvalidHostName: www.pyt hon.org:389
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/hostname/README.txt
README.txt
============================= Payment Data (Credit Cards) ============================= z3c.schema.payments provides some level of error detection in payment data prior to storing the information or sending it to a payment processor. Currently this module only supports validation of credit card numbers, but this could conceivably be extended to other payment forms Credit Cards ============ Credit card numbering specifications are defined in ISO 7812-1:1983. Verifying that the credit card number supplied by a user conforms to the ISO standard provides some error checking which can catch typographical errors, transposition, etc. This does not validate the card against the financial networks as a valid account. However, verifying that the card number is well formed is fast and catching typographical errors in this way is much faster than sending the card number to a credit card processor. First, let's setup a credit card field: >>> from z3c.schema.payments import CreditCard >>> from z3c.schema.payments import interfaces >>> cc = CreditCard() >>> interfaces.IISO7812CreditCard.providedBy(cc) True The simple restrictions are quick to check. Credit cards should be all numeric, no alpha characters allowed: >>> cc.constraint('44444444444AAAA8') False >>> cc.constraint('4444444444444448') True Also, we can't have any returns or line endings in the number: >>> cc.constraint('444444444444\n4448') False >>> cc.constraint('44444444\r44444448') False One of the first specifications of ISO 7812 is a "Major Industry Identifier," which is the first number of an ISO 7812 compliant account number. Originally, banking, financial, and merchandizing (store account) cards were limited to the major industry identifiers 4, 5, and 6. However American Express, Diner's Club, and Carte Blanche were all assigned a major industry number 3. So a valid card must start with one of these numbers: >>> cc.validate(u'0000000000000000') Traceback (most recent call last): ... NotValidISO7812CreditCard: 0000000000000000 >>> cc.validate(u'1111111111111117') Traceback (most recent call last): ... NotValidISO7812CreditCard: 1111111111111117 >>> cc.validate(u'2222222222222224') Traceback (most recent call last): ... NotValidISO7812CreditCard: 2222222222222224 >>> cc.validate(u'3333333333333331') >>> cc.validate(u'4111111111111111') >>> cc.validate(u'5555555555555557') >>> cc.validate(u'3333333333333331') >>> cc.validate(u'6666666666666664') >>> cc.validate(u'7777777777777771') Traceback (most recent call last): ... NotValidISO7812CreditCard: 7777777777777771 >>> cc.validate(u'8888888888888888') Traceback (most recent call last): ... NotValidISO7812CreditCard: 8888888888888888 >>> cc.validate(u'9999999999999995') Traceback (most recent call last): ... NotValidISO7812CreditCard: 9999999999999995 The ISO specification also defines a check digit which should always be the last digit of a card number. The check digit is calculated using the Luhn (Mod 10) formula. In this way, each credit card number contains its own CRC of sorts. This is our main validation that a credit card number is well formed. Validating a number with a check digit that uses the LUHN formula: Step 1: Starting with the next-to-last digit and moving left, double the value of every other digit. The calculation starts with the next-to-last digit because the last digit is the check digit. * When selecting every other digit, always work right-to-left and do not start with the rightmost digit (since that is the check digit). * The last digit (check digit) is considered #1 (odd number) and the next-to-last digit is #2 (even number). You will only double the values of the even-numbered digits. Step 2: Add all unaffected digits to the values obtained in Step 1. * If any of the values resulting from Step 1 are double-digits, do not add the double-digit value to the total, but rather add the two digits, and add this sum to the total. Result: The total obtained in Step 2 must be a number ending in zero (exactly divisible by 10) for the number to be valid. The validate method of z3c.schema.payments.ISO7812CreditCard does the Luhn calculation on the provided card number. If the calculation fails, there is either an error in the number or the card is simply not valid. We use in our tests here and above numbers that technically meet the criteria of the ISO specification without the risk of the number actually being a valid card number registered with a financial institution: >>> cc.validate(u'4444444444444448') >>> cc.validate(u'4444444444444449') Traceback (most recent call last): ... NotValidISO7812CreditCard: 4444444444444449
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/payments/README.txt
README.txt
__docformat__ = "reStructuredText" import zope.interface import zope.schema from z3c.schema.email import interfaces rfc822_specials = '()<>@,;:\\"[]' def isValidMailAddress(addr): """Returns True if the email address is valid and False if not.""" # First we validate the name portion (name@domain) c = 0 while c < len(addr): if addr[c] == '@': break # Make sure there are only ASCII characters if ord(addr[c]) <= 32 or ord(addr[c]) >= 127: return False # A RFC-822 address cannot contain certain ASCII characters if addr[c] in rfc822_specials: return False c = c + 1 # check whether we have any input and that the name did not end with a dot if not c or addr[c - 1] == '.': return False # check also starting and ending dots in (name@domain) if addr.startswith('.') or addr.endswith('.'): return False # Next we validate the domain portion (name@domain) domain = c = c + 1 # Ensure that the domain is not empty (name@) if domain >= len(addr): return False count = 0 while c < len(addr): # Make sure that domain does not end with a dot or has two dots in a # row if addr[c] == '.': if c == domain or addr[c - 1] == '.': return False count = count + 1 # Make sure there are only ASCII characters if ord(addr[c]) <= 32 or ord(addr[c]) >= 127: return False # A RFC-822 address cannot contain certain ASCII characters if addr[c] in rfc822_specials: return False c = c + 1 if count >= 1: return True else: return False @zope.interface.implementer(interfaces.IRFC822MailAddress) class RFC822MailAddress(zope.schema.TextLine): """A valid email address.""" def constraint(self, value): return '\n' not in value and '\r' not in value def _validate(self, value): super()._validate(value) if not isValidMailAddress(value): raise interfaces.NotValidRFC822MailAdress(value)
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/email/field.py
field.py
==================== RFC 822 Mail Address ==================== Let's first generate an E-mail field: >>> from z3c.schema.email import RFC822MailAddress >>> email = RFC822MailAddress() Check that the constraints of the value are fulfilled: >>> email.constraint('foo\n') False >>> email.constraint('foo\r') False >>> email.constraint('foo') True Now make sure the E-mail addresses validate: >>> email.validate(10) Traceback (most recent call last): ... WrongType: (10, <type 'unicode'>, '') >>> email.validate(u'foo@bar.') Traceback (most recent call last): ... NotValidRFC822MailAdress: foo@bar. >>> email.validate(u'[email protected]') Since the field uses a simple function to validate its E-mail fields, it is easier to use it for the tests: >>> from z3c.schema.email import isValidMailAddress >>> isValidMailAddress(u'[email protected]') True >>> isValidMailAddress(u'[email protected]') True * Name failures >>> isValidMailAddress(u'foo\[email protected]') False >>> isValidMailAddress(u'foo<@bar.com') False >>> isValidMailAddress(u'foo:@bar.com') False * Overall failures >>> isValidMailAddress(u'') False >>> isValidMailAddress(u'foo.') False >>> isValidMailAddress(u'[email protected]') False >>> isValidMailAddress(u'[email protected]') False >>> isValidMailAddress(u'[email protected].') False * Domain failures >>> isValidMailAddress(u'foo@') False >>> isValidMailAddress(u'foo@bar.') False >>> isValidMailAddress(u'foo@bar') False >>> isValidMailAddress(u'[email protected]') False >>> isValidMailAddress(u'foo@bar\r.com') False >>> isValidMailAddress(u'foo@bar<.com') False >>> isValidMailAddress(u'foo@bar:.com') False
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/email/README.txt
README.txt
================ Optional Choices ================ The optional choice field is desiged to offer a set of default choices or allow, optionally, to enter a custom value. The custom value has to conform to a specified field. Here is an example of creating such a field: >>> import zope.schema >>> from z3c.schema.optchoice import OptionalChoice >>> optchoice = OptionalChoice( ... title=u'Occupation', ... values=(u'Programmer', u'Designer', u'Project Manager'), ... value_type=zope.schema.TextLine()) Note that the value type *must* be a field: >>> OptionalChoice( ... title=u'Occupation', ... values=(u'Programmer', u'Designer', u'Project Manager'), ... value_type=object()) Traceback (most recent call last): ValueError: 'value_type' must be field instance. Let's now ensure that we can validate not only choices, but also custom values: >>> optchoice.validate(u'Programmer') >>> optchoice.validate(u'Project Manager') >>> optchoice.validate(u'Scripter') >>> optchoice.validate(u'Scripter\nHTML\n') Traceback (most recent call last): ... ConstraintNotSatisfied: Scripter HTML Let's now ensure that we can convert values from unicode to a real value as well. To demonstrate this feature, we have to create a more restrictive optional choice field: >>> optchoice = OptionalChoice( ... title=u'Age', ... values=(10, 20, 30, 40, 50), ... value_type=zope.schema.Int(min=0)) >>> optchoice.fromUnicode(u'10') 10 >>> optchoice.fromUnicode(u'40') 40 >>> optchoice.fromUnicode(u'45') 45 >>> optchoice.fromUnicode(u'-10') Traceback (most recent call last): ... TooSmall: (-10, 0)
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/optchoice/README.txt
README.txt
===================== Regular Expressions ===================== Let's first create the regex field. >>> from z3c.schema.regex import Regex >>> regex = Regex() The regex field only allows compilable regular expressions. >>> regex.validate(r'.*') >>> regex.validate(r'^\s+$') It does not validate regular expressions that do not compile. >>> regex.validate('(i') Traceback (most recent call last): ... InvalidRegex: '(i', unbalanced parenthesis When used to process input, only valid values are returned. >>> regex.fromUnicode(u'.*') '.*' >>> regex.fromUnicode(u'(i') Traceback (most recent call last): ... InvalidRegex: '(i', unbalanced parenthesis
z3c.schema
/z3c.schema-2.0-py3-none-any.whl/z3c/schema/regex/README.txt
README.txt
from lxml import etree import grokcore.component as grok from persistent import Persistent from zope.interface import Interface, alsoProvides import zope.datetime from zope.location import Location from zope.schema import getFieldsInOrder from zope.schema.interfaces import IText, IInt, IObject, IList, IChoice, ISet from zope.schema.interfaces import IDatetime def serialize_to_tree(container, schema, instance): for name, field in getFieldsInOrder(schema): value = field.get(instance) IXMLGenerator(field).output(container, value) return container def serialize( container_name, schema, instance, encoding='UTF-8', pretty_print=True): container = etree.Element(container_name) container = serialize_to_tree(container, schema, instance) return etree.tostring( container, encoding=encoding, pretty_print=pretty_print) def deserialize_from_tree(container, schema, instance): for element in container: field = schema[element.tag] value = IXMLGenerator(field).input(element) field.set(instance, value) alsoProvides(instance, schema) def deserialize(xml, schema, instance): container = etree.XML(xml) deserialize_from_tree(container, schema, instance) class GeneratedObject(Location, Persistent): def __init__(self): pass class IXMLGenerator(Interface): def output(container, value): """Output value as XML element according to field. """ def input(element): """Input XML element according to field and return value. """ class Text(grok.Adapter): grok.context(IText) grok.implements(IXMLGenerator) def output(self, container, value): element = etree.SubElement(container, self.context.__name__) element.text = value def input(self, element): if element.text is not None: return unicode(element.text) return None class Int(grok.Adapter): grok.context(IInt) grok.implements(IXMLGenerator) def output(self, container, value): element = etree.SubElement(container, self.context.__name__) if value is not None: element.text = str(value) def input(self, element): if element.text is not None and element.text != '': return int(element.text) return None class Object(grok.Adapter): grok.context(IObject) grok.implements(IXMLGenerator) def output(self, container, value): container = etree.SubElement(container, self.context.__name__) for name, field in getFieldsInOrder(self.context.schema): IXMLGenerator(field).output(container, field.get(value)) def input(self, element): instance = GeneratedObject() deserialize_from_tree(element, self.context.schema, instance) return instance class List(grok.Adapter): grok.context(IList) grok.implements(IXMLGenerator) def output(self, container, value): container = etree.SubElement(container, self.context.__name__) field = self.context.value_type for v in value: IXMLGenerator(field).output(container, v) def input(self, element): field = self.context.value_type return [ IXMLGenerator(field).input(sub_element) for sub_element in element] class Datetime(grok.Adapter): grok.context(IDatetime) grok.implements(IXMLGenerator) def output(self, container, value): element = etree.SubElement(container, self.context.__name__) if value is not None: element.text = value.isoformat() def input(self, element): if element.text is not None: return zope.datetime.parseDatetimetz(element.text) return None class Choice(grok.Adapter): grok.context(IChoice) grok.implements(IXMLGenerator) def output(self, container, value): element = etree.SubElement(container, self.context.__name__) element.text = value def input(self, element): if element.text is not None: return element.text return None class Set(grok.Adapter): grok.context(ISet) grok.implements(IXMLGenerator) def output(self, container, value): container = etree.SubElement(container, self.context.__name__) field = self.context.value_type for v in value: IXMLGenerator(field).output(container, v) def input(self, element): field = self.context.value_type return set([ IXMLGenerator(field).input(sub_element) for sub_element in element])
z3c.schema2xml
/z3c.schema2xml-1.0.tar.gz/z3c.schema2xml-1.0/src/z3c/schema2xml/_schema2xml.py
_schema2xml.py
Schema To XML ************* Introduction ============ This package can convert objects described by Zope 3 schema to simple XML structures. It's also able to convert this XML back into objects. The export and import processes are completely schema-driven; any attribute not described in the schema is not seen by this system at all. This system can be used to create export and import systems for Zope 3 applications. It could also be used to provide XML representations of objects for other purposes, such as XSLT transformations, or even just to get a full-text representation for index purposes. The package lies on ``lxml`` for the serialization to XML. Serialization ============= Let's first define a simple Zope 3 schema:: >>> from zope import interface, schema >>> class IName(interface.Interface): ... first_name = schema.TextLine(title=u'First name') ... last_name = schema.TextLine(title=u'Last name') Let's now make a class that implements this schema:: >>> from zope.interface import implements >>> class Name(object): ... implements(IName) ... def __init__(self, first_name, last_name): ... self.first_name = first_name ... self.last_name = last_name Let's make an instance of the class:: >>> name = Name('Karel', 'Titulaer') Now let's serialize it to XML: >>> from z3c.schema2xml import serialize >>> print serialize('container', IName, name) <container> <first_name>Karel</first_name> <last_name>Titulaer</last_name> </container> This also works for other kinds of fields:: >>> from zope import interface, schema >>> class IAddress(interface.Interface): ... street_name = schema.TextLine(title=u'Street name') ... number = schema.Int(title=u'House number') >>> class Address(object): ... implements(IAddress) ... def __init__(self, street_name, number): ... self.street_name = street_name ... self.number = number >>> address = Address('Hofplein', 42) >>> print serialize('container', IAddress, address) <container> <street_name>Hofplein</street_name> <number>42</number> </container> If a field is not filled in, the serialization will result in an empty element:: >>> address2 = Address(None, None) >>> print serialize('container', IAddress, address2) <container> <street_name/> <number/> </container> If a schema defines an Object field with its own schema, the serialization can also handle this:: >>> class IPerson(interface.Interface): ... name = schema.Object(title=u"Name", schema=IName) ... address = schema.Object(title=u"Address", schema=IAddress) >>> class Person(object): ... implements(IPerson) ... def __init__(self, name, address): ... self.name = name ... self.address = address >>> person = Person(name, address) >>> print serialize('person', IPerson, person) <person> <name> <first_name>Karel</first_name> <last_name>Titulaer</last_name> </name> <address> <street_name>Hofplein</street_name> <number>42</number> </address> </person> A schema can also define a List field with elements with their own schema. Let's make an object and serialize it:: >>> class ICommission(interface.Interface): ... members = schema.List( ... title=u"Commission", ... value_type=schema.Object(__name__='person', ... schema=IPerson)) Note that we have to explicitly specify __name__ for the field that's used for value_type here, otherwise we have no name to serialize to XML with. >>> class Commission(object): ... implements(ICommission) ... def __init__(self, members): ... self.members = members >>> commission = Commission( ... [person, Person(Name('Chriet', 'Titulaer'), Address('Ruimteweg', 3))]) >>> print serialize('commission', ICommission, commission) <commission> <members> <person> <name> <first_name>Karel</first_name> <last_name>Titulaer</last_name> </name> <address> <street_name>Hofplein</street_name> <number>42</number> </address> </person> <person> <name> <first_name>Chriet</first_name> <last_name>Titulaer</last_name> </name> <address> <street_name>Ruimteweg</street_name> <number>3</number> </address> </person> </members> </commission> We get an adapter lookop failure whenever we try to serialize a field type for which there's no an serializer:: >>> class IWithNonSerializableField(interface.Interface): ... field = schema.Field(title=u"Commission") >>> class NotSerializable(object): ... implements(IWithNonSerializableField) ... def __init__(self, value): ... self.field = value >>> not_serializable = NotSerializable(None) >>> serialize('noway', IWithNonSerializableField, not_serializable) Traceback (most recent call last): ... TypeError: ('Could not adapt', <zope.schema._bootstrapfields.Field object at ...>, <InterfaceClass z3c.schema2xml._schema2xml.IXMLGenerator>) Deserialization =============== Now we want to deserialize XML according to a schema to an object that provides this schema. >>> from z3c.schema2xml import deserialize >>> xml = ''' ... <container> ... <first_name>Karel</first_name> ... <last_name>Titulaer</last_name> ... </container> ... ''' >>> name = Name('', '') >>> deserialize(xml, IName, name) >>> name.first_name u'Karel' >>> name.last_name u'Titulaer' The order of the fields in XML does not matter:: >>> xml = ''' ... <container> ... <last_name>Titulaer</last_name> ... <first_name>Karel</first_name> ... </container> ... ''' >>> name = Name('', '') >>> deserialize(xml, IName, name) >>> name.first_name u'Karel' >>> name.last_name u'Titulaer' After deserialization, the object alsoProvides the schema interface:: >>> IName.providedBy(name) True This also works for other kinds of fields:: >>> xml = ''' ... <container> ... <street_name>Hofplein</street_name> ... <number>42</number> ... </container> ... ''' >>> address = Address('', 0) >>> deserialize(xml, IAddress, address) >>> address.street_name u'Hofplein' >>> address.number 42 If a schema defines an Object field with its own schema, the serialization can also handle this:: >>> xml = ''' ... <person> ... <name> ... <first_name>Karel</first_name> ... <last_name>Titulaer</last_name> ... </name> ... <address> ... <street_name>Hofplein</street_name> ... <number>42</number> ... </address> ... </person> ... ''' >>> person = Person(Name('', ''), Address('', 0)) >>> deserialize(xml, IPerson, person) >>> person.name.first_name u'Karel' >>> person.name.last_name u'Titulaer' >>> person.address.street_name u'Hofplein' >>> person.address.number 42 >>> IPerson.providedBy(person) True >>> IName.providedBy(person.name) True >>> IAddress.providedBy(person.address) True Again the order in which the fields come in XML shouldn't matter:: >>> xml = ''' ... <person> ... <address> ... <number>42</number> ... <street_name>Hofplein</street_name> ... </address> ... <name> ... <last_name>Titulaer</last_name> ... <first_name>Karel</first_name> ... </name> ... </person> ... ''' >>> person = Person(Name('', ''), Address('', 0)) >>> deserialize(xml, IPerson, person) >>> person.name.first_name u'Karel' >>> person.name.last_name u'Titulaer' >>> person.address.street_name u'Hofplein' >>> person.address.number 42 >>> IPerson.providedBy(person) True >>> IName.providedBy(person.name) True >>> IAddress.providedBy(person.address) True >>> xml = ''' ... <commission> ... <members> ... <person> ... <name> ... <first_name>Karel</first_name> ... <last_name>Titulaer</last_name> ... </name> ... <address> ... <street_name>Hofplein</street_name> ... <number>42</number> ... </address> ... </person> ... <person> ... <name> ... <first_name>Chriet</first_name> ... <last_name>Titulaer</last_name> ... </name> ... <address> ... <street_name>Ruimteweg</street_name> ... <number>3</number> ... </address> ... </person> ... </members> ... </commission> ... ''' >>> commission = Commission([]) >>> deserialize(xml, ICommission, commission) >>> len(commission.members) 2 >>> member = commission.members[0] >>> member.name.first_name u'Karel' >>> member.address.street_name u'Hofplein' >>> member = commission.members[1] >>> member.name.first_name u'Chriet' >>> member.address.street_name u'Ruimteweg' Whenever the XML element is empty, the resulting value should be None: >>> from z3c.schema2xml import deserialize >>> xml = ''' ... <container> ... <first_name></first_name> ... <last_name/> ... </container> ... ''' >>> name = Name('', '') >>> deserialize(xml, IName, name) >>> name.first_name is None True >>> name.last_name is None True For all kinds of fields, like strings and ints...:: >>> xml = ''' ... <container> ... <street_name/> ... <number/> ... </container> ... ''' >>> address = Address('', 0) >>> deserialize(xml, IAddress, address) >>> address.street_name is None True >>> address.number is None True ...and the fields of subobjects (but not the subobject themselves!):: >>> xml = ''' ... <person> ... <name> ... <first_name/> ... <last_name/> ... </name> ... <address> ... <street_name/> ... <number/> ... </address> ... </person> ... ''' >>> person = Person(Name('', ''), Address('', 0)) >>> deserialize(xml, IPerson, person) >>> person.name.first_name is None True >>> person.name.last_name is None True >>> IPerson.providedBy(person) True >>> IName.providedBy(person.name) True >>> person.address is None False >>> person.address.street_name is None True >>> person.address.number is None True >>> IAddress.providedBy(person.address) True Similarly, where a sequence is expected the value should be an empty sequence: >>> xml = ''' ... <commission> ... <members/> ... </commission> ... ''' >>> commission = Commission([]) >>> deserialize(xml, ICommission, commission) >>> len(commission.members) 0 TextLine, Int, Object and List have just been tested. Now follow tests for the other field types that have a serializer. Datetime ======== Datetime objects:: >>> from datetime import datetime >>> class IWithDatetime(interface.Interface): ... datetime = schema.Datetime(title=u'Date and time') >>> class WithDatetime(object): ... implements(IWithDatetime) ... def __init__(self, datetime): ... self.datetime = datetime >>> with_datetime = WithDatetime(datetime(2006, 12, 31)) >>> xml = serialize('container', IWithDatetime, with_datetime) >>> print xml <container> <datetime>2006-12-31T00:00:00</datetime> </container> >>> new_datetime = WithDatetime(None) >>> deserialize(xml, IWithDatetime, new_datetime) >>> new_datetime.datetime.year 2006 >>> new_datetime.datetime.month 12 >>> new_datetime.datetime.day 31 Let's try it with the field not filled in:: >>> with_datetime = WithDatetime(None) >>> xml = serialize('container', IWithDatetime, with_datetime) >>> print xml <container> <datetime/> </container> >>> new_datetime= WithDatetime(None) >>> deserialize(xml, IWithDatetime, new_datetime) >>> new_datetime.datetime is None True Choice ====== Choice fields. For now, we only work with Choice fields that have text values:: >>> from zc.sourcefactory.basic import BasicSourceFactory >>> class ChoiceSource(BasicSourceFactory): ... def getValues(self): ... return [u'alpha', u'beta'] >>> class IWithChoice(interface.Interface): ... choice = schema.Choice(title=u'Choice', required=False, ... source=ChoiceSource()) >>> class WithChoice(object): ... implements(IWithChoice) ... def __init__(self, choice): ... self.choice = choice >>> with_choice = WithChoice('alpha') >>> xml = serialize('container', IWithChoice, with_choice) >>> print xml <container> <choice>alpha</choice> </container> >>> new_choice = WithChoice(None) >>> deserialize(xml, IWithChoice, new_choice) >>> new_choice.choice 'alpha' >>> with_choice = WithChoice(None) >>> xml = serialize('container', IWithChoice, with_choice) >>> print xml <container> <choice/> </container> >>> deserialize(xml, IWithChoice, new_choice) >>> new_choice.choice is None True Set === Set fields are very similar to List fields:: >>> class IWithSet(interface.Interface): ... set = schema.Set(title=u'Set', required=False, ... value_type=schema.Choice(__name__='choice', ... source=ChoiceSource())) >>> class WithSet(object): ... implements(IWithSet) ... def __init__(self, set): ... self.set = set >>> with_set = WithSet(set(['alpha'])) >>> xml = serialize('container', IWithSet, with_set) >>> print xml <container> <set> <choice>alpha</choice> </set> </container> >>> with_set = WithSet(set(['alpha', 'beta'])) >>> xml = serialize('container', IWithSet, with_set) >>> print xml <container> <set> <choice>alpha</choice> <choice>beta</choice> </set> </container> >>> new_set = WithSet(None) >>> deserialize(xml, IWithSet, new_set) >>> new_set.set set(['alpha', 'beta'])
z3c.schema2xml
/z3c.schema2xml-1.0.tar.gz/z3c.schema2xml-1.0/src/z3c/schema2xml/README.txt
README.txt
z3c.schemadiff ============ Let's set up a schema describing objects we want to diff. >>> class IPizza(interface.Interface): ... name = schema.TextLine(title=u"Name") ... toppings = schema.Set( ... title=u"Toppings", ... value_type=schema.TextLine(), ... ) A class definition. >>> class Pizza(object): ... interface.implements(IPizza) ... ... def __init__(self, name, toppings): ... self.name = name ... self.toppings = toppings Add two instances, a classic Margherita and a Roman Capricciosa pizza. >>> margherita = Pizza(u"Margherita", ... (u"Tomato", u"Mozzarella", u"Basil")) >>> capricciosa = Pizza(u"Capricciosa", ... (u"Tomato", u"Mozarella", u"Mushrooms", u"Artichokes", u"Prosciutto")) To compare these, we need to register a field diff component for each of our fields. >>> from z3c.schemadiff import field >>> component.provideAdapter(field.TextLineDiff) >>> component.provideAdapter(field.SetDiff) Let's try it out. >>> from z3c.schemadiff.interfaces import IFieldDiff >>> name = IFieldDiff(IPizza['name']) >>> name.lines(margherita.name) (u'Margherita',) >>> toppings = IFieldDiff(IPizza['toppings']) >>> toppings.lines(margherita.toppings) (u'Tomato', u'Mozzarella', u'Basil') Now we can make a diff of the two instances. >>> from z3c.schemadiff import schema >>> schema.diff(margherita, capricciosa) {<zope.schema._field.Set object at ...>: ((u'Tomato', u'Mozzarella', u'Basil'), (u'Tomato', u'Mozarella', u'Mushrooms', u'Artichokes', u'Prosciutto')), <zope.schema._bootstrapfields.TextLine object at ...>: ((u'Margherita',), (u'Capricciosa',))}
z3c.schemadiff
/z3c.schemadiff-0.1.tar.gz/z3c.schemadiff-0.1/src/z3c/difftool/README.txt
README.txt
__docformat__ = "reStructuredText" import zope.component import zope.event import zope.lifecycleevent from zope.index.text import parsetree from zope.location import location from z3c.indexer.search import SearchQuery from z3c.template.template import getPageTemplate from z3c.template.template import getLayoutTemplate from z3c.form.interfaces import IWidgets from z3c.form import button from z3c.form import field from z3c.form import form from z3c.formui import form as formui from z3c.form.browser.radio import RadioFieldWidget from z3c.searcher import interfaces from z3c.searcher.interfaces import _ from z3c.searcher import criterium from z3c.searcher import filter class CriteriumForm(form.Form): formErrorsMessage = _('There were some errors.') successMessage = _('Data successfully updated.') noChangesMessage = _('No changes were applied.') fields = field.Fields(interfaces.ISearchCriterium).select('connectorName', 'value') fields['connectorName'].widgetFactory = RadioFieldWidget def updateWidgets(self): self.widgets = zope.component.getMultiAdapter( (self, self.request, self.getContent()), IWidgets) self.widgets.update() @property def criteriumName(self): return self.context.__name__ def save(self): data, errors = self.widgets.extract() if errors: self.status = self.formErrorsMessage return content = self.getContent() changed = form.applyChanges(self, content, data) if changed: zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent(content)) self.status = self.successMessage else: self.status = self.noChangesMessage @button.buttonAndHandler(_('Remove'), name='remove') def handleRemove(self, data): searchFilter = self.context.__parent__ searchFilter.removeCriterium(self.context) self.request.response.redirect(self.request.getURL()) class TextCriteriumForm(CriteriumForm): fields = field.Fields(interfaces.ITextCriterium).select('connectorName', 'value') fields['connectorName'].widgetFactory = RadioFieldWidget class FilterForm(form.Form): """Filter form.""" zope.interface.implements(interfaces.IFilterForm) # default form vars prefix = 'filterform' ignoreContext = True criteriumRows = [] rowName = 'row' # The filterName is used in the ISearchSession to identify filter filterName = 'searchFilter' # will probably get overriden by the parent form filterFactory = filter.SearchFilter # customization hooks @property def filterKey(self): """Return the default filter key. You can override this method and use a KeyReference intid if you need different filters for each context. """ return interfaces.SEARCH_SESSION_FILTER_KEY @property def addCriteriumName(self): return self.prefix + '-add' @property def criteriumFactories(self): for name, factory in self.searchFilter.criteriumFactories: yield {'name': name, 'title': factory.title} @property def searchFilter(self): session = interfaces.ISearchSession(self.request) searchFilter = session.getFilter(self.filterName, self.filterKey) if searchFilter is None: searchFilter = self.filterFactory() session.addFilter(self.filterName, searchFilter, self.filterKey) # Locate the search filter, so that security does not get lost location.locate(searchFilter, self.context, self.filterName) return searchFilter def values(self): # TODO: implement better error handling and allow to register error # views for unknown index search error. Right now we only catch some # known search index errors. try: # generate the search query searchQuery = self.searchFilter.generateQuery() # return result return SearchQuery(searchQuery).searchResults() except TypeError: self.status = _('One of the search filter is setup improperly.') except parsetree.ParseError, error: self.status = _('Invalid search text.') # Return an empty result, since an error must have occurred return [] def setupCriteriumRows(self): self.criteriumRows = [] append = self.criteriumRows.append for criterium in self.searchFilter.criteria: row = zope.component.getMultiAdapter( (criterium, self.request), name=self.rowName) row.__name__ = row.criteriumName row.prefix = '%s.criterium.%s' % (self.prefix, str(row.criteriumName)) row.update() append(row) def update(self): self.setupCriteriumRows() super(FilterForm, self).update() @button.buttonAndHandler(_(u'Add'), name='add') def handleAdd(self, action): name = self.request.get(self.addCriteriumName, None) if name is not None: self.searchFilter.createAndAddCriterium(name) self.setupCriteriumRows() self.status = _('New criterium added.') @button.buttonAndHandler(_(u'Clear'), name='clear') def handleClear(self, action): self.searchFilter.clear() self.setupCriteriumRows() self.status = _('Criteria cleared.') @button.buttonAndHandler(_(u'Search'), name='search') def handleSearch(self, action): data, errors = self.widgets.extract() for row in self.criteriumRows: row.save() class SearchForm(formui.Form): """Search form using a sub form for offering filters. Note this form uses the layout/content template pattern by default. And the content template renders the search filter into the ``extra-info``` slot offered from z3c.formui ``form`` macro """ zope.interface.implements(interfaces.ISearchForm) template = getPageTemplate() values = [] filterFactory = filter.SearchFilter def setupFilterForm(self): """Setup filter form before super form get updated.""" self.filterForm = FilterForm(self.context, self.request) self.filterForm.filterFactory = self.filterFactory def updateFilterForm(self): """Update filter form after super form get updated.""" self.filterForm.update() self.values = self.filterForm.values() def update(self): # setup filter form self.setupFilterForm() # process super form super(SearchForm, self).update() # process filter form self.updateFilterForm()
z3c.searcher
/z3c.searcher-0.6.0.zip/z3c.searcher-0.6.0/src/z3c/searcher/form.py
form.py
__docformat__ = "reStructuredText" import zope.i18nmessageid import zope.interface import zope.schema from zope.schema import vocabulary from zope.session.interfaces import ISession from zope.location.interfaces import ILocation from z3c.indexer import interfaces from z3c.indexer import query from z3c.form.interfaces import IForm from z3c.table.interfaces import ITable _ = zope.i18nmessageid.MessageFactory('z3c') SEARCH_SESSION = u'z3c.search.intefaces.ISearchSession' SEARCH_SESSION_FILTER_KEY = 'default' CONNECTOR_OR = 'OR' CONNECTOR_AND = 'AND' CONNECTOR_NOT = 'NOT' NOVALUE = object() class ISearchSession(ISession): """Search session supporting API for filter management. Filters contain the criterium rows and are stored persistent The methods support a key argument. This could be a context reference key give from the IntId utility or some other discriminator. If we do not support a key, the string ``default`` is used. """ def getFilter(name, key=SEARCH_SESSION_FILTER_KEY): """Return search filter by name.""" def getFilters(name): """Return a list of search filters.""" def addFilter(name, searchFilter, key=SEARCH_SESSION_FILTER_KEY): """Add search filter.""" def removeFilter(name, key=SEARCH_SESSION_FILTER_KEY): """Remove search filter.""" connectorVocabulary = vocabulary.SimpleVocabulary([ vocabulary.SimpleTerm(CONNECTOR_OR, title=_('or')), vocabulary.SimpleTerm(CONNECTOR_AND, title=_('and')), vocabulary.SimpleTerm(CONNECTOR_NOT, title=_('not')), ]) class ISearchCriterium(ILocation): """A search citerium of a piece of data.""" __name__ = zope.schema.TextLine( title=_('Name'), description=_('The locatable criterium name.'), required=True) label = zope.schema.TextLine( title=_('Label'), description=_('Label used to present the criterium.'), required=True) operatorLabel = zope.schema.TextLine( title=_('Operator label'), description=_('The operator label.'), required=True) indexOrName = zope.interface.Attribute("Index or index name.") operator = zope.schema.Object( title=_('Operator'), description=_('The operator used for the chain the queries.'), schema=interfaces.IQuery, required=True) connectorName = zope.schema.Choice( title=_('Connector Name'), description=_('The criterium connector name.'), vocabulary=connectorVocabulary, default=CONNECTOR_OR, required=True) value = zope.schema.TextLine( title=_('Search Query'), required=True) def search(searchQuery): """Generate chainable search query.""" class ITextCriterium(ISearchCriterium): """Sample full text search criterium implementation.""" class ISearchCriteriumFactory(zope.interface.Interface): """A factory for the search criterium""" title = zope.schema.TextLine( title=_('Title'), description=_('A human-readable title of the criterium.'), required=True) weight = zope.schema.Int( title=_('Int'), description=_('The weight/importance of the factory among all ' 'factories.'), required=True) def __call__(): """Generate the criterium.""" class ISearchFilter(zope.interface.Interface): """Search criteria for position search.""" criteria = zope.interface.Attribute( """Return a sequence of selected criteria.""") criteriumFactories = zope.schema.List( title=_('Criteria factories'), description=_('The criteria factories.'), value_type=zope.schema.Object( title=_('Criterium factory'), description=_('The criterium factory.'), schema=ISearchCriteriumFactory, required=True), default=[]) def clear(): """Clear the criteria.""" def createCriterium(name, value=NOVALUE): """Create a criterium by factory name.""" def addCriterium(criterium): """Add a criterium by name at the end of the list.""" def createAndAddCriterium(name, value=NOVALUE): """Create and add a criterium by name at the end of the list.""" def removeCriterium(criterium): """Add a criterium by name at the end of the list.""" def getDefaultQuery(): """Get a query that returns the default values. Override this method in your custom search filter if needed. This query get used if ``NO`` criterias are available. """ def getAndQuery(): """Return a ``And`` query which get used by default or None. Override this method in your custom search filter if needed. This query get used if ``one or more`` criterias are available. """ def getNotQuery(): """Return a ``Not`` query which get used as starting query or None. Override this method in your custom search filter if needed. This query get used if ``one or more`` criterias are available. """ def generateQuery(): """Generate a query object.""" class ICriteriumForm(IForm): """Criterium form.""" criteriumName = zope.schema.Field( title=_('Criterium name'), description=_('The criterium name'), required=True) def save(): """Save criterium changes.""" class IFilterForm(IForm): """Filter form.""" criteriumRows = zope.schema.List( title=_('List of criterium forms'), description=_('A list of criterium forms'), value_type=zope.schema.Field( title=_('Criterium form'), description=_('Criterium form'), required=True ), default=[], required=False) rowName = zope.schema.Field( title=_('Row name'), description=_('The row name used for lookup row forms.'), required=True) filterKey = zope.schema.Field( title=_('Seach filter key'), description=_('The search filter annotation key.'), required=True, default=SEARCH_SESSION_FILTER_KEY) addCriteriumName = zope.schema.Field( title=_('Add criterium name'), description=_('The name used for identify add criterium action.'), required=True) criteriumFactories = zope.schema.Dict( title=_('Name criterium factory dictionary'), description=_('The name criterium factory dictionary'), required=True, default={}) searchFilter = zope.schema.Field( title=_('Search filter class'), description=_('The search filter class'), required=False) def setupCriteriumRows(): """Setup criterium row forms.""" class ISearchForm(IForm): """Search form.""" class ISearchTable(ITable): """Search table."""
z3c.searcher
/z3c.searcher-0.6.0.zip/z3c.searcher-0.6.0/src/z3c/searcher/interfaces.py
interfaces.py
====== README ====== This package provides a persistent search query implementation. This search query is implemented as a filter object which can use search criteria for build the search query. This package also offers some z3c.form based management views which allo us to manage the search filter and it's search criteria. Let's define a site with indexes which allows us to build search filter for. Note, this package depends on the new z3c.indexer package which offers a modular indexing concept. But you can use this package with the zope.app.catalog package too. You only have to build our own search citerium. Start a simple test setup ------------------------- Setup some helpers: >>> import zope.component >>> from zope.site import folder >>> from zope.site import LocalSiteManager >>> from z3c.indexer.interfaces import IIndex Setup a site >>> class SiteStub(folder.Folder): ... """Sample site.""" >>> site = SiteStub() >>> root['site'] = site >>> sm = LocalSiteManager(site) >>> site.setSiteManager(sm) And set the site as the current site. This is normaly done by traversing to a site: >>> from zope.app.component import hooks >>> hooks.setSite(site) Setup a IIntIds utility: >>> from zope.intid import IntIds >>> from zope.intid.interfaces import IIntIds >>> intids = IntIds() >>> sm['default']['intids'] = intids >>> sm.registerUtility(intids, IIntIds) TextIndex --------- Setup a text index: >>> from z3c.indexer.index import TextIndex >>> textIndex = TextIndex() >>> sm['default']['textIndex'] = textIndex >>> sm.registerUtility(textIndex, IIndex, name='textIndex') FieldIndex ---------- Setup a field index: >>> from z3c.indexer.index import FieldIndex >>> fieldIndex = FieldIndex() >>> sm['default']['fieldIndex'] = fieldIndex >>> sm.registerUtility(fieldIndex, IIndex, name='fieldIndex') ValueIndex ---------- Setup a value index: >>> from z3c.indexer.index import ValueIndex >>> valueIndex = ValueIndex() >>> sm['default']['valueIndex'] = valueIndex >>> sm.registerUtility(valueIndex, IIndex, name='valueIndex') SetIndex -------- Setup a set index: >>> from z3c.indexer.index import SetIndex >>> setIndex = SetIndex() >>> sm['default']['setIndex'] = setIndex >>> sm.registerUtility(setIndex, IIndex, name='setIndex') DemoContent ----------- Define a content object: >>> import persistent >>> import zope.interface >>> from zope.app.container import contained >>> from zope.schema.fieldproperty import FieldProperty >>> class IDemoContent(zope.interface.Interface): ... """Demo content.""" ... title = zope.schema.TextLine( ... title=u'Title', ... default=u'') ... ... body = zope.schema.TextLine( ... title=u'Body', ... default=u'') ... ... field = zope.schema.TextLine( ... title=u'a field', ... default=u'') ... ... value = zope.schema.TextLine( ... title=u'A value', ... default=u'') ... ... iterable = zope.schema.Tuple( ... title=u'A sequence of values', ... default=()) >>> class DemoContent(persistent.Persistent, contained.Contained): ... """Demo content.""" ... zope.interface.implements(IDemoContent) ... ... title = FieldProperty(IDemoContent['title']) ... body = FieldProperty(IDemoContent['body']) ... field = FieldProperty(IDemoContent['field']) ... value = FieldProperty(IDemoContent['value']) ... iterable = FieldProperty(IDemoContent['iterable']) ... ... def __init__(self, title=u''): ... self.title = title ... ... def __repr__(self): ... return '<%s %r>' % (self.__class__.__name__, self.title) Create and add the content object to the site: >>> demo = DemoContent(u'Title') >>> demo.body = u'Body text' >>> demo.field = u'Field' >>> demo.value = u'Value' >>> demo.iterable = (1, 2, 'Iterable') >>> site['demo'] = demo The zope event subscriber for __setitem__ whould call the IIntIds register method for our content object. But we didn't setup the relevant subscribers, so we do this here: >>> uid = intids.register(demo) Indexer ------- Setup a indexer adapter for our content object. >>> from z3c.indexer.indexer import MultiIndexer >>> class DemoIndexer(MultiIndexer): ... zope.component.adapts(IDemoContent) ... ... def doIndex(self): ... ... # index context in valueIndex ... valueIndex = self.getIndex('textIndex') ... txt = '%s %s' % (self.context.title, self.context.body) ... valueIndex.doIndex(self.oid, txt) ... ... # index context in fieldIndex ... fieldIndex = self.getIndex('fieldIndex') ... fieldIndex.doIndex(self.oid, self.context.field) ... ... # index context in setIndex ... setIndex = self.getIndex('setIndex') ... setIndex.doIndex(self.oid, self.context.iterable) ... ... # index context in valueIndex ... valueIndex = self.getIndex('valueIndex') ... valueIndex.doIndex(self.oid, self.context.value) Register the indexer adapter as a named adapter: >>> zope.component.provideAdapter(DemoIndexer, name='DemoIndexer') Indexing -------- Before we start indexing, we check the index: >>> textIndex.documentCount() 0 >>> fieldIndex.documentCount() 0 >>> setIndex.documentCount() 0 >>> valueIndex.documentCount() 0 Now we can index our demo object: >>> from z3c.indexer.indexer import index >>> index(demo) And check our indexes: >>> textIndex.documentCount() 1 >>> fieldIndex.documentCount() 1 >>> setIndex.documentCount() 1 >>> valueIndex.documentCount() 1 Search Filter ------------- Now we are ready and can start with our search filter implementation. The following search filter returns no results by default because it defines NoTerm as getDefaultQuery. This is usefull if you have a larg set of data and you like to start with a empty query if no cirterium is selected. >>> from z3c.searcher import interfaces >>> from z3c.searcher.filter import EmptyTerm >>> from z3c.searcher.filter import SearchFilter >>> class IContentSearchFilter(interfaces.ISearchFilter): ... """Search filter for content objects.""" >>> class ContentSearchFilter(SearchFilter): ... """Content search filter.""" ... ... zope.interface.implements(IContentSearchFilter) ... ... def getDefaultQuery(self): ... return EmptyTerm() Search Criterium ---------------- And we define a criterium for our demo content. This text search criterium uses the text index registered as ``textIndex`` above: >>> from z3c.searcher import criterium >>> class TextCriterium(criterium.TextCriterium): ... """Full text search criterium for ``textIndex`` index.""" ... ... indexOrName = 'textIndex' Such a criterium can search in our index. Let's start with a empty search query: >>> from z3c.indexer.search import SearchQuery >>> searchQuery = SearchQuery() You can see that the searchQuery returns a empty result. >>> len(searchQuery.searchResults()) 0 showcase ~~~~~~~~ Now we can create a criterium instance and give them a value: >>> sampleCriterium = TextCriterium() >>> sampleCriterium.value = u'Bod*' Now the criterium is able to search in it's related index within the given value within a given (emtpy) search query. This empty query is only used as a chainable query object. Each result get added or removed from this chain dependent on it's connector ``And``, ``OR`` or ``Not``: >>> searchQuery = sampleCriterium.search(searchQuery) Now you can see that our criterium found a result from the text index: >>> len(searchQuery.searchResults()) 1 >>> content = list(searchQuery.searchResults())[0] >>> content.body u'Body text' Search Criterium Factory ------------------------ The test above shows you how criterium can search in indexes. But that's not all. Our concept offers a search filter which can manage more then one search criterium in a filter. A criterium is an adapter for a filter. This means we need to create an adapter factory and register this factory as an adapter for our filter. Let's now create this criterium adapter factory: >>> textCriteriumFactory = criterium.factory(TextCriterium, 'fullText') This search criterium factory class implements ISearchCriteriumFactory: >>> interfaces.ISearchCriteriumFactory.implementedBy(textCriteriumFactory) True and we register this adapter for our content search filter: >>> zope.component.provideAdapter(textCriteriumFactory, ... (IContentSearchFilter,), name='fullText') showcase ~~~~~~~~ Now you can see that our content search filter knows about the search criterium factories: >>> contentSearchFilter = ContentSearchFilter() >>> contentSearchFilter.criteriumFactories [(u'fullText', <z3c.searcher.criterium.TextCriteriumFactory object at ...>)] Since the search criterium factory is an adapter for our search filter, the factory can adapt our contentSearchFilter: >>> textCriteriumFactory = textCriteriumFactory(contentSearchFilter) >>> textCriteriumFactory <z3c.searcher.criterium.TextCriteriumFactory object at ...> Now we can call the factory and we will get back our search criterium instance: >>> textCriterium = textCriteriumFactory() >>> textCriterium <TextCriterium object at ...> Our search criterium provides ISearchCriterium: >>> interfaces.ISearchCriterium.providedBy(textCriterium) True Search Example -------------- Now we are ready to search within our filter construct. First let's create a plain content search filter: >>> sampleFilter = ContentSearchFilter() Then let's add a criterium by it's factory name: >>> sampleCriterium = sampleFilter.createCriterium('fullText') Now we can set a value for the criterium: >>> sampleCriterium.value = u'Title' And add the criterium to our filter: >>> sampleFilter.addCriterium(sampleCriterium) That's all, now our filter is a ble to genearet a query: >>> sampleQuery = sampleFilter.generateQuery() And the sample search query can return the result: >>> len(sampleQuery.searchResults()) 1 >>> content = list(sampleQuery.searchResults())[0] >>> content.title u'Title' Search Session -------------- Before we show how to use the criterium and filter within z3c.form components, we will show you how the search session is working. Let's register and create a search session: >>> from z3c.searcher import session >>> zope.component.provideAdapter(session.SearchSession) Now we can create a test request and get the session as adapter for a request: >>> import z3c.form.testing >>> request = z3c.form.testing.TestRequest() >>> searchSession = interfaces.ISearchSession(request) >>> searchSession <z3c.searcher.session.SearchSession object at ...> The search session offers an API for store and manage filters: >>> searchSession.addFilter('foo', sampleFilter) And we can get such filters from the search session by name. >>> searchSession.getFilter('foo') <ContentSearchFilter object at ...> Or we can get all search filters sotred in this session: >>> searchSession.getFilters() [<ContentSearchFilter object at ...>] And we can remove a filter by it's name: >>> searchSession.removeFilter('foo') >>> searchSession.getFilters() [] There is also another argument called ``key`` in the search session methods. This argument can be used as namespace. If you need to support a specific filter only for one object instance, you can use a key which is unique to that object as discriminator. >>> myFilter = ContentSearchFilter() >>> searchSession.addFilter('foo', myFilter, key='myKey') Such filters are only available if the right ``key`` is used: >>> searchSession.getFilter('foo') is None True >>> searchSession.getFilter('foo', key='myKey') <ContentSearchFilter object at ...> >>> searchSession.getFilters() [] Now let's cleanup our search session and remove the filter stored by the key: >>> searchSession.getFilters('myKey') [<ContentSearchFilter object at ...>] >>> searchSession.removeFilter('foo', 'myKey') >>> searchSession.getFilters('myKey') [] Criterium Form -------------- Now we will show you how the form part is working. Each criterium can render itself within a form. We offer a CriteriumForm class for doing this. Let's create and render such a criterium form: >>> import z3c.form.testing >>> from z3c.searcher import form >>> criteriumRow = form.CriteriumForm(textCriterium, request) >>> criteriumRow <z3c.searcher.form.CriteriumForm object at ...> We also need to set a prefix, this is normaly done by the search form by calling setupCriteriumRows. And normaly the criterium is located in the search filter. We just need a criterium __name__ for now: >>> textCriterium.__name__ = u'1' >>> criteriumRow.prefix = 'form.criterium.%s' % str(textCriterium.__name__) >>> criteriumRow.prefix 'form.criterium.1' Before we can render the form, we need to register the templates: >>> from zope.configuration import xmlconfig >>> import zope.component >>> import zope.viewlet >>> import zope.app.component >>> import zope.app.security >>> import zope.app.publisher.browser >>> import z3c.template >>> import z3c.macro >>> import z3c.formui >>> xmlconfig.XMLConfig('meta.zcml', zope.component)() >>> xmlconfig.XMLConfig('meta.zcml', zope.viewlet)() >>> xmlconfig.XMLConfig('meta.zcml', zope.app.component)() >>> xmlconfig.XMLConfig('meta.zcml', zope.app.security)() >>> xmlconfig.XMLConfig('meta.zcml', zope.app.publisher.browser)() >>> xmlconfig.XMLConfig('meta.zcml', z3c.macro)() >>> xmlconfig.XMLConfig('meta.zcml', z3c.template)() >>> xmlconfig.XMLConfig('div-form.zcml', z3c.formui)() >>> context = xmlconfig.file('meta.zcml', z3c.template) >>> context = xmlconfig.string(""" ... <configure ... xmlns:z3c="http://namespaces.zope.org/z3c"> ... <configure package="z3c.searcher"> ... <z3c:template ... template="filter.pt" ... for=".form.FilterForm" ... /> ... <z3c:template ... template="criterium.pt" ... for=".form.CriteriumForm" ... /> ... <z3c:template ... template="search.pt" ... for=".form.SearchForm" ... /> ... <z3c:template ... template="table.pt" ... for=".table.SearchTable" ... /> ... </configure> ... </configure> ... """, context=context) And we also need some widgets from z3c.form: >>> import z3c.form.testing >>> z3c.form.testing.setupFormDefaults() Now we can render the criterium form: >>> criteriumRow.update() >>> print criteriumRow.render() <tr> <td style="padding-right:5px;"> <span>Text</span> </td> <td style="padding-right:5px;"> <b>matches</b> </td> <td style="padding-right:5px;"> <input id="form-criterium-1-widgets-value" name="form.criterium.1.widgets.value" class="text-widget required textline-field" value="" type="text" /> <span class="option"> <label for="form-criterium-1-widgets-connectorName-0"> <input id="form-criterium-1-widgets-connectorName-0" name="form.criterium.1.widgets.connectorName:list" class="radio-widget required choice-field" value="OR" checked="checked" type="radio" /> <span class="label">or</span> </label> </span> <span class="option"> <label for="form-criterium-1-widgets-connectorName-1"> <input id="form-criterium-1-widgets-connectorName-1" name="form.criterium.1.widgets.connectorName:list" class="radio-widget required choice-field" value="AND" type="radio" /> <span class="label">and</span> </label> </span> <span class="option"> <label for="form-criterium-1-widgets-connectorName-2"> <input id="form-criterium-1-widgets-connectorName-2" name="form.criterium.1.widgets.connectorName:list" class="radio-widget required choice-field" value="NOT" type="radio" /> <span class="label">not</span> </label> </span> <input name="form.criterium.1.widgets.connectorName-empty-marker" type="hidden" value="1" /> </td> <td style="padding-right:5px;"> <input id="form-criterium-1-buttons-remove" name="form.criterium.1.buttons.remove" class="submit-widget button-field" value="Remove" type="submit" /> </td> </tr> Filter Form ------------ There is also a filter form which can represent the SearchFilter. This form includes the CriteriumForm part. Note we uses a dumy context becaue it's not relevant where you render this form because the form will get the filters from the session. >>> filterForm = form.FilterForm(object(), request) >>> filterForm <z3c.searcher.form.FilterForm object at ...> But before we can use the form, we need to set our search filter class as factory. Because only this search filter knows our criteria: >>> filterForm.filterFactory = ContentSearchFilter Now we can render our filter form: >>> filterForm.update() >>> print filterForm.render() <fieldset> <legend>Filter</legend> <div> <label for="filterformnewCriterium"> New Criterium </label> <select name="filterformnewCriterium" size="1"> <option value="fullText">fullText</option> </select> <input id="filterform-buttons-add" name="filterform.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> </div> <div> <input id="filterform-buttons-search" name="filterform.buttons.search" class="submit-widget button-field" value="Search" type="submit" /> <input id="filterform-buttons-clear" name="filterform.buttons.clear" class="submit-widget button-field" value="Clear" type="submit" /> </div> </fieldset> Search Form ----------- There is also a search form which allows you to simply define a search page. This search form uses the criterium and filter form and allows you to simply create a search page. Let's define a custom search page: >>> class ContentSearchForm(form.SearchForm): ... ... filterFactory = ContentSearchFilter Before we can use the form, our request needs to provide the form UI layer: >>> from zope.interface import alsoProvides >>> from z3c.formui.interfaces import IDivFormLayer >>> alsoProvides(request, IDivFormLayer) That's all you need for write a simple search form. This form uses it's own content search filter and of corse the criteria configured for this filter. >>> searchForm = ContentSearchForm(object(), request) >>> searchForm.update() >>> print searchForm.render() <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="form" id="form"> <div class="viewspace"> <div> <fieldset> <legend>Filter</legend> <div> <label for="filterformnewCriterium"> New Criterium </label> <select name="filterformnewCriterium" size="1"> <option value="fullText">fullText</option> </select> <input id="filterform-buttons-add" name="filterform.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> </div> <div> <input id="filterform-buttons-search" name="filterform.buttons.search" class="submit-widget button-field" value="Search" type="submit" /> <input id="filterform-buttons-clear" name="filterform.buttons.clear" class="submit-widget button-field" value="Clear" type="submit" /> </div> </fieldset> </div> <div> </div> </div> <div> <div class="buttons"> </div> </div> </form> Search Table ------------ There is also a search table. This search table uses the criterium and filter form and allows you to simply create a search page which will list the results as table. Let's define a custom search table: >>> from z3c.searcher import table >>> class ContentSearchTable(table.SearchTable): ... ... filterFactory = ContentSearchFilter Before we can use the form, our request needs to provide the form UI layer: >>> from zope.interface import alsoProvides >>> from z3c.formui.interfaces import IDivFormLayer >>> alsoProvides(request, IDivFormLayer) That's all you need for write a simple search form. This form uses it's own content search filter and of corse the criteria configured for this filter. >>> searchTable = ContentSearchTable(object(), request) >>> searchTable.update() >>> print searchTable.render() <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" name="formTable" id="formTable"> <div class="viewspace"> <div> <div class="filterForm"> <fieldset> <legend>Filter</legend> <div> <label for="filterformnewCriterium"> New Criterium </label> <select name="filterformnewCriterium" size="1"> <option value="fullText">fullText</option> </select> <input id="filterform-buttons-add" name="filterform.buttons.add" class="submit-widget button-field" value="Add" type="submit" /> </div> <div> <input id="filterform-buttons-search" name="filterform.buttons.search" class="submit-widget button-field" value="Search" type="submit" /> <input id="filterform-buttons-clear" name="filterform.buttons.clear" class="submit-widget button-field" value="Clear" type="submit" /> </div> </fieldset> </div> <div> </div> </div> </div> <div> <div class="buttons"> </div> </div> </form>
z3c.searcher
/z3c.searcher-0.6.0.zip/z3c.searcher-0.6.0/src/z3c/searcher/README.txt
README.txt
__docformat__ = "reStructuredText" import persistent import persistent.list import zope.component import zope.interface import zope.event import zope.lifecycleevent from zope.location import location from zope.container import contained from z3c.indexer import query from z3c.indexer.search import SearchQuery from z3c.searcher import interfaces class EmptyTerm(object): """Return a empty list as result.""" def apply(self): return [] class SearchFilter(persistent.Persistent, contained.Contained): """Persistent search filter implementation. This component uses the component architecture to determine its available criterium components. """ zope.interface.implements(interfaces.ISearchFilter) counter = 0 def __init__(self): super(SearchFilter, self).__init__() self.criteria = persistent.list.PersistentList() self.counter = 0 def clear(self): """See interfaces.ISearchFilter""" self.__init__() @property def criteriumFactories(self): """See interfaces.ISearchFilter""" adapters = zope.component.getAdapters( (self,), interfaces.ISearchCriteriumFactory) return sorted(adapters, key=lambda (n, a): a.weight) def createCriterium(self, name, value=interfaces.NOVALUE): """Create a criterium.""" criterium = zope.component.getAdapter( self, interfaces.ISearchCriteriumFactory, name=name)() if value is not interfaces.NOVALUE: criterium.value = value criterium.__parent__ = self return criterium def addCriterium(self, criterium): """See interfaces.ISearchFilter""" self.counter += 1 location.locate(criterium, self, unicode(self.counter)) self.criteria.append(criterium) def createAndAddCriterium(self, name, value=interfaces.NOVALUE): criterium = self.createCriterium(name) if value is not interfaces.NOVALUE: criterium.value = value zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(criterium)) self.addCriterium(criterium) def removeCriterium(self, criterium): """See interfaces.ISearchFilter""" self.criteria.remove(criterium) def getDefaultQuery(self): """See interfaces.ISearchFilter""" return EmptyTerm() def getAndQuery(self): """See interfaces.ISearchFilter""" return None def getNotQuery(self): """See interfaces.ISearchFilter""" return None def generateQuery(self): """See interfaces.ISearchFilter""" # If no criteria are selected, return all values if not len(self.criteria): return self.getDefaultQuery() searchQuery = SearchQuery() # order the criterium by the order or, and, not orCriteria = [] andCriteria = [] notCriteria = [] for criterium in self.criteria: if criterium.connectorName == interfaces.CONNECTOR_OR: orCriteria.append(criterium) if criterium.connectorName == interfaces.CONNECTOR_AND: andCriteria.append(criterium) if criterium.connectorName == interfaces.CONNECTOR_NOT: notCriteria.append(criterium) # apply given ``or`` criteria if any for criterium in orCriteria: searchQuery = criterium.search(searchQuery) # apply given ``and`` criteria if any for criterium in andCriteria: searchQuery = criterium.search(searchQuery) # apply default ``And`` query if available andQuery = self.getAndQuery() if andQuery is not None: searchQuery = searchQuery.And(andQuery) # apply (remove) default ``Not`` query if available notQuery = self.getNotQuery() if notQuery is not None: return query.Not(self.getNotQuery) # apply given ``not`` criteria if any for criterium in notCriteria: searchQuery = criterium.search(searchQuery) return searchQuery
z3c.searcher
/z3c.searcher-0.6.0.zip/z3c.searcher-0.6.0/src/z3c/searcher/filter.py
filter.py
__docformat__ = "reStructuredText" import persistent import zope.interface from zope.schema.fieldproperty import FieldProperty from zope.container import contained from z3c.indexer import query from z3c.searcher import interfaces from z3c.searcher.interfaces import _ class SearchCriterium(persistent.Persistent, contained.Contained): """Search criterium for some data. This search criterium is implemented as an adapter to the search """ zope.interface.implements(interfaces.ISearchCriterium) label = None indexOrName = None # See interfaces.ISearchCriterium operator = query.Eq operatorLabel = _('equals') value = FieldProperty(interfaces.ISearchCriterium['value']) connectorName = FieldProperty(interfaces.ISearchCriterium['connectorName']) def search(self, searchQuery): """See interfaces.ISearchCriterium. Note, this can raise TypeError or zope.index.text.parsetree.ParseError for text index or any other error raised from other indexes. We only catch te TypeError and ParseError in the offered FilterForm. """ operatorQuery = self.operator(self.indexOrName, self.value) if self.connectorName == interfaces.CONNECTOR_OR: return searchQuery.Or(operatorQuery) if self.connectorName == interfaces.CONNECTOR_AND: return searchQuery.And(operatorQuery) if self.connectorName == interfaces.CONNECTOR_NOT: return searchQuery.Not(operatorQuery) class SetSearchCriterium(SearchCriterium): operator = query.AnyOf operatorLabel = _('is') def search(self, searchQuery): """See interfaces.ISearchCriterium. Note, this can raise TypeError or zope.index.text.parsetree.ParseError for text index or any other error raised from other indexes. We only catch te TypeError and ParseError in the offered FilterForm. """ operatorQuery = self.operator(self.indexOrName, [self.value]) if self.connectorName == interfaces.CONNECTOR_OR: return searchQuery.Or(operatorQuery) if self.connectorName == interfaces.CONNECTOR_AND: return searchQuery.And(operatorQuery) if self.connectorName == interfaces.CONNECTOR_NOT: return searchQuery.Not(operatorQuery) class TextCriterium(SearchCriterium): """Search criterium for some data.""" zope.interface.implements(interfaces.ITextCriterium) label = _('Text') operator = query.TextQuery operatorLabel = _('matches') value = FieldProperty(interfaces.ITextCriterium['value']) class SearchCriteriumFactoryBase(object): """Search Criterium Factory.""" zope.interface.implements(interfaces.ISearchCriteriumFactory) klass = None title = None weight = 0 def __init__(self, context): pass def __call__(self): return self.klass() def factory(klass, title): return type('%sFactory' %klass.__name__, (SearchCriteriumFactoryBase,), {'klass': klass, 'title': title})
z3c.searcher
/z3c.searcher-0.6.0.zip/z3c.searcher-0.6.0/src/z3c/searcher/criterium.py
criterium.py
__docformat__ = "reStructuredText" import zope.interface import z3c.formui.form import z3c.table.table from z3c.form import button from z3c.template.template import getPageTemplate from z3c.searcher import interfaces from z3c.searcher.interfaces import _ from z3c.searcher import filter from z3c.searcher import form # conditions def hasContent(form): return form.hasContent def canCancel(form): return form.supportsCancel class SearchTable(z3c.table.table.Table, z3c.formui.form.Form): """Search form with result table.""" zope.interface.implements(interfaces.ISearchTable) template = getPageTemplate() prefix = 'formTable' # internal defaults hasContent = False nextURL = None ignoreContext = False filterForm = None # table defaults cssClasses = {'table': 'contents'} cssClassEven = u'even' cssClassOdd = u'odd' cssClassSelected = u'selected' batchSize = 25 startBatchingAt = 25 # customize this part allowCancel = True filterFactory = filter.SearchFilter def setupFilterForm(self): """Setup filter form before super form get updated.""" self.filterForm = form.FilterForm(self.context, self.request) self.filterForm.filterFactory = self.filterFactory def updateFilterForm(self): """Update filter form after super form get updated.""" self.filterForm.update() def setupConditions(self): self.hasContent = bool(self.rows) if self.allowCancel: self.supportsCancel = self.hasContent def updateAfterActionExecution(self): """Update table data if subform changes soemthing.""" # first update table data which probably changed super(SearchTable, self).update() # second setup conditions self.setupConditions() # third update action which we have probably different conditions for self.updateActions() def update(self): # 1 .setup filter form self.setupFilterForm() # 2. process filter form self.updateFilterForm() # 3. setup widgets self.updateWidgets() # 4. setup search values, generate rows, setup headers and columns super(SearchTable, self).update() # 5. setup conditions self.setupConditions() # 6. setup form part self.updateActions() self.actions.execute() @property def values(self): return self.filterForm.values() @button.buttonAndHandler(_('Cancel'), name='cancel', condition=canCancel) def handleCancel(self, action): self.nextURL = self.request.getURL() def render(self): """Render the template.""" if self.nextURL is not None: self.request.response.redirect(self.nextURL) return "" return self.template()
z3c.searcher
/z3c.searcher-0.6.0.zip/z3c.searcher-0.6.0/src/z3c/searcher/table.py
table.py
================ z3c.securitytool ================ z3c.securitytool is a Zope3 package aimed at providing component level security information to assist in analyzing security problems and to potentially expose weaknesses. The goal of the security tool is to provide a matrix of users and their effective permissions for all available views for any given component and context. We also provide two further levels of detail. You can view the details of how a user came to have the permission on a given view, by clicking on the permission in the matrix. .. image:: http://farm3.static.flickr.com/2318/2521732872_81a709e3db_m.jpg :height: 200 :width: 400 :target: http://flickr.com/photos/blackburnd/ ================= Demo Instructions ================= You can run the demo by downloading just the securitytool package - ``# svn co svn://svn.zope.org/repos/main/z3c.securitytool/trunk securitytool`` - ``# cd securitytool`` - ``# python bootstrap.py`` - ``# ./bin/buildout`` - ``# ./bin/demo fg`` Then access the demo site using: - http://localhost:8080/++skin++SecurityTool/securityMatrix.html - user: admin - password: admin There are some folders added with permissions and roles applied to show the settings in the demo. - http://localhost:8080/++skin++SecurityTool/Folder1/securityMatrix.html - http://localhost:8080/++skin++SecurityTool/Folder1/Folder2/securityMatrix.html These permissions should mirror what you see in the @@grant.html views - http://localhost:8080/Folder1/Folder2/@@grant.html - http://localhost:8080/Folder1/@@grant.html ``(These settings are added when the database is first opened`` ``You can find these settings in demoSetup.py)`` ============================================== How to use the securityTool with your project: ============================================== Remember this is a work in progress. 1. Add the z3c.securitytool to your install_requires in your setup.py. 2. Add the <include package="z3c.securitytool"/> to your site.zcml 3. Use the skin `++skin++SecurityTool` to access securityTool pages 4. Append @@securityMatrix.html view to any context to view the permission matrix for that context using the security tool skin. For example: http://localhost:8080/++skin++SecurityTool/Folder1/@@securityMatrix.html
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/README.txt
README.txt
from zope.app import zapi from zope.app.apidoc.presentation import getViewInfoDictionary from zope.interface import Interface, implements, providedBy from zope.publisher.browser import TestRequest, applySkin from zope.component import adapts from zope.publisher.interfaces.browser import IBrowserRequest from zope.securitypolicy.interfaces import Allow, Unset, Deny from z3c.securitytool.globalfunctions import * from z3c.securitytool.matrixdetails import MatrixDetails from z3c.securitytool import interfaces class PrincipalDetails(MatrixDetails): implements(interfaces.IPrincipalDetails) adapts(Interface) def __call__(self,principal_id, skin=IBrowserRequest): """Return all security settings (permissions, groups, roles) for all interfaces provided by this context for a `principal_id`, and of course we are only after browser views""" request = TestRequest() applySkin(request, skin) pMatrix = {'permissions': [], 'permissionTree': [], 'roles': {}, 'roleTree': [], 'groups': {}} ifaces = tuple(providedBy(self.context)) for iface in ifaces: for view_reg in getViews(iface, IBrowserRequest): view = getView(self.context, view_reg, skin) if not view: continue all_settings = [{name:val} for name,val in settingsForObject(view) ] self.roleSettings, junk = getSettingsForMatrix(view) self.updatePrincipalMatrix(pMatrix, principal_id, all_settings) principals = zapi.principals() principal = principals.getPrincipal(principal_id) if principal.groups: for group_id in principal.groups: gMatrix = {group_id: self(group_id)} pMatrix['groups'].update(gMatrix) # The following section updates the principalPermissions with # the permissions found in the groups assigned. if the permisssion # already exists for the principal then we ignore it. permList = [x.items()[1][1] for x in pMatrix['permissions']] for matrix in gMatrix.values(): for tmp in matrix['permissions']: gPerm = tmp['permission'] if gPerm not in permList: pMatrix['permissions'].append(tmp) self.orderRoleTree(pMatrix) return pMatrix def updateMatrixRoles(self, pMatrix, principal_id, name, item): """ updates the MatrixRoles for the PrincipalDetails class """ for curRole in item.get('principalRoles', ()): if curRole['principal'] != principal_id: continue role = curRole['role'] parentList = item.get('parentList',None) if parentList: # If we have a parent list we want to populate the tree self.updateRoleTree(pMatrix, item,parentList,curRole) if curRole['setting'] == Deny: try: # Here we see if we have added a security setting with # this role before, if it is now denied we remove it. del pMatrix['roles'][role] except: #Cannot delete something that is not there pass else: self.updateRoles(pMatrix,item,role,curRole)
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/src/z3c/securitytool/principaldetails.py
principaldetails.py
from zope.app import zapi from zope.publisher.interfaces import IRequest from zope.publisher.interfaces.browser import IBrowserRequest from zope.component import adapts, getGlobalSiteManager from zope.publisher.browser import TestRequest, applySkin from zope.securitypolicy.interfaces import IPrincipalPermissionMap from zope.securitypolicy.interfaces import IPrincipalRoleMap from zope.securitypolicy.interfaces import IRolePermissionMap from zope.securitypolicy.principalpermission import principalPermissionManager from zope.securitypolicy.principalrole import principalRoleManager from zope.securitypolicy.rolepermission import rolePermissionManager def getViews(iface, reqType=IRequest): """Get all view registrations for a particular interface.""" gsm = getGlobalSiteManager() for reg in gsm.registeredAdapters(): if (len(reg.required) == 2 and reg.required[1] is not None and reqType.isOrExtends(reg.required[1])): if (reg.required[0] is None or iface.isOrExtends(reg.required[0])): yield reg def hasPermissionSetting(settings): """Check recursively if a security mapping contains any permission setting. """ if (settings['permissions'] or settings['roles']): return True for setting in settings['groups'].values(): if hasPermissionSetting(setting): return True return False def principalDirectlyProvidesPermission(prinPermMap, principal_id, permission_id): """Return directly provided permission setting for a given principal and permission. """ for prinPerm in prinPermMap: if (prinPerm['principal'] == principal_id and prinPerm['permission'] == permission_id): return prinPerm['setting'].getName() def roleProvidesPermission(rolePermMap, role_id, permission_id): """Return the permission setting for a given role and permission.""" for rolePerm in rolePermMap: if (rolePerm['role'] == role_id and rolePerm['permission'] == permission_id): return rolePerm['setting'].getName() def principalRoleProvidesPermission(prinRoleMap, rolePermMap, principal_id, permission_id,role=None): """Return the role id and permission setting for a given principal and permission. """ if role: for prinRole in prinRoleMap: if (prinRole['principal'] == principal_id and prinRole['setting'].getName() == 'Allow' and role == prinRole['role']): role_id = prinRole['role'] return (role_id, roleProvidesPermission(rolePermMap, role_id, permission_id)) for prinRole in prinRoleMap: if (prinRole['principal'] == principal_id and prinRole['setting'].getName() == 'Allow'): role_id = prinRole['role'] return (role_id, roleProvidesPermission(rolePermMap, role_id, permission_id)) return (None, None) def renderedName(name): """The root folder is the only unlocated context object.""" if name is None: return u'Root Folder' return name def settingsForObject(ob): """Analysis tool to show all of the grants to a process This method was copied from zopepolicy.py in the zope. security policy package. Also needed to add a parentList this just helps locate the object when we display it to the user. """ result = [] while ob is not None: data = {} principalPermissions = IPrincipalPermissionMap(ob, None) if principalPermissions is not None: settings = principalPermissions.getPrincipalsAndPermissions() #settings.sort() #The only difference from the original method data['principalPermissions'] = [ {'principal': pr, 'permission': p, 'setting': s} for (p, pr, s) in settings] principalRoles = IPrincipalRoleMap(ob, None) if principalRoles is not None: settings = principalRoles.getPrincipalsAndRoles() data['principalRoles'] = [ {'principal': p, 'role': r, 'setting': s} for (r, p, s) in settings] rolePermissions = IRolePermissionMap(ob, None) if rolePermissions is not None: settings = rolePermissions.getRolesAndPermissions() data['rolePermissions'] = [ {'permission': p, 'role': r, 'setting': s} for (p, r, s) in settings] parent = getattr(ob, '__parent__', None) while parent is not None: if not data.has_key('parentList'): data['parentList'] = [] thisName = getattr(ob, '__name__') or 'Root Folder' data['parentList'].append(thisName) if parent: name = getattr(parent, '__name__') or 'Root Folder' data['parentList'].append(name) parent = getattr(parent, '__parent__', None) result.append((getattr(ob, '__name__', '(no name)'), data)) ob = getattr(ob, '__parent__', None) # This is just to create an internal unique name for the object # using the name and depth of the object. Im not sure but a # linkedlist may be a better approach. if data.has_key('parentList'): data['uid'] = data['parentList'][0]+"_" + \ str(len(data['parentList'])) # Here we need to add the parentlist and uid to display it properly # in the roleTree and in the permissionTree result[-1][1]['parentList'] = ['Root Folder'] result[-1][1]['uid'] = 'Root Folder' result[-1][1]['name'] = 'Root Folder' data = {} result.append(('global settings', data)) settings = principalPermissionManager.getPrincipalsAndPermissions() settings.sort() data['principalPermissions'] = [ {'principal': pr, 'permission': p, 'setting': s} for (p, pr, s) in settings] settings = principalRoleManager.getPrincipalsAndRoles() data['principalRoles'] = [ {'principal': p, 'role': r, 'setting': s} for (r, p, s) in settings] settings = rolePermissionManager.getRolesAndPermissions() data['rolePermissions'] = [ {'permission': p, 'role': r, 'setting': s} for (p, r, s) in settings] data['parentList'] = ['global settings'] data['uid'] = 'global settings' return result def getSettingsForMatrix(viewInstance): """ Here we aggregate all the principal permissions into one object We need them all for our lookups to work properly in principalRoleProvidesPermission. """ allSettings = {} permSetting = () settingList = [val for name ,val in settingsForObject(viewInstance)] # The settings list is an aggregate of all settings # so we can lookup permission settings for any role for setting in settingList: for key,val in setting.items(): if not allSettings.has_key(key): allSettings[key] = [] allSettings[key].extend(val) settings= settingsForObject(viewInstance) settings.reverse() return allSettings, settings def getView(context, view_reg, skin=IBrowserRequest): """Instantiate view from given registration and skin. Return `None` if the view isn't callable. """ request = TestRequest() applySkin(request, skin) try: view_inst = view_reg.factory(context, request) if callable(view_inst): return view_inst except TypeError: pass def mergePermissionsFromGroups(principals,matrix): """ This method recursively looks through all the principals in the viewPermMatrix and inspects the inherited permissions from groups assigned to the principal. """ # Actually this does need a post-order depth first... # Thanks Jacob sysPrincipals = zapi.principals() for principal in principals: for group_id in principal.groups: group = sysPrincipals.getPrincipal(group_id) mergePermissionsFromGroups([sysPrincipals.getPrincipal(x) for x in principal.groups],matrix) if matrix.has_key(group_id): res = matrix[group_id] for item in res: # We only want the setting if we do not alread have it. # or if it is an Allow permission as the allow seems to # override the deny with conflicting group permissions. if item not in matrix[principal.id] or res[item] == 'Allow': matrix[principal.id][item] = res[item]
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/src/z3c/securitytool/globalfunctions.py
globalfunctions.py
from zope.app import zapi from zope.app.apidoc.presentation import getViewInfoDictionary from zope.interface import Interface, implements, providedBy from zope.publisher.browser import TestRequest, applySkin from zope.component import adapts from zope.publisher.interfaces.browser import IBrowserRequest from zope.securitypolicy.interfaces import Allow, Unset, Deny from z3c.securitytool.globalfunctions import * from z3c.securitytool import interfaces from z3c.securitytool.matrixdetails import MatrixDetails class PermissionDetails(MatrixDetails): """Get permission details for a given principal and view. Includes the permissions set by the groups the principal belongs to. """ implements(interfaces.IPermissionDetails) adapts(Interface) def __call__(self,principal_id,view_name, skin=IBrowserRequest): self.read_perm = 'zope.Public' self.view_name = view_name self.skin = skin request = TestRequest() applySkin(request, skin) pMatrix = {'permissions': [], 'permissionTree': [], 'roles': {}, 'roleTree': [], 'groups': {}} ifaces = tuple(providedBy(self.context)) for iface in ifaces: for view_reg in getViews(iface, skin): if view_reg.name == view_name: view = getView(self.context, view_reg, skin) all_settings = [{name:val} for name,val in settingsForObject(view) ] self.read_perm = \ getViewInfoDictionary(view_reg)['read_perm']\ or 'zope.Public' self.roleSettings, junk = getSettingsForMatrix(view) self.rolePermMap = self.roleSettings.get( 'rolePermissions', ()) self.updatePrincipalMatrix(pMatrix, principal_id, all_settings) break principals = zapi.principals() principal = principals.getPrincipal(principal_id) if principal.groups: for group_id in principal.groups: gMatrix = {group_id: self(group_id,view_name,skin)} pMatrix['groups'].update(gMatrix) # The following section updates the principalPermissions with # the permissions found in the groups assigned. if the permisssion # already exists for the principal then we ignore it. permList = [x.items()[1][1] for x in pMatrix['permissions']] for matrix in gMatrix.values(): for tmp in matrix['permissions']: gPerm = tmp['permission'] if gPerm not in permList: pMatrix['permissions'].append(tmp) self.orderRoleTree(pMatrix) return pMatrix def updateMatrixRoles(self, pMatrix, principal_id, name, item): """ Updates the roles for the PermissionDetails class """ for curRole in item.get('principalRoles', ()): if curRole['principal'] != principal_id: continue role = curRole['role'] perm = roleProvidesPermission(self.rolePermMap, role, self.read_perm ) if perm != 'Allow' and perm != 'Deny': continue parentList = item.get('parentList',None) if parentList: # If we have a parent list we want to populate the tree self.updateRoleTree(pMatrix, item,parentList,curRole) if curRole['setting'] == Deny: try: # Here we see if we have added a security setting with # this role before, if it is now denied we remove it. del pMatrix['roles'][role] except: #Cannot delete something that is not there pass else: self.updateRoles(pMatrix, item,role,curRole)
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/src/z3c/securitytool/permissiondetails.py
permissiondetails.py
import transaction from zope.app.folder import Folder from zope.app import zapi from zope.app.appsetup.bootstrap import getInformationFromEvent from zope.securitypolicy.interfaces import IPrincipalPermissionManager from zope.securitypolicy.interfaces import IPrincipalRoleManager class Participation: interaction = None class CreateStructure(object): def __init__(self,event): """ This method gets called on IDatabaseOpenedEvent when running the Demo we add some seemingly random security permissions to the folder tree created below so users of the demo can see what security tool can display """ db, connection, root, root_folder = getInformationFromEvent(event) # Lets get the root folder so we can assign some permissions to # specific contexts root=zapi.getRoot(root_folder) # If the following folders do not exist... lets create them if 'Folder1' not in root: root['Folder1'] = Folder() if 'Folder2' not in root['Folder1']: root['Folder1']['Folder2'] = Folder() if 'Folder3' not in root['Folder1']['Folder2']: root['Folder1']['Folder2']['Folder3'] = Folder() # Lets get the list of all principals on the system. sysPrincipals = zapi.principals() principals = [x.id for x in sysPrincipals.getPrincipals('') if x.id not in ['zope.group1','zope.group2','zope.randy']] # Here is where we begin to set the permissions for the root context level roleManager = IPrincipalRoleManager(root) permManager = IPrincipalPermissionManager(root) roleManager.assignRoleToPrincipal('zope.Editor', 'zope.group1') # Here we assign the group group1 to zope.daniel and zope.randy group1 = sysPrincipals.getPrincipal('zope.group1') group2 = sysPrincipals.getPrincipal('zope.group2') daniel = sysPrincipals.getPrincipal('zope.daniel') randy = sysPrincipals.getPrincipal('zope.randy') # We add group1 and group2 to Randy to make sure that the # allow permission overrides the Deny permission at the # same level. randy.groups.append('zope.group1') randy.groups.append('zope.group2') # We add randy as a group to daniel with a subgroup # of group1 and and group2 daniel.groups.append('zope.randy') roleManager.assignRoleToPrincipal('zope.Writer', 'zope.daniel') roleManager.assignRoleToPrincipal('zope.Writer', 'zope.stephan') for principal in principals: permManager.grantPermissionToPrincipal('concord.ReadIssue', principal) permManager.denyPermissionToPrincipal('concord.DeleteArticle', principal) permManager.denyPermissionToPrincipal('concord.CreateArticle', principal) # Now at the root level we will deny all the permissions to group2 and # Allow all the permissions to group 1 for perm in ['concord.DeleteIssue', 'concord.CreateIssue', 'concord.ReadIssue', 'concord.CreateArticle', 'concord.DeleteArticle', 'concord.PublishIssue']: permManager.denyPermissionToPrincipal(perm, group1.id) permManager.grantPermissionToPrincipal(perm,group2.id) # Here is where we begin to set the permissions for the context level of # Folder1. roleManager = IPrincipalRoleManager(root['Folder1']) permManager = IPrincipalPermissionManager(root['Folder1']) roleManager.assignRoleToPrincipal('zope.Janitor', 'zope.markus') roleManager.assignRoleToPrincipal('zope.Writer', 'zope.daniel') for principal in principals: permManager.denyPermissionToPrincipal('concord.ReadIssue', principal) permManager.grantPermissionToPrincipal('concord.DeleteIssue', principal) permManager.grantPermissionToPrincipal('concord.CreateArticle', principal) # Here is where we begin to set the permissions for the context level of # /root/Folder1/Folder2. roleManager = IPrincipalRoleManager(root['Folder1']['Folder2']) permManager = IPrincipalPermissionManager(root['Folder1']['Folder2']) roleManager.assignRoleToPrincipal('zope.Janitor', 'zope.markus') roleManager.assignRoleToPrincipal('zope.Writer', 'zope.daniel') permManager.denyPermissionToPrincipal('concord.CreateArticle', 'zope.daniel') permManager.denyPermissionToPrincipal('concord.CreateIssue', 'zope.daniel') permManager.denyPermissionToPrincipal('concord.CreateIssue', 'zope.stephan') permManager.denyPermissionToPrincipal('concord.CreateIssue', 'zope.markus') permManager.denyPermissionToPrincipal('concord.CreateIssue', 'zope.anybody') # Here is where we begin to set the permissions for the context level of # /root/Folder1/Folder2/Folder3. roleManager = IPrincipalRoleManager(root['Folder1']\ ['Folder2']\ ['Folder3']) permManager = IPrincipalPermissionManager(root['Folder1']\ ['Folder2']\ ['Folder3']) roleManager.removeRoleFromPrincipal('zope.Writer','zope.daniel') roleManager.removeRoleFromPrincipal('zope.Janitor', 'zope.markus') transaction.commit()
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/src/z3c/securitytool/demoSetup.py
demoSetup.py
from zope.app import zapi from zope.securitypolicy.interfaces import Allow, Unset, Deny class MatrixDetails(object): """ This is the super class of PrincipalDetails and PermissionDetails """ def __init__(self,context): """ init method for the super class """ self.context = context def updatePrincipalMatrix(self, pMatrix, principal_id, settings): """ this method recursively populates the principal permissions dict (MatrixDetails) """ principals = zapi.principals() principal = principals.getPrincipal(principal_id) for setting in settings: for name, item in setting.items(): self.updateMatrixRoles(pMatrix, principal_id, name,item) self.updateMatrixPermissions(pMatrix, principal_id, item) def updateMatrixPermissions(self, pMatrix, principal_id, item): """ Here we get all the permissions for the given principal on the item passed. """ for prinPerms in item.get('principalPermissions', ()): if principal_id != prinPerms['principal']: continue # If this method is being used by permissionDetails then # we will have a read_perm in the self namespace. If it is # the same as curPerm we can continue curPerm = prinPerms['permission'] if getattr(self,'read_perm',curPerm) != curPerm: continue if item.get('parentList',None): self.updatePermissionTree(pMatrix, item,prinPerms) mapping = {'permission': prinPerms['permission'], 'setting' : prinPerms['setting'],} dup = [perm for perm in pMatrix['permissions'] \ if perm['permission'] == mapping['permission']] if dup: # This means we already have a record with this permission # and the next record would be less specific so we continue continue pMatrix['permissions'].append(mapping) def orderRoleTree(self,pMatrix): # This is silly I know but I want global settings at the end try: roleTree = pMatrix['roleTree'] globalSettings = roleTree.pop(0) roleTree.append(globalSettings) except IndexError: # Attempting to pop empty list pass def updateRoleTree(self,pMatrix,item,parentList,curRole): """ This method is responsible for poplating the roletree. """ roleTree = pMatrix['roleTree'] key = item.get('uid') keys = [x.keys()[0] for x in roleTree] # Each key is unique so we just get the list index to edit if key in keys: listIdx = keys.index(key) else: roleTree.append({key:{}}) listIdx = -1 roleTree[listIdx][key]['parentList'] = parentList roleTree[listIdx][key]['name'] = item.get('name') roleTree[listIdx][key].setdefault('roles',[]) # We make sure we only add the roles we do not yet have. if curRole not in roleTree[listIdx][key]['roles']: roleTree[listIdx][key]['roles'].append(curRole) def updateRoles(self,pMatrix, item,role,curRole): if curRole['setting'] == Allow: # We only want to append the role if it is Allowed roles = pMatrix['roles'] rolePerms = self.roleSettings['rolePermissions'] if not roles.has_key(role): roles[role] = [] # Here we get the permissions provided by each role for rolePerm in rolePerms: if rolePerm['role'] == role: mapping = {'permission': rolePerm['permission'], 'setting' : rolePerm['setting'].getName() } if mapping not in roles[role]: roles[role].append(mapping) def updatePermissionTree(self,pMatrix, item,prinPerms): """ method responsible for creating permission tree """ permissionTree = pMatrix['permissionTree'] key = item.get('uid') keys = [x.keys()[0] for x in permissionTree] # Each key is unique so we just get the list index to edit if key in keys: listIdx = keys.index(key) else: permissionTree.append({key:{}}) listIdx = -1 permissionTree[listIdx][key]['parentList'] = item.get('parentList') permissionTree[listIdx][key]['name'] = item.get('name') permissionTree[listIdx][key].setdefault('permissions',[]) if prinPerms not in permissionTree[listIdx][key]['permissions']: permissionTree[listIdx][key]['permissions'].append(prinPerms)
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/src/z3c/securitytool/matrixdetails.py
matrixdetails.py
from copy import deepcopy from pprint import pprint from zope.app import zapi from zope.app.apidoc.presentation import getViewInfoDictionary from zope.i18nmessageid import ZopeMessageFactory as _ from zope.interface import Interface, implements, providedBy from zope.publisher.browser import TestRequest, applySkin from zope.publisher.interfaces import IRequest from zope.publisher.interfaces.browser import IBrowserRequest from zope.securitypolicy.interfaces import Allow, Unset, Deny from z3c.securitytool.permissiondetails import * from z3c.securitytool.principaldetails import * from z3c.securitytool.globalfunctions import * from z3c.securitytool import interfaces class SecurityChecker(object): """ Workhorse of the security tool package""" implements(interfaces.ISecurityChecker) adapts(Interface) def __init__(self, context): self.context = context def getPermissionSettingsForAllViews(self,interfaces, skin=IBrowserRequest, selectedPermission=None): """ retrieves permission settings for all views""" request = TestRequest() self.selectedPermission = selectedPermission applySkin(request, skin) self.viewMatrix = {} self.viewPermMatrix = {} self.viewRoleMatrix = {} self.views = {} self.permissions = set() for iface in interfaces: for view_reg in getViews(iface, skin): viewInstance = getView(self.context, view_reg, skin) if viewInstance: self.populateMatrix(viewInstance,view_reg) self.aggregateMatrices() return [self.viewMatrix,self.views,self.permissions] def aggregateMatrices(self): """ This method is used to aggregate the two matricies together. There is a role matrix and a permission matrix. The reason for the role matrix is that we can have lower level assignments to override higher level assingments seperately from the direct assignments of permissions. We need to merge these together to have a complete matrix, When there is a conflict between permissions and role-permissions permissions will always win. """ # Populate the viewMatrix with the permissions gained only from the # assigned roles for item in self.viewRoleMatrix: if not self.viewMatrix.has_key(item): self.viewMatrix[item] = {} for viewSetting in self.viewRoleMatrix[item]: val = self.viewRoleMatrix[item][viewSetting] \ and 'Allow' or '--' self.viewMatrix[item].update({viewSetting:val}) # Populate the viewMatrix with the permissions which are # only directly assigned. for item in self.viewPermMatrix: if not self.viewMatrix.has_key(item): self.viewMatrix[item] = {} for viewSetting in self.viewPermMatrix[item]: self.viewMatrix[item].update( {viewSetting:self.viewPermMatrix[item][viewSetting]}) principals = zapi.principals() getPrin = principals.getPrincipal viewPrins = [getPrin(prin) for prin in self.viewMatrix] # Now we will inherit the permissions from groups assigned to each # principal and digest them accordingly, This section populates the # groupPermMatrix. The tmpMatrix is a collection the permissions # inherited only from groups. # Here we will just populate the temp matrix with the # with a copy of the contents of the viewMatrix. There # is probably a better way to do this but for now ;) # TODO update to a better method tmpMatrix = deepcopy(self.viewMatrix) mergePermissionsFromGroups(viewPrins,tmpMatrix) # Now we merge our last set of permissions into the main viewMatrix # for our display. for prinItem in tmpMatrix: for item in tmpMatrix[prinItem]: if not self.viewMatrix[prinItem].has_key(item): # We only want to add the permission if it does not exist # we do not want to overwrite the permission. self.viewMatrix[prinItem][item] = tmpMatrix[prinItem][item] def getReadPerm(self,view_reg): """ Helper method which returns read_perm and view name""" info = getViewInfoDictionary(view_reg) read_perm = info['read_perm'] if read_perm == None: read_perm = 'zope.Public' self.permissions.add(read_perm) name = info['name'] return name, read_perm def populateMatrix(self,viewInstance,view_reg): """ populates the matrix used for the securityMatrix view""" self.name, read_perm = self.getReadPerm(view_reg) # If we are not viewing the permission the user has selected if self.selectedPermission and self.selectedPermission != read_perm: return self.views[self.name] = read_perm allSettings, settings = getSettingsForMatrix(viewInstance) rolePermMap = allSettings.get('rolePermissions', ()) self.populateViewRoleMatrix(rolePermMap,settings,read_perm) prinPermissions = allSettings.get('principalPermissions',[]) self.populatePermissionMatrix(read_perm,prinPermissions) def populateViewRoleMatrix(self,rolePermMap,settings,read_perm): """ This method is responsible for populating the viewRoleMatrix of the security matrix this will be merged with the permissionMatrix after both are fully populated. """ for name, setting in settings: principalRoles = setting.get('principalRoles', []) for role in principalRoles: principal = role['principal'] if not self.viewRoleMatrix.has_key(principal): self.viewRoleMatrix[principal] = {} if read_perm == 'zope.Public': permSetting = (role,'Allow') elif role['setting'] == Deny: #If the role has a setting and it is Deny. try: # Here we see if we have added a security setting with # this role before, if it is now denied we remove it. del self.viewRoleMatrix[principal]\ [self.name][role['role']] continue except KeyError: pass else: # The role has a setting and is Allow so we add it to the # matrix. permSetting = principalRoleProvidesPermission( principalRoles, rolePermMap, principal, read_perm, role['role']) # The role is either Allow or zope.public so we add # it to the viewRoleMatrix. if permSetting[1]: self.viewRoleMatrix[principal].setdefault(self.name,{}) self.viewRoleMatrix[principal]\ [self.name].update({role['role']:permSetting[1]}) def populatePermissionMatrix(self,read_perm,principalPermissions): """ This method populates the principal permission section of the view matrix, it is half responsible for the 'Allow' and 'Deny' on the securityMatrix.html page. The other half belongs to the role permissions (viewRoleMatrix). """ matrix = self.viewPermMatrix principalPermissions.reverse() for prinPerm in principalPermissions: if prinPerm['permission'] != read_perm: #If it is not the read_perm it is uninteresting continue principal_id = prinPerm['principal'] setting = prinPerm['setting'].getName() if matrix.setdefault(principal_id,{self.name:setting}) == \ {self.name:setting}: #If the principal_id is not in the matrix add it continue else: # This is now the permission for this view # since we reversed the list we are travering # from the root level to our current level # so anything we find here we keep. matrix[principal_id][self.name] = setting
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/src/z3c/securitytool/securitytool.py
securitytool.py
====================== Detailed Documentation ====================== On the main page of the securityTool you will be able to select the desired skin from all the available skins on the system. On initial load of the securitytool you will only see permissions for IBrowserRequest and your current context. The interesting information is when you select the skins. A future release of this tool will offer a selection to view all information for all skins as well as each skin individually. You can also truncate the results by selecting the permission from the filter select box. When you click on the "Allow" or "Deny" security tool will explain where these permissions were specified whether by role, group, or in local context. When you click on a user-name all the permissions inherited from roles, groups or specifically assigned permissions will be displayed. >>> import zope >>> from zope.app import zapi >>> from pprint import pprint >>> from zope.interface import providedBy >>> from z3c.securitytool.securitytool import * >>> from z3c.securitytool.interfaces import ISecurityChecker >>> from z3c.securitytool.interfaces import IPrincipalDetails >>> from z3c.securitytool.interfaces import IPermissionDetails >>> from z3c.securitytool.browser import ISecurityToolSkin >>> root = getRootFolder() Several things are added to the database on the IDatabaseOpenedEvent when starting the demo or running the tests. These settings are used to test the functionality in the tests as well as populate a matrix for the demo. Lets make sure the items were added with demoSetup.py, We will assume that if Folder1 exists in the root folder then demoSetup.py was executed. >>> sorted(root.keys()) [u'Folder1'] To retrieve the permission settings for the folder we must first adapt the context to a SecurityChecker Object. >>> folder1 = ISecurityChecker(root['Folder1']) >>> print folder1.__class__.__name__ SecurityChecker Lets introspect the object. >>> pprint(dir(folder1)) ['__class__', '__component_adapts__', ... 'aggregateMatrices', 'context', 'getPermissionSettingsForAllViews', 'getReadPerm', 'populateMatrix', 'populatePermissionMatrix', 'populateViewRoleMatrix'] To get all the security settings for particular context level the getPermissionSettingsForAllViews is called with a tuple of interfaces. All the views registered for the interfaces passed will be inspected. Since nothing should be registered for only zope.interface.Interface we should receive an empty set, of permissions, roles and groups. >>> folder1.getPermissionSettingsForAllViews(zope.interface.Interface) [{}, {}, set([])] A realistic test would be to get all the interfaces provided by a specific context level like `Folder1`. Being a folder these are the interfaces as you might expect. >>> ifaces = tuple(providedBy(root['Folder1'])) >>> pprint(ifaces) (<InterfaceClass zope.site.interfaces.IFolder>, <InterfaceClass zope.container.interfaces.IContentContainer>, <InterfaceClass persistent.interfaces.IPersistent>, <InterfaceClass zope.location.interfaces.IContained>, <InterfaceClass zope.component.interfaces.IPossibleSite>) The next step to determine security levels is the getViews function. `getViews` gets all the registered views for this interface. This is refined later to the views that are only accessible in this context. >>> pprint(sorted([x for x in getViews(ifaces[0])])) [AdapterRegistration... ITraversable, u'acquire', ... AdapterRegistration... ITraversable, u'adapter', ... AdapterRegistration... ITraversable, u'attribute', ... AdapterRegistration... ITraversable, u'etc', ... AdapterRegistration... ITraversable, u'item', ... AdapterRegistration... ITraversable, u'lang', ... AdapterRegistration... ITraversable, u'resource', ... AdapterRegistration... ITraversable, u'skin', ... AdapterRegistration... ITraversable, u'vh', ... AdapterRegistration... ITraversable, u'view', ... Since this is a large result set returned we will only test enough pieces of the results to inform of the desired behavior and to make sure the results are sane. >>> permDetails = folder1.getPermissionSettingsForAllViews(ifaces, ... ISecurityToolSkin) By using the ISecurityToolSkin we can see the actual securityTool views. The securityTool views are only registered for the ISecurityToolSkin layer. >>> pprint(permDetails) [... 'zope.globalmgr': {u'<i>no name</i>': 'Allow', u'DELETE': 'Allow', u'OPTIONS': 'Allow', u'PUT': 'Allow', u'absolute_url': 'Allow', u'permissionDetails.html': 'Allow', u'principalDetails.html': 'Allow', u'securityMatrix.html': 'Allow'}, ...] As you can see below the `zope.anybody` has the 'Allow' permission for the four views listed below. The securitytool views are not listed here because they are neither specifically denied or allowed for this principal. >>> pprint(permDetails) ... [{'zope.anybody': {u'<i>no name</i>': 'Allow', u'DELETE': 'Allow', u'OPTIONS': 'Allow', u'PUT': 'Allow', u'absolute_url': 'Allow'}, ... Another section of the result set shows all valid views for this context and skin, along with the permission required for access to the view. >>> pprint(permDetails) [... {u'<i>no name</i>': 'zope.Public', u'DELETE': 'zope.Public', u'OPTIONS': 'zope.Public', u'PUT': 'zope.Public', u'absolute_url': 'zope.Public', u'permissionDetails.html': 'zope.ManageContent', u'principalDetails.html': 'zope.ManageContent', u'securityMatrix.html': 'zope.ManageContent'}, ...] All the principals in the system are in this data structure. Here we just print a subset of the structure, to make sure the data is sane. >>> pprint(sorted(permDetails[0].keys())) ['zope.anybody', 'zope.daniel', 'zope.globalmgr', 'zope.group1', 'zope.markus', 'zope.martin', 'zope.mgr', 'zope.randy', 'zope.sample_manager', 'zope.stephan'] This of course should be identical to the users on the system from zapi.getPrincipals() without (zope.anybody) >>> from zope.app import zapi >>> sysPrincipals = zapi.principals() >>> principals = [x.id for x in sysPrincipals.getPrincipals('')] >>> pprint(sorted(principals)) ['zope.daniel', 'zope.globalmgr', 'zope.group1', 'zope.group2', 'zope.markus', 'zope.martin', 'zope.mgr', 'zope.randy', 'zope.sample_manager', 'zope.stephan'] ======================================== Using securitytool to inspect principals ======================================== Lets see what the principalDetails look like for the principal Daniel and the context of 'Folder1'. First we retrieve the principalDetails for Folder1: >>> prinDetails = PrincipalDetails(root[u'Folder1']) Then we filter out the uninteresting information for the user being inspected. >>> matrix = prinDetails('zope.daniel') The principal details structure contains five interesting pieces of data. >>> pprint(sorted(matrix.keys())) ['groups', 'permissionTree', 'permissions', 'roleTree', 'roles'] Below we check to make sure the groups data structure from the user daniel is returned as expected. This is the data used to populate the groups section on the User Details page. >>> pprint(matrix['groups'].keys()) ['zope.randy'] The permission tree is used to display the levels of inheritance that were traversed to attain the permission displayed. The permission is stored as a list so the order is maintained. (yes I know there are better ways to accomplish this) >>> pprint(matrix['permissionTree'][0]) {u'Folder1_2': {'name': None, 'parentList': [u'Folder1', 'Root Folder'], 'permissions': [{'permission': 'concord.CreateArticle', 'principal': 'zope.daniel', 'setting': PermissionSetting: Allow}, {'permission': 'concord.ReadIssue', 'principal': 'zope.daniel', 'setting': PermissionSetting: Deny}, {'permission': 'concord.DeleteIssue', 'principal': 'zope.daniel', 'setting': PermissionSetting: Allow}]}} >>> pprint(matrix['permissionTree'][1]) {'Root Folder': {'name': 'Root Folder', 'parentList': ['Root Folder'], 'permissions': [{'permission': 'concord.DeleteArticle', 'principal': 'zope.daniel', 'setting': PermissionSetting: Deny}, {'permission': 'concord.CreateArticle', 'principal': 'zope.daniel', 'setting': PermissionSetting: Deny}, {'permission': 'concord.ReadIssue', 'principal': 'zope.daniel', 'setting': PermissionSetting: Allow}]}} The permissions section of the matrix displays the final say on whether or not the user has permissions at this context level. >>> pprint(matrix['permissions'], width=1) [{'permission': 'concord.CreateArticle', 'setting': PermissionSetting: Allow}, {'permission': 'concord.ReadIssue', 'setting': PermissionSetting: Deny}, {'permission': 'concord.DeleteIssue', 'setting': PermissionSetting: Allow}, {'permission': 'concord.DeleteArticle', 'setting': PermissionSetting: Deny}, {'permission': 'concord.CreateIssue', 'setting': PermissionSetting: Allow}, {'permission': 'concord.PublishIssue', 'setting': PermissionSetting: Allow}] The roleTree structure is used to display the roles attained at each level of traversal. The roleTree is stored as a list so to consistently test the data properly we will create a dictionary out of it and is similar in function to the permissionTree. >>> tmpDict = {} >>> keys = matrix['roleTree'] >>> for item in matrix['roleTree']: ... tmpDict.update(item) >>> pprint(tmpDict['Root Folder']) {'name': 'Root Folder', 'parentList': ['Root Folder'], 'roles': [{'principal': 'zope.daniel', 'role': 'zope.Writer', 'setting': PermissionSetting: Allow}]} >>> pprint(tmpDict['Folder1_2']) {'name': None, 'parentList': [u'Folder1', 'Root Folder'], 'roles': [{'principal': 'zope.daniel', 'role': 'zope.Writer', 'setting': PermissionSetting: Allow}]} >>> pprint(tmpDict['global settings']) {'name': None, 'parentList': ['global settings'], 'roles': [{'principal': 'zope.daniel', 'role': 'zope.Janitor', 'setting': PermissionSetting: Allow}]} The roles section of the matrix displays the final say on whether or not the user has the role assigned at this context level. >>> pprint(matrix['roles'], width=1) {'zope.Janitor': [{'permission': 'concord.ReadIssue', 'setting': 'Allow'}], 'zope.Writer': [{'permission': 'concord.DeleteArticle', 'setting': 'Allow'}, {'permission': 'concord.CreateArticle', 'setting': 'Allow'}, {'permission': 'concord.ReadIssue', 'setting': 'Allow'}]} Now lets see what the permission details returns >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> from z3c.securitytool.interfaces import IPermissionDetails >>> permAdapter = zapi.getMultiAdapter((root[u'Folder1'], ... ),IPermissionDetails) >>> prinPerms = permAdapter('zope.daniel', ... 'ReadIssue.html', ... ) >>> print permAdapter.skin <InterfaceClass zope.publisher.interfaces.browser.IBrowserRequest> >>> print permAdapter.read_perm zope.Public >>> print permAdapter.view_name ReadIssue.html >>> pprint(prinPerms) {'groups': {'zope.randy': {'groups': {'zope.group1': {'groups': {}, 'permissionTree': [], 'permissions': [], 'roleTree': [], 'roles': {}}, 'zope.group2': {'groups': {}, 'permissionTree': [], 'permissions': [], 'roleTree': [], 'roles': {}}}, 'permissionTree': [], 'permissions': [], 'roleTree': [], 'roles': {}}}, 'permissionTree': [], 'permissions': [], 'roleTree': [], 'roles': {}} Following are the helper functions used within the securitytool, These contain a set of common functionality that is used in many places. Lets see if the 'hasPermissionSetting' method returns True if there is a permission or role and False if there is not. >>> hasPermissionSetting({'permissions':'Allow'}) True We need to make some dummy objects to test the 'hasPermissionSetting' method >>> emptySettings = {'permissions': [], ... 'roles': {}, ... 'groups': {}} >>> fullSettings = {'permissions': 'Allow', ... 'roles': {}, ... 'groups': {}} We also need to make sure the recursive functionality works for this method >>> hasPermissionSetting({'permissions':{},'roles':{}, ... 'groups':{'group1':emptySettings, ... 'group2':fullSettings}}) True >>> from zope.securitypolicy.interfaces import Allow, Unset, Deny >>> prinPermMap = ({'principal':'daniel', ... 'permission':'takeOverTheWORLD', ... 'setting': Allow}) >>> rolePermMap = ({'role':'Janitor', ... 'permission':'takeOverTheWORLD', ... 'setting': Allow}) >>> prinRoleMap = ({'principal':'daniel', ... 'role':'Janitor', ... 'setting': Allow}) Lets test the method with our new dummy data >>> principalDirectlyProvidesPermission([prinPermMap],'daniel', ... 'takeOverTheWORLD') 'Allow' And we also need to test the roleProvidesPermission >>> roleProvidesPermission([rolePermMap], 'Janitor', 'takeOverTheWORLD') 'Allow' And we also need to test the roleProvidesPermission >>> principalRoleProvidesPermission([prinRoleMap], ... [rolePermMap], ... 'daniel', ... 'takeOverTheWORLD') ('Janitor', 'Allow') See janitors CAN take over the world!!!!! And of course the rendered name to display on the page template If we do not receive a name that means we are on the root level. >>> renderedName(None) u'Root Folder' >>> renderedName('Daniel') 'Daniel' >>> folder1.populatePermissionMatrix('takeOverTheWORLD',[prinPermMap]) TestBrowser Smoke Tests ----------------------- Lets make sure all the views work properly. Just a simple smoke test >>> from zope.testbrowser.testing import Browser >>> manager = Browser() >>> authHeader = 'Basic mgr:mgrpw' >>> manager.addHeader('Authorization', authHeader) >>> manager.handleErrors = False >>> server = 'http://localhost:8080/++skin++SecurityTool' >>> manager.open(server + '/@@securityMatrix.html') First we will check if the main page is available >>> manager.open(server + '/@@securityMatrix.html') >>> manager.open(server + '/Folder1/@@securityMatrix.html') >>> manager.open(server + '/Folder1/Folder2/Folder3/@@securityMatrix.html') Now lets send the filter variable so our test is complete >>> manager.open(server + '/@@securityMatrix.html?' ... 'FILTER=None&selectedSkin=ConcordTimes') And with the selected permission >>> manager.open(server + '/@@securityMatrix.html?' ... 'FILTER=None&selectedSkin=ConcordTimes&' ... 'selectedPermission=zope.Public') Here we send an invalid selectedPermisson ( just for coverage ) ;) >>> manager.open(server + '/@@securityMatrix.html?' ... 'FILTER=None&selectedSkin=ConcordTimes&' ... 'selectedPermission=zope.dummy') And with the None permission >>> manager.open(server + '/@@securityMatrix.html?' ... 'FILTER=None&selectedSkin=ConcordTimes&' ... 'selectedPermission=None') This is the principal detail page, you can get to by clicking on the principals name at the top of the form >>> manager.open(server + ... '/@@principalDetails.html?principal=zope.daniel') >>> manager.open(server + ... '/Folder1/Folder2/Folder3/' ... '@@principalDetails.html?principal=zope.daniel') >>> 'Permission settings' in manager.contents True And lets call the view without a principal >>> manager.open(server + '/@@principalDetails.html') Traceback (most recent call last): ... PrincipalLookupError: no principal specified Here is the view you will see if you click on the actual permission value in the matrix intersecting the view to the user on a public view. >>> manager.open(server + '/@@permissionDetails.html?' ... 'principal=zope.daniel&view=PUT') Ok lets send the command without the principal >>> manager.open(server + '/@@permissionDetails.html?view=PUT') Traceback (most recent call last): ... PrincipalLookupError: no user specified And now we will test it without the view name >>> manager.open(server + '/@@permissionDetails.html?' ... 'principal=zope.daniel') And now with a view name that does not exist >>> manager.open(server + '/@@permissionDetails.html?' ... 'principal=zope.daniel&view=garbage') Lets also test with a different context level >>> manager.open(server + ... '/Folder1/Folder2/Folder3/' ... '@@permissionDetails.html' ... '?principal=zope.daniel&view=ReadIssue.html')
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/src/z3c/securitytool/README.txt
README.txt
from zope.publisher.browser import BrowserView from zope.publisher.interfaces.browser import IBrowserRequest,IBrowserSkinType from zope.component import getGlobalSiteManager from zope.publisher.interfaces import IRequest import zope.interface import urllib from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile from zope.security.proxy import removeSecurityProxy from zope.interface import providedBy from zope.session.interfaces import ISession from zope.app import zapi from z3c.securitytool.securitytool import settingsForObject from z3c.securitytool.securitytool import MatrixDetails, PrincipalDetails, PermissionDetails from z3c.securitytool.interfaces import ISecurityChecker, IPrincipalDetails, IPermissionDetails SESSION_KEY = 'securitytool' class PrincipalMatrixView(BrowserView): """ This is the view used to populate the vum.html (securitytool main page) """ pageTemplateFile = "viewprincipalmatrix.pt" evenOddClasses = ('even','odd') evenodd = 0 def __call__(self): self.update() return self.render() def update(self): skin = self.handleSkinSelection() perm = self.handlePermissionSelection() ifaces = tuple(providedBy(self.context)) security_checker = ISecurityChecker(self.context) # Here we populate the viewMatrix self.viewMatrix, self.views, self.permissions = \ security_checker.getPermissionSettingsForAllViews(ifaces, skin, perm) self.path = '/'.join( self.request.get('REQUEST_URI','').split('/')[2:-1]) self.sortViews() def render(self): return ViewPageTemplateFile(self.pageTemplateFile)(self) def handleSkinSelection(self): """ This method handles the logic for the selectedSkin widget and session storage for the widget """ selectedPermission = None formSkin = self.request.form.get('selectedSkin','') sessionSkin= ISession(self.request)[SESSION_KEY].get('selectedSkin','') defaultSkin= self.skinTypes.items()[0][0] if formSkin: selectedSkin = formSkin elif sessionSkin: selectedSkin = sessionSkin else: selectedSkin = defaultSkin skin = zapi.getUtility(IBrowserSkinType,selectedSkin) ISession(self.request)[SESSION_KEY]['selectedSkin'] = selectedSkin return skin def handlePermissionSelection(self): """ This method handles the logic for the selectedPermission widget and session storage for the widget """ formPerm = self.request.form.get('selectedPermission','') sessionPerm= ISession(self.request)[SESSION_KEY].get( 'selectedPermission','') if formPerm: if formPerm == u'None': selectedPermission = '' else: selectedPermission = formPerm else: selectedPermission = sessionPerm or '' ISession(self.request)[SESSION_KEY]['selectedPermission'] = \ selectedPermission return selectedPermission def sortViews(self): """ self.views is a dict in the form of {view:perm} Here It would make more sense to group by permission rather than view """ self.viewList = {} sortedPerms = sorted([(v,k) for k,v in self.views.items()]) for item in sortedPerms: if self.viewList.has_key(item[0]): self.viewList[item[0]].append(item[1]) else: self.viewList[item[0]] = [item[1]] def cssclass(self): """ determiner what background color to use for lists """ if self.evenodd != 1: self.evenodd = 1 else: self.evenodd = 0 return self.evenOddClasses[self.evenodd] def getPermissionSetting(self, view, principal): try: return self.viewMatrix[principal][view] except KeyError: return '--' @property def skinTypes(self): """ gets all the available skins on the system """ skinNames = {} for name, util in zapi.getUtilitiesFor(IBrowserSkinType, self.context): skinNames[name] = False if (self.request.form.has_key('selectedSkin') and self.request.form['selectedSkin'] == name): skinNames[name] = True return skinNames @property def urlEncodedViewName(self): """ properly formats variables for use in urls """ urlNames = {} for key in self.views.keys(): urlNames[key] = urllib.quote(key) return urlNames def getPermissionList(self): """ returns sorted permission list""" return sorted(self.permissions) class PrincipalDetailsView(BrowserView): """ view class for ud.html (User Details)""" pageTemplateFile = "principalinfo.pt" def update(self): self.principal = self.request.get('principal','no principal specified') skin = getSkin(self.request) or IBrowserRequest principal_security = PrincipalDetails(self.context) self.principalPermissions = principal_security(self.principal, skin=skin) self.legend = (u"<span class='Deny'>Red Bold = Denied Permission" u"</span>,<span class='Allow'> Green Normal = " u"Allowed Permission </span>") self.preparePrincipalPermissions() def preparePrincipalPermissions(self): """ This method just organized the permission and role tree lists to display properly. """ permTree = self.principalPermissions['permissionTree'] for idx, item in enumerate(permTree): for uid,value in item.items(): if value.has_key('permissions'): self.principalPermissions['permissionTree']\ [idx][uid]['permissions'].sort() self.principalPermissions['permissionTree']\ [idx][uid]['parentList'].reverse() permTree = self.principalPermissions['roleTree'] for idx, item in enumerate(permTree): for uid,value in item.items(): if value.has_key('roles'): self.principalPermissions['roleTree']\ [idx][uid]['roles'].sort() self.principalPermissions['roleTree']\ [idx][uid]['parentList'].reverse() def render(self): return ViewPageTemplateFile(self.pageTemplateFile)(self) def __call__(self): self.update() return self.render() class PermissionDetailsView(BrowserView): """ view class for ud.html (User Details)""" pageTemplateFile = "permdetails.pt" def update(self): self.principal = self.request.get('principal','no user specified') self.view = self.request.get('view','no view specified') self.skin = getSkin(self.request) or IBrowserRequest permAdapter = zapi.getMultiAdapter((self.context, ),IPermissionDetails) self.principalPermissions = permAdapter(self.principal, self.view, self.skin) self.legend = (u"<span class='Deny'>Red Bold = Denied Permission" u"</span>,<span class='Allow'> Green Normal = " u"Allowed Permission </span>") self.preparePrincipalPermissions() def preparePrincipalPermissions(self): """ This method just organized the permission and role tree lists to display properly. """ permTree = self.principalPermissions['permissionTree'] for idx, item in enumerate(permTree): for uid,value in item.items(): if value.has_key('permissions'): self.principalPermissions['permissionTree']\ [idx][uid]['permissions'].sort() self.principalPermissions['permissionTree']\ [idx][uid]['parentList'].reverse() permTree = self.principalPermissions['roleTree'] for idx, item in enumerate(permTree): for uid,value in item.items(): if value.has_key('roles'): self.principalPermissions['roleTree']\ [idx][uid]['roles'].sort() self.principalPermissions['roleTree']\ [idx][uid]['parentList'].reverse() def render(self): return ViewPageTemplateFile(self.pageTemplateFile)(self) def __call__(self): self.update() return self.render() def getSkin(request): """Get the skin from the session.""" sessionData = ISession(request)[SESSION_KEY] selectedSkin = sessionData.get('selectedSkin', IBrowserRequest) return zapi.queryUtility(IBrowserSkinType, selectedSkin)
z3c.securitytool
/z3c.securitytool-0.5.1.tar.gz/z3c.securitytool-0.5.1/src/z3c/securitytool/browser/views.py
views.py
=========================================== Mercurial File Finder Plugin for Setuptools =========================================== This package provides a simple, command-based file finder plugin for setuptools. Once installed, one can create distributions using a pacakge that has been checked out with Mercurial. So let's create a workspace: >>> import tempfile >>> ws = tempfile.mkdtemp() Since the workspace is not a mercurial repository, the finder returns an empty list and leaves an error message in the logs: >>> from z3c.setuptools_mercurial import finder >>> finder.find_files(ws) abort: There is no Mercurial repository here (.hg not found)! (code 255) <BLANKLINE> [] Also, if the directory does not exist, we get an error message, but an empty result set: >>> finder.find_files('/foo') [Errno 2] No such file or directory: '/foo' [] Let's now create a new repository: >>> import os >>> repos = os.path.join(ws, 'test') >>> cmd('hg init ' + repos) The finder still fails with error code 1, since no file is yet added in the repository: >>> finder.find_files(repos) (code 1) [] Let's now add soem directories and files and the finder should be happy. >>> cmd('touch ' + os.path.join(repos, 'data.txt')) >>> cmd('hg add ' + os.path.join(repos, 'data.txt')) >>> cmd('mkdir ' + os.path.join(repos, 'dir1')) >>> cmd('touch ' + os.path.join(repos, 'dir1', 'data1.txt')) >>> cmd('hg add ' + os.path.join(repos, 'dir1', 'data1.txt')) >>> cmd('mkdir ' + os.path.join(repos, 'dir1', 'dir11')) >>> cmd('touch ' + os.path.join(repos, 'dir1', 'dir11', 'data1.txt')) >>> cmd('hg add ' + os.path.join(repos, 'dir1', 'dir11', 'data1.txt')) >>> finder.find_files(repos) ['data.txt', 'dir1/data1.txt', 'dir1/dir11/data1.txt'] Note that the result of the finder is always a list of relative locations based on the input directory. >>> finder.find_files(os.path.join(repos, 'dir1')) ['data1.txt', 'dir11/data1.txt'] Buildout 1.5 and higher ----------------------- When one uses zc.buildout 1.5 or higher, the system's environment is manipulated. In particular, the PYTHONPATH OS environment variable is rewritten. In that case it should be deleted: >>> import os >>> bo_orig_path = os.environ.pop('BUILDOUT_ORIGINAL_PYTHONPATH', None) >>> orig_path = os.environ.get('PYTHONPATH') >>> os.environ['PYTHONPATH'] = '/bogus' >>> finder.find_files(os.path.join(repos, 'dir1')) ['data1.txt', 'dir11/data1.txt'] >>> if bo_orig_path: ... os.environ['BUILDOUT_ORIGINAL_PYTHONPATH'] = bo_orig_path >>> if orig_path: ... os.environ['PYTHONPATH'] = orig_path
z3c.setuptools_mercurial
/z3c.setuptools_mercurial-1.1.1.tar.gz/z3c.setuptools_mercurial-1.1.1/src/z3c/setuptools_mercurial/README.txt
README.txt
import os from xml.dom import minidom, XML_NAMESPACE from zope.interface import implements from zope.i18n.simpletranslationdomain import SimpleTranslationDomain from zope.i18nmessageid import MessageFactory from z3c.sharedmimeinfo.basedir import iterDataPaths from z3c.sharedmimeinfo.interfaces import IMIMEType SMI_NAMESPACE = 'http://www.freedesktop.org/standards/shared-mime-info' msgfactory = MessageFactory('shared-mime-info') mimeTypesTranslationDomain = SimpleTranslationDomain('shared-mime-info') _mime_type_cache = {} class MIMEType(unicode): """Single MIME type representation""" implements(IMIMEType) __slots__ = ('_media', '_subtype', '_title') def __new__(cls, media, subtype=None): if subtype is None and '/' in media: media, subtype = media.split('/', 1) if (media, subtype) in _mime_type_cache: return _mime_type_cache[(media, subtype)] obj = super(MIMEType, cls).__new__(cls, media+'/'+subtype) obj._media = unicode(media) obj._subtype = unicode(subtype) obj._title = None for path in iterDataPaths(os.path.join('mime', media, subtype + '.xml')): doc = minidom.parse(path) if doc is None: continue for comment in doc.documentElement.getElementsByTagNameNS(SMI_NAMESPACE, 'comment'): data = ''.join([n.nodeValue for n in comment.childNodes]).strip() lang = comment.getAttributeNS(XML_NAMESPACE, 'lang') msgid = '%s/%s' % (media, subtype) if not lang: obj._title = msgfactory(msgid, default=data) else: mimeTypesTranslationDomain.messages[(lang, msgid)] = data _mime_type_cache[(media, subtype)] = obj return obj title = property(lambda self:self._title or unicode(self)) media = property(lambda self:self._media) subtype = property(lambda self:self._subtype) def __repr__(self): return '<%s %s>' % (self.__class__.__name__, str(self))
z3c.sharedmimeinfo
/z3c.sharedmimeinfo-0.1.0.tar.gz/z3c.sharedmimeinfo-0.1.0/src/z3c/sharedmimeinfo/mimetype.py
mimetype.py
================== z3c.sharedmimeinfo ================== This package provides an utility for guessing MIME type from file name and/or actual contents. It's based on freedesktop.org's shared-mime-info database. .. contents:: Shared MIME info database ------------------------- The `shared-mime-info <http://freedesktop.org/wiki/Software/shared-mime-info>`_ is a extensible database of common MIME types. It provides powerful MIME type detection mechanism as well as multi-lingual type descriptions. This package requires shared-mime-info to be installed and accessible. The easiest way to do that is to install it system-wide, for example installing the ``shared-mime-info`` package on Ubuntu. The specification_ also describes other ways to install and extend the database. .. _specification: http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-0.13.html#s2_layout Thread-safety ------------- Note, that this package is currently not thread-safe, because data are meant to be loaded only once, on module import. If there will be any problems because of that, it could be changed in future. MIME type guessing ------------------ The easiest way to use this package is to import the ``getType`` function from the root module:: >>> from z3c.sharedmimeinfo import getType This function tries to guess the MIME type as specified in shared-mime-info specification document and always returns some usable MIME type, using application/octet-stream or text/plain as fallback. It can detect MIME type by file name, its contents or both, so it accepts two arguments: filename (string) and/or file (file-like object). At least one of them should be given. As said above, it needs at least one argument, so you can't call it with no arguments:: >>> getType() Traceback (most recent call last): ... TypeError: Either filename or file should be provided or both of them Passing file name is done via the ``filename`` argument:: >>> print getType(filename='document.doc') application/msword Passing file contents is done via ``file`` argument, which accepts a file-like object. Let's use our testing helper function to open a sample file and try to guess a type for it:: >>> print getType(file=openSample('png')) image/png If the MIME type cannot be detected, either ``text/plain`` or ``application/octet-stream`` will be returned. The function will try to guess is it text or binary by checking the first 32 bytes:: >>> print getType(filename='somefile', file=openSample('text')) text/plain >>> print getType(filename='somefile', file=openSample('binary')) application/octet-stream MIME type objects ----------------- Objects returned by ``getType`` and other functions (see below) are actually an extended unicode string objects, providing additional info about the MIME type. They provide the IMIMEType interface:: >>> from zope.interface.verify import verifyObject >>> from z3c.sharedmimeinfo.interfaces import IMIMEType >>> mt = getType(filename='document.doc') >>> verifyObject(IMIMEType, mt) True As they are actually unicode objects, they can be compared like strings:: >>> mt == 'application/msword' True They also provides the ``media`` and ``subtype`` attributes:: >>> mt.media u'application' >>> mt.subtype u'msword' And finally, they provide the ``title`` attribute that is a translatable message:: >>> mt.title u'application/msword' >>> from zope.i18nmessageid.message import Message >>> isinstance(mt.title, Message) True Let's check the i18n features that comes with shared-mime-info and are supported by this package. As seen above, the MIME type title message ID is actually its <media>/<subtype>, but if we translate it, we'll get a human-friendly string:: >>> from zope.i18n import translate >>> translate(mt.title) u'Word document' >>> translate(mt.title, target_language='ru') u'\u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442 Word' >>> from z3c.sharedmimeinfo.mimetype import MIMEType We can also create IMIMEType objects by hand, using the MIMEType class:: >>> from z3c.sharedmimeinfo.mimetype import MIMEType We can create them specifying media and subtype as two arguments or as a single argument in the "media/subtype" form:: >>> MIMEType('text/plain') <MIMEType text/plain> >>> MIMEType('image', 'png') <MIMEType image/png> Note, that the MIMEType objects are cached, so if you you'll create another object for the same mime type, you'll get the same object:: >>> mt = MIMEType('text/plain') >>> mt2 = MIMEType('text/plain') >>> mt2 is mt True Advanced usage -------------- The ``getType`` function, described above is actually a method of the IMIMETypesUtility object. The IMIMETypesUtility is a core component for guessing MIME types. Let's import the utility directly and play with it:: >>> from z3c.sharedmimeinfo.utility import mimeTypesUtility >>> from z3c.sharedmimeinfo.interfaces import IMIMETypesUtility >>> verifyObject(IMIMETypesUtility, mimeTypesUtility) True It has three methods for getting mime type. Those three methods are ``getType`` (described above), ``getTypeByFileName``, ``getTypeByContents``. Detection by file name ~~~~~~~~~~~~~~~~~~~~~~ The ``getTypeByFileName`` method of the MIME types utility looks up the type by filename:: >>> mt = mimeTypesUtility.getTypeByFileName('example.doc') shared-mime-info database is really nice, it can even detect mime type for file names like ``Makefile``:: >>> print mimeTypesUtility.getTypeByFileName('Makefile') text/x-makefile Also, it know the difference in extension letter case. For example the ``.C`` should be detected as C++ file, when ``.c`` is plain C file:: >>> print mimeTypesUtility.getTypeByFileName('hello.C') text/x-c++src >>> print mimeTypesUtility.getTypeByFileName('main.c') text/x-csrc The method will return ``None`` if it fails determining type from file name:: >>> print mimeTypesUtility.getTypeByFileName('somefilename') None Detection by contents ~~~~~~~~~~~~~~~~~~~~~ The ``getTypeByContents`` method accepts a file-like object and two optional arguments: min_priority and max_priority that can be used to specify the range of "magic" rules to be used. By default, min_priority is 0 and max_priority is 100, so all rules will be in use. See shared-mime-info specification for details. We have some sample files that should be detected by contents:: >>> fdoc = openSample('doc') >>> print mimeTypesUtility.getTypeByContents(fdoc) application/msword >>> fhtml = openSample('html') >>> print mimeTypesUtility.getTypeByContents(fhtml) text/html >>> fpdf = openSample('pdf') >>> print mimeTypesUtility.getTypeByContents(fpdf) application/pdf >>> fpng = openSample('png') >>> print mimeTypesUtility.getTypeByContents(fpng) image/png If we pass the file without any known magic bytes, it will return ``None``:: >>> funknown = openSample('binary') >>> print mimeTypesUtility.getTypeByContents(funknown) None >>> del fdoc, fhtml, fpdf, fpng, funknown
z3c.sharedmimeinfo
/z3c.sharedmimeinfo-0.1.0.tar.gz/z3c.sharedmimeinfo-0.1.0/src/z3c/sharedmimeinfo/README.txt
README.txt
import re import os import fnmatch from zope.interface import implements from z3c.sharedmimeinfo.basedir import iterDataPaths from z3c.sharedmimeinfo.interfaces import IMIMETypesUtility from z3c.sharedmimeinfo.magic import MagicDB from z3c.sharedmimeinfo.mimetype import MIMEType findBinary = re.compile('[\0-\7]').search class MIMETypesUtility(object): """MIME type guessing utility""" implements(IMIMETypesUtility) _extensions = None _literals = None _globs = None _magicDB = None def __init__(self): self._extensions = {} self._literals = {} self._globs = [] self._magicDB = MagicDB() for path in iterDataPaths(os.path.join('mime', 'globs')): self._importGlobFile(path) self._globs.sort(key=lambda ob:len(ob[0]), reverse=True) for path in iterDataPaths(os.path.join('mime', 'magic')): self._magicDB.mergeFile(path) def _importGlobFile(self, path): for line in open(path, 'r'): if line.startswith('#'): continue line = line[:-1] type_name, pattern = line.split(':', 1) mtype = MIMEType(type_name) if pattern.startswith('*.'): rest = pattern[2:] if not ('*' in rest or '[' in rest or '?' in rest): self._extensions[rest] = mtype continue if '*' in pattern or '[' in pattern or '?' in pattern: self._globs.append((pattern, mtype)) else: self._literals[pattern] = mtype def getTypeByFileName(self, filename): """Return type guessed by filename""" if filename in self._literals: return self._literals[filename] lfilename = filename.lower() if lfilename in self._literals: return self._literals[lfilename] ext = filename while True: p = ext.find('.') if p < 0: break ext = ext[p + 1:] if ext in self._extensions: return self._extensions[ext] ext = lfilename while True: p = ext.find('.') if p < 0: break ext = ext[p + 1:] if ext in self._extensions: return self._extensions[ext] for (glob, mime_type) in self._globs: if fnmatch.fnmatch(filename, glob): return mime_type if fnmatch.fnmatch(lfilename, glob): return mime_type return None def getTypeByContents(self, file, min_priority=0, max_priority=100): """Return type guessed by data. Accepts file-like object""" return self._magicDB.match(file, min_priority, max_priority) def getType(self, filename=None, file=None): """Try to guess content type either by file name or contents or both""" if (filename is None) and (file is None): raise TypeError('Either filename or file should be provided or both of them') type = None if file: type = self.getTypeByContents(file, min_priority=80) if not type and filename: type = self.getTypeByFileName(filename) if not type and file: type = self.getTypeByContents(file, max_priority=80) if not type: type = MIMEType('application', 'octet-stream') if file: file.seek(0, 0) if not findBinary(file.read(32)): type = MIMEType('text', 'plain') return type mimeTypesUtility = MIMETypesUtility() getType = mimeTypesUtility.getType
z3c.sharedmimeinfo
/z3c.sharedmimeinfo-0.1.0.tar.gz/z3c.sharedmimeinfo-0.1.0/src/z3c/sharedmimeinfo/utility.py
utility.py
from z3c.sharedmimeinfo.mimetype import MIMEType class MagicDB(object): """A database of magic rules for guessing type based on file contents""" def __init__(self): self.types = {} self.maxlen = 0 def mergeFile(self, fname): """Merge specified shared-mime-info magic file into the database""" f = open(fname, 'r') line = f.readline() if line != 'MIME-Magic\0\n': raise Exception('Not a MIME magic file') while True: shead = f.readline() if not shead: break if shead[0] != '[' or shead[-2:] != ']\n': raise Exception('Malformed section heading') pri, tname = shead[1:-2].split(':') pri = int(pri) mtype = MIMEType(tname) ents = self.types.setdefault(pri, []) magictype = MagicType(mtype) c = f.read(1) f.seek(-1, 1) while c and c!='[': rule = magictype.getLine(f) if rule: rulelen = rule.getLength() if rulelen > self.maxlen: self.maxlen = rulelen c = f.read(1) f.seek(-1, 1) ents.append(magictype) if not c: break def match(self, file, min_priority=0, max_priority=100): """Try to guess type of specified file-like object""" file.seek(0, 0) buf = file.read(self.maxlen) for priority, types in sorted(self.types.items(), key=lambda ob:ob[0], reverse=True): if priority > max_priority: continue if priority < min_priority: break for type in types: m = type.match(buf) if m: return m return None class MagicType(object): """A representation of the mime type, determined by magic. It can tell if some data matches its mime type or not. """ def __init__(self, mtype): self.mtype = mtype self.top_rules = [] self.last_rule = None def getLine(self, f): """Process a portion of the magic database to build a rule tree for this type""" nrule = MagicRule(f) if nrule.nest and self.last_rule: self.last_rule.appendRule(nrule) else: self.top_rules.append(nrule) self.last_rule = nrule return nrule def match(self, buffer): """Try to match given contents using rules defined for this type""" for rule in self.top_rules: if rule.match(buffer): return self.mtype class MagicRule(object): """A representation of a magic rule node as defined in the shared-mime-info""" def __init__(self, f): self.next = None self.prev = None indent = '' while True: c = f.read(1) if c == '>': break indent += c if not indent: self.nest = 0 else: self.nest = int(indent) start = '' while True: c = f.read(1) if c == '=': break start += c self.start = int(start) hb = f.read(1) lb = f.read(1) self.lenvalue = ord(lb) + (ord(hb) << 8) self.value = f.read(self.lenvalue) c = f.read(1) if c == '&': self.mask = f.read(self.lenvalue) c = f.read(1) else: self.mask = None if c == '~': w = '' while c != '+' and c!='\n': c = f.read(1) if c == '+' or c == '\n': break w += c self.word = int(w) else: self.word = 1 if c == '+': r = '' while c != '\n': c = f.read(1) if c == '\n': break r += c self.range = int(r) else: self.range = 1 if c != '\n': raise Exception('Malformed MIME magic line') def getLength(self): """Return needed amout of bytes that is required for this rule""" return self.start + self.lenvalue + self.range def appendRule(self, rule): """Add a (sub)rule""" if self.nest < rule.nest: self.next = rule rule.prev = self elif self.prev: self.prev.appendRule(rule) def match(self, buffer): """Try to match data with this rule and its subrules""" if self.matchFirst(buffer): if self.next: return self.next.match(buffer) return True def matchFirst(self, buffer): """Try to match data using this rule definition""" l = len(buffer) for o in xrange(self.range): s = self.start + o e = s + self.lenvalue if l < e: return False if self.mask: test = '' for i in xrange(self.lenvalue): c = ord(buffer[s + i]) & ord(self.mask[i]) test += chr(c) else: test = buffer[s:e] if test == self.value: return True
z3c.sharedmimeinfo
/z3c.sharedmimeinfo-0.1.0.tar.gz/z3c.sharedmimeinfo-0.1.0/src/z3c/sharedmimeinfo/magic.py
magic.py
============================= A base Skin based on Pagelets ============================= The ``z3c.skin.pagelet`` package provides a skin for the ``z3c.pagelet`` package. Note, the pagelet skin is only registered in the test layer. You can use this skin as a base for your own skins or just use it as a sample for the ``z3c.pagelet`` package. Open a browser and access the ``Pagelet`` skin: >>> from z3c.etestbrowser.testing import ExtendedTestBrowser >>> user = ExtendedTestBrowser() >>> user.addHeader('Accept-Language', 'en') >>> user.open('http://localhost/++skin++Pagelet') Let's see how such a skin looks like: >>> print user.contents <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <base href="http://localhost/++skin++Pagelet/@@index.html" /> <BLANKLINE> <BLANKLINE> <title>Pagelet skin</title> <BLANKLINE> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="pragma" content="no-cache" /> <link type="text/css" rel="stylesheet" href="http://localhost/++skin++Pagelet/@@/pagelet.css" media="all" /> <BLANKLINE> <script type="text/javascript"> var contextURL='http://localhost/++skin++Pagelet/';</script> <BLANKLINE> <link rel="icon" type="image/png" href="http://localhost/++skin++Pagelet/@@/favicon.png" /> </head> <body> <div id="layoutWrapper"> <div id="layoutContainer"> <div id="headerContainer"> <div id="breadcrumbs" class="sortable"> <BLANKLINE> </div> <div id="user"> User: Manager </div> <img id="logo" src="http://localhost/++skin++Pagelet/@@/img/logo.gif" width="53" height="51" alt="logo" /> </div> <div id="menuContainer"></div> <div id="naviContainer" class="sortable"> <BLANKLINE> <BLANKLINE> </div> <div id="contentContainer"> <div id="tabContainer"></div> <div id="content"> <div>This is the default index view</div> <BLANKLINE> </div> </div> </div> </div> </body> </html> <BLANKLINE>
z3c.skin.pagelet
/z3c.skin.pagelet-1.0.2.tar.gz/z3c.skin.pagelet-1.0.2/src/z3c/skin/pagelet/README.txt
README.txt
SOAP Support ============ This SOAP implementation allows you provide SOAP views for objects. The SOAP layer is based on `ZSI <http://pywebsvcs.sourceforge.net/>`__. The package requires ZSI 2.0 or better. SOAP support is implemented in a way very similar to the standard Zope XML-RPC support. To call methods via SOAP, you need to create and register SOAP views. Version >= 0.5.4 are intended to be used with Zope 2.13 and higher. Older versions (0.5.3 and under) should work correctly with Zope < 2.13 This package is largely inspired from Zope 3 SOAP (http://svn.zope.org/soap).
z3c.soap
/z3c.soap-0.5.5.zip/z3c.soap-0.5.5/README.rst
README.rst
import sys import types from string import replace from zExceptions import Unauthorized from zope.publisher.xmlrpc import premarshal from ZSI import TC, ParsedSoap from ZSI import SoapWriter, Fault from zope.component import queryUtility from z3c.soap.interfaces import IZSIRequestType, IZSIResponseType import ZSI import logging import traceback from zope.interface import implements from z3c.soap.interfaces import ISOAPResponse from xml.dom.minidom import Node class SOAPParser(object): def __init__(self, data): self.parsed = ParsedSoap(data) self.root = self.parsed.body_root self.target = self.root.localName self.method = replace(self.target, '.', '/') def parse(self): data = ZSI._child_elements(self.root) if len(data) == 0: params = () else: resolver = queryUtility(IZSIRequestType, name=self.target) if resolver is None: targetWithNamespace = "%s/%s" % (self.root.namespaceURI, self.target) resolver = queryUtility(IZSIRequestType, name=targetWithNamespace) if resolver and hasattr(resolver, 'typecode'): tc = resolver.typecode params = [resolver.typecode.parse(self.root, self.parsed)] resolver = queryUtility(IZSIResponseType, name=self.target) if resolver is None: targetWithNamespace = "%s/%s" % (self.root.namespaceURI, self.target) resolver = queryUtility(IZSIResponseType, name=targetWithNamespace) params.append(resolver) else: tc = TC.Any() params = [tc.parse(e, self.parsed) for e in data] params = tuple(params) return params def parse_input(data): parser = SOAPParser(data) return parser.parse() class SOAPResponse: """Customized Response that handles SOAP-specific details. We override setBody to marhsall Python objects into SOAP. We also override exception to convert errors to SOAP faults. If these methods stop getting called, make sure that ZPublisher is using the soap.Response object created above and not the original HTTPResponse object from which it was cloned. It's probably possible to improve the 'exception' method quite a bit. The current implementation, however, should suffice for now. """ implements(ISOAPResponse) _contentType = 'text/xml' _soap11 = None _soap12 = None # Because we can't predict what kind of thing we're customizing, # we have to use delegation, rather than inheritence to do the # customization. def __init__(self, real): self.__dict__['_real']=real def __getattr__(self, name): return getattr(self._real, name) def __setattr__(self, name, v): return setattr(self._real, name, v) def __delattr__(self, name): return delattr(self._real, name) def setBody(self, body, title='', is_error=0, bogus_str_search=None): if isinstance(body, Fault): # Convert Fault object to SOAP response. body = body.AsSOAP() else: # Marshall our body as an SOAP response. Strings will be sent # strings, integers as integers, etc. We do *not* convert # everything to a string first. try: target = self._method body = premarshal(body) result = body if hasattr(result, 'typecode'): tc = result.typecode else: tc = TC.Any(aslist=1, pname=target + 'Response') result = [result] sw = SoapWriter(nsdict={}, header=True, outputclass=None, encodingStyle=None) body = str(sw.serialize(result, tc)) Node.unlink(sw.dom.node) Node.unlink(sw.body.node) del sw.dom.node del sw.body.node del sw.dom del sw.body except: self.exception() return # Set our body to the message, and fix our MIME type. self._real.setBody(body) self._setHeader() return self def exception(self, fatal=0, info=None, absuri_match=None, tag_search=None): if isinstance(info, tuple) and len(info)==3: t, v, tb = info else: t, v, tb = sys.exc_info() content = "".join(traceback.format_tb(tb)) logger = logging.getLogger('Zope') logger.info('SOAPException: %s' % content) f=v if t == 'Unauthorized' or t == Unauthorized or ( isinstance(t, types.ClassType) and issubclass(t, Unauthorized)): self._real.setStatus(401) f = ZSI.Fault(Fault.Server, "Not authorized") elif not isinstance(v, Fault): self._real.setStatus(500) f = ZSI.FaultFromException(u"%s : %s" % (v, content), 0) self.setBody(f) return tb def _setHeader(self): self.setHeader('content-length', len(self._real.body)) self._real.setHeader('content-type', self._contentType) if self._soap11: self._real.setHeader('content-type', 'text/xml') if self._soap12: self._real.setHeader('content-type', 'application/soap+xml') response=SOAPResponse
z3c.soap
/z3c.soap-0.5.5.zip/z3c.soap-0.5.5/z3c/soap/soap.py
soap.py
import sys from zExceptions import Redirect, Unauthorized from ZPublisher.mapply import mapply from ZPublisher.Publish import (call_object, missing_name, dont_publish_class, get_module_info, Retry) from ZPublisher.pubevents import PubStart, PubSuccess, PubFailure, \ PubBeforeCommit, PubAfterTraversal, PubBeforeAbort from zope.publisher.browser import setDefaultSkin from zope.publisher.interfaces import ISkinnable from zope.security.management import newInteraction, endInteraction from zope.event import notify from z3c.soap.interfaces import ISOAPRequest from z3c.soap.soap import SOAPResponse def publish(request, module_name, after_list, debug=0, # Optimize: call_object=call_object, missing_name=missing_name, dont_publish_class=dont_publish_class, mapply=mapply, ): (bobo_before, bobo_after, object, realm, debug_mode, err_hook, validated_hook, transactions_manager)= get_module_info(module_name) parents=None response=None try: notify(PubStart(request)) # TODO pass request here once BaseRequest implements IParticipation newInteraction() request.processInputs() request_get=request.get response=request.response # First check for "cancel" redirect: if request_get('SUBMIT','').strip().lower()=='cancel': cancel=request_get('CANCEL_ACTION','') if cancel: raise Redirect, cancel after_list[0]=bobo_after if debug_mode: response.debug_mode=debug_mode if realm and not request.get('REMOTE_USER',None): response.realm=realm if bobo_before is not None: bobo_before() # Get the path list. # According to RFC1738 a trailing space in the path is valid. path=request_get('PATH_INFO') request['PARENTS']=parents=[object] if transactions_manager: transactions_manager.begin() object=request.traverse(path, validated_hook=validated_hook) notify(PubAfterTraversal(request)) if transactions_manager: transactions_manager.recordMetaData(object, request) result=mapply(object, request.args, request, call_object,1, missing_name, dont_publish_class, request, bind=1) if result is not response: response.setBody(result) notify(PubBeforeCommit(request)) if transactions_manager: transactions_manager.commit() endInteraction() notify(PubSuccess(request)) return response except: # save in order to give 'PubFailure' the original exception info exc_info = sys.exc_info() # DM: provide nicer error message for FTP sm = None if response is not None: sm = getattr(response, "setMessage", None) if sm is not None: from asyncore import compact_traceback cl,val= sys.exc_info()[:2] sm('%s: %s %s' % ( getattr(cl,'__name__',cl), val, debug_mode and compact_traceback()[-1] or '')) # debug is just used by tests (has nothing to do with debug_mode!) # XXX begin monkeypatch if ISOAPRequest.providedBy(request): if transactions_manager: transactions_manager.abort() endInteraction() if response is None: response = SOAPResponse(request.response) if isinstance(exc_info[1], Unauthorized): response._unauthorized() else: response.exception() return response # XXX end monkeypatch if not debug and err_hook is not None: retry = False if parents: parents=parents[0] try: try: return err_hook(parents, request, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], ) except Retry: if not request.supports_retry(): return err_hook(parents, request, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], ) retry = True finally: # Note: 'abort's can fail. Nevertheless, we want end request handling try: try: notify(PubBeforeAbort(request, exc_info, retry)) finally: if transactions_manager: transactions_manager.abort() finally: endInteraction() notify(PubFailure(request, exc_info, retry)) # Only reachable if Retry is raised and request supports retry. newrequest=request.retry() request.close() # Free resources held by the request. # Set the default layer/skin on the newly generated request if ISkinnable.providedBy(newrequest): setDefaultSkin(newrequest) try: return publish(newrequest, module_name, after_list, debug) finally: newrequest.close() else: # Note: 'abort's can fail. Nevertheless, we want end request handling try: try: notify(PubBeforeAbort(request, exc_info, False)) finally: if transactions_manager: transactions_manager.abort() finally: endInteraction() notify(PubFailure(request, exc_info, False)) raise import ZPublisher.Publish ZPublisher.Publish.publish = publish import logging logger = logging.getLogger('Zope') logger.info("z3c.soap: monkeypatched ZPublisher.Publish.publish") from Products.PluggableAuthService.plugins.CookieAuthHelper import CookieAuthHelper from urllib import quote def unauthorized(self): req = self.REQUEST resp = req['RESPONSE'] # If we set the auth cookie before, delete it now. if resp.cookies.has_key(self.cookie_name): del resp.cookies[self.cookie_name] # Redirect if desired. url = self.getLoginURL() # XXX begin monkeypatch if ISOAPRequest.providedBy(req): #no need to redirect if it's a soap request return 0 # XXX end monkeypatch if url is not None: came_from = req.get('came_from', None) if came_from is None: came_from = req.get('ACTUAL_URL', '') query = req.get('QUERY_STRING') if query: if not query.startswith('?'): query = '?' + query came_from = came_from + query else: # If came_from contains a value it means the user # must be coming through here a second time # Reasons could be typos when providing credentials # or a redirect loop (see below) req_url = req.get('ACTUAL_URL', '') if req_url and req_url == url: # Oops... The login_form cannot be reached by the user - # it might be protected itself due to misconfiguration - # the only sane thing to do is to give up because we are # in an endless redirect loop. return 0 if '?' in url: sep = '&' else: sep = '?' url = '%s%scame_from=%s' % (url, sep, quote(came_from)) resp.redirect(url, lock=1) resp.setHeader('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT') resp.setHeader('Cache-Control', 'no-cache') return 1 # Could not challenge. return 0 CookieAuthHelper.unauthorized = unauthorized logger.info("z3c.soap: monkeypatched CookieAuthHelper.unauthorized")
z3c.soap
/z3c.soap-0.5.5.zip/z3c.soap-0.5.5/z3c/soap/patch.py
patch.py
import ZSI from zope.app.publication.interfaces import ISOAPRequestFactory from zope.publisher.http import HTTPRequest, HTTPResponse from z3c.soap.interfaces import ISOAPRequest, ISOAPResponse from ZSI import TC, ParsedSoap, ParseException from ZSI import SoapWriter, Fault from zope.security.proxy import isinstance from zope.security.interfaces import IUnauthorized from zope.publisher.xmlrpc import premarshal from zope.interface import implements from StringIO import StringIO import traceback class SOAPRequestFactory(object): """ This class implements a SOAP request factory that is registered for zope.app.publication.interfaces.ISOAPRequestFactory as a utility. This lets the hook in the z3 publisher delegate to us for SOAP requests. """ implements(ISOAPRequestFactory) def __call__(self, input, env): return SOAPRequest(input, env) factory = SOAPRequestFactory() class SOAPRequest(HTTPRequest): implements(ISOAPRequest) ## __slots__ = ( ## '_target', ## '_root', ## ) _target = '' _root = None _args = () def _getPositionalArguments(self): return self._args def _createResponse(self): """Create a specific SOAP response object.""" return SOAPResponse() def _setError(self, error): self._getResponse()._error = error def processInputs(self): try: input = self._body_instream.read() parsed = ParsedSoap(input) # We do not currently handle actors or mustUnderstand elements. actors = parsed.WhatActorsArePresent() if len(actors): self._setError(ZSI.FaultFromActor(actors[0])) return must = parsed.WhatMustIUnderstand() if len(must): uri, localname = must[0] self._setError(ZSI.FaultFromNotUnderstood(uri, localname)) return except ParseException, e: self._setError(ZSI.FaultFromZSIException(e)) return except Exception, e: self._setError(ZSI.FaultFromException(e, 1)) return # Parse the SOAP input. try: docstyle = 0 # cant really tell... resolver = None # XXX root = self._root = parsed.body_root target = self._target = root.localName self.setPathSuffix(target.split('.')) if docstyle: self._args = (root) else: data = ZSI._child_elements(root) if len(data) == 0: self._args = () else: try: try: type = data[0].localName tc = getattr(resolver, type).typecode except Exception, e: tc = TC.Any() self._args = [tc.parse(e, parsed) for e in data] self._args = tuple(self._args) except ZSI.EvaluateException, e: self._error = ZSI.FaultFromZSIException(e) return except Exception, e: self._setError(ZSI.FaultFromException(e, 0)) class SOAPResponse(HTTPResponse): implements(ISOAPResponse) _error = None def setBody(self, body): """Sets the body of the response""" # A SOAP view can return a Fault directly to indicate an error. if isinstance(body, Fault): self._error = body if not self._error: try: target = self._request._target body = premarshal(body) output = StringIO() result = body if hasattr(result, 'typecode'): tc = result.typecode else: tc = TC.Any(aslist=1, pname=target + 'Response') result = [result] SoapWriter(output).serialize(result, tc) output.seek(0) if not self._status_set: self.setStatus(200) self.setHeader('content-type', 'text/xml') self._body = output.read() self._updateContentLength() return except Exception, e: self._error = ZSI.FaultFromException(e, 0) # Error occurred in input, during parsing or during processing. self.setStatus(500) self.setHeader('content-type', 'text/xml') self.setResult(self._error.AsSOAP()) #self._updateContentLength() def handleException(self, exc_info): """Handle exceptions that occur during processing.""" type, value = exc_info[:2] content = "".join(traceback.format_tb(exc_info[-1])) if IUnauthorized.providedBy(value): self.setStatus(401) self.setBody("") #XXXself._body = "" #self._updateContentLength() return if not isinstance(value, Fault): value = ZSI.FaultFromException(u"%s : %s" % (value, content), 0) self.setStatus(500) self.setBody(value)
z3c.soap
/z3c.soap-0.5.5.zip/z3c.soap-0.5.5/z3c/soap/publisher.py
publisher.py
SOAP Support ============ This SOAP implementation allows you provide SOAP views for objects. The SOAP layer is based on `ZSI <http://pywebsvcs.sourceforge.net/>`__. The package requires ZSI 2.0 or better. SOAP support is implemented in a way very similar to the standard Zope XML-RPC support. To call methods via SOAP, you need to create and register SOAP views. Version >= 0.5.4 are intended to be used with Zope 2.13 and higher. Older versions (0.5.3 and under) should work correctly with Zope < 2.13 This package is largely inspired from Zope 3 SOAP (http://svn.zope.org/soap). Let's write a simple SOAP view that echoes various types of input: >>> import ZSI >>> from Products.Five import BrowserView >>> class EchoView(BrowserView): ... ... def echoString(self, value): ... return value ... ... def echoStringArray(self, value): ... return value ... ... def echoInteger(self, value): ... return value ... ... def echoIntegerArray(self, value): ... return value ... ... def echoFloat(self, value): ... return value ... ... def echoFloatArray(self, value): ... return value ... ... def echoStruct(self, value): ... return value ... ... def echoStructArray(self, value): ... return value ... ... def echoVoid(self): ... return ... ... def echoBase64(self, value): ... import base64 ... return base64.encodestring(value) ... ... def echoDate(self, value): ... import time ... return time.gmtime(time.mktime(value)) ... ... def echoDecimal(self, value): ... return value ... ... def echoBoolean(self, value): ... return value ... ... def ValidateEmailRequest(self, requestData, response): ... mail = requestData._Email ... response._Status = '%s is OK' % mail ... return response ... ... def testFault(self): ... raise ZSI.Fault(ZSI.Fault.Client, "Testing the zsi fault") Now we'll register it as a SOAP view. For now we'll just register the view for folder objects and call it on the root folder: >>> from zope.configuration import xmlconfig >>> ignored = xmlconfig.string(""" ... <configure ... xmlns="http://namespaces.zope.org/zope" ... xmlns:browser="http://namespaces.zope.org/browser" ... xmlns:soap="http://namespaces.zope.org/soap" ... > ... ... <!-- We only need to do this include in this example, ... Normally the include has already been done for us. --> ... ... <include package="z3c.soap" file="meta.zcml" /> ... <include package="Products.Five" file="meta.zcml" /> ... <include package="z3c.soap"/> ... ... <soap:view ... for="OFS.interfaces.IFolder" ... methods="echoString echoStringArray echoInteger echoIntegerArray ... echoFloat echoFloatArray echoStruct echoVoid echoBase64 ... echoDate echoDecimal echoBoolean ValidateEmailRequest ... testFault" ... class="z3c.soap.README.EchoView" ... permission="zope2.SOAPAccess" ... /> ... ... <utility ... factory="z3c.soap.tests.mailvalidation.validateEmailIn" ... name="ValidateEmailRequest" ... provides="z3c.soap.interfaces.IZSIRequestType"/> ... ... <utility ... factory="z3c.soap.tests.mailvalidation.validateEmailOut" ... name="ValidateEmailRequest" ... provides="z3c.soap.interfaces.IZSIResponseType"/> ... ... ... </configure> ... """) And call our SOAP method: >>> from Testing.ZopeTestCase import user_name, user_password >>> self.setRoles(['Manager']) >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoString xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:string">hello</arg1> ... </m:echoString> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password), handle_errors=True) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml <BLANKLINE> ...hello... Note that we get an unauthorized error if we don't supply authentication credentials, because we protected the view with the ManageContent permission when we registered it: >>> self.logout() >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoString xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:string">hello</arg1> ... </m:echoString> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """) HTTP/1.0 401 Unauthorized Content-Length: ... Content-Type: text/xml Www-Authenticate: basic realm="Zope2" <BLANKLINE> <SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SOAP-ENV:Header></SOAP-ENV:Header><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Server</faultcode><faultstring>Not authorized</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope> Parameters ---------- SOAP views can take any parameters that ZSI can understand. The following demonstrate the use of primitive SOAP-defined types: >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoString xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:string">hello</arg1> ... </m:echoString> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml... <BLANKLINE> ...hello... >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoStringArray xmlns:m="http://www.soapware.org/"> ... <param SOAP-ENC:arrayType="xsd:ur-type[4]" xsi:type="SOAP-ENC:Array"> ... <item xsi:type="xsd:string">one</item> ... <item xsi:type="xsd:string">two</item> ... <item xsi:type="xsd:string">three</item> ... <item xsi:type="xsd:string">four</item> ... </param> ... </m:echoStringArray> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml... <BLANKLINE> ...one...two...three...four... >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoInteger xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:int">42</arg1> ... </m:echoInteger> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml... <BLANKLINE> ...42... >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoIntegerArray xmlns:m="http://www.soapware.org/"> ... <param SOAP-ENC:arrayType="xsd:ur-type[4]" xsi:type="SOAP-ENC:Array"> ... <item xsi:type="xsd:int">1</item> ... <item xsi:type="xsd:int">2</item> ... <item xsi:type="xsd:int">3</item> ... <item xsi:type="xsd:int">4</item> ... </param> ... </m:echoIntegerArray> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml... <BLANKLINE> ...1...2...3...4... Note that floats are returned as xsd:decimal values: >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoFloat xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:float">42.2</arg1> ... </m:echoFloat> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml <BLANKLINE> ...xsi:type="xsd:float">42.200000</... Even if they're in float arrays: >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoFloatArray xmlns:m="http://www.soapware.org/"> ... <param SOAP-ENC:arrayType="xsd:ur-type[4]" xsi:type="SOAP-ENC:Array"> ... <item xsi:type="xsd:float">1.1</item> ... <item xsi:type="xsd:float">2.2</item> ... <item xsi:type="xsd:float">3.3</item> ... <item xsi:type="xsd:float">4.4</item> ... </param> ... </m:echoFloatArray> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml <BLANKLINE> ...xsi:type="xsd:float">1.100000</... ...xsi:type="xsd:float">2.200000</... ...xsi:type="xsd:float">3.300000</... ...xsi:type="xsd:float">4.400000</... >>> result = http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoStruct xmlns:m="http://www.soapware.org/"> ... <param> ... <first xsi:type="xsd:string">first 1</first> ... <last xsi:type="xsd:string">last 1</last> ... </param> ... </m:echoStruct> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) >>> result = str(result) >>> assert(result.find('first 1') > -1) >>> assert(result.find('last 1') > -1) Note that arrays of structs (at least per the interop suite) do not seem to work: >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ... xmlns:so="http://soapinterop.org/"> ... <SOAP-ENV:Body> ... <m:echoStructArray xmlns:m="http://www.soapware.org/xsd"> ... <inputArray SOAP-ENC:arrayType="so:SOAPStruct[2]" ... xsi:type="SOAP-ENC:Array"> ... <item xsi:type="so:SOAPStruct"> ... <varString xsi:type="xsd:string">str 1</varString> ... <varInt xsi:type="xsd:int">1</varInt> ... </item> ... <item xsi:type="so:SOAPStruct"> ... <varString xsi:type="xsd:string">str 2</varString> ... <varInt xsi:type="xsd:int">2</varInt> ... </item> ... </inputArray> ... </m:echoStructArray> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password), handle_errors=True) HTTP/1.0 500 Internal Server Error Content-Length: ... Content-Type: text/xml <BLANKLINE> <SOAP-ENV:Envelope ... ... >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoVoid xmlns:m="http://www.soapware.org/"> ... </m:echoVoid> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml <BLANKLINE> ...echoVoidResponse... >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoBase64 xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="SOAP-ENC:base64">AAECAwQF</arg1> ... </m:echoBase64> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml... <BLANKLINE> ...AAECAwQF... Datetimes appear to work: >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoDate xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:dateTime">1970-11-27T11:34:56.000Z</arg1> ... </m:echoDate> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml... <BLANKLINE> ...1970-11-27T10:34:56... >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoDecimal xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:float">123456789.0123</arg1> ... </m:echoDecimal> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml... <BLANKLINE> ...123456789.0123... >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 102 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoBoolean xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:boolean">1</arg1> ... </m:echoBoolean> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml... <BLANKLINE> ...1... Faults ------ If you need to raise an error, you can either raise an exception as usual or (if you need more control over fault info) return a `ZSI.Fault` object directly. Either case causes a fault response to be returned: >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 104 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:echoInteger xmlns:m="http://www.soapware.org/"> ... <arg1 xsi:type="xsd:int">hello</arg1> ... </m:echoInteger> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password), handle_errors=True) HTTP/1.0 500 Internal Server Error Content-Length: ... Content-Type: text/xml <BLANKLINE> <SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SOAP-ENV:Header></SOAP-ENV:Header><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Server</faultcode><faultstring>Processing Failure</faultstring><detail><ZSI:FaultDetail><ZSI:string> ... Here is a ZSI Fault response: >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 104 ... Content-Type: text/xml ... SOAPAction: / ... ... <?xml version="1.0"?> ... <SOAP-ENV:Envelope ... SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Body> ... <m:testFault xmlns:m="http://www.soapware.org/"> ... </m:testFault> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope> ... """ % (user_name, user_password), handle_errors=True) HTTP/1.0 200 OK Content-Length: 488 Content-Type: text/xml <BLANKLINE> <SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><SOAP-ENV:Header></SOAP-ENV:Header><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Client</faultcode><faultstring>Testing the zsi fault</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope> Complex Types ------------- For ZSI to successfully marshal complex values (instances of classes), you must define a typecode that describes the object (see the ZSI docs for details on defining typecodes). Once the typecode is defined, it must be accessible through an instance via the attribute name 'typecode' to be automatically marshalled. >>> print http(r""" ... POST /test_folder_1_ HTTP/1.0 ... Authorization: Basic %s:%s ... Content-Length: 104 ... Content-Type: text/xml ... SOAPAction: / ... ... <SOAP-ENV:Envelope ... xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ... xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ... xmlns:ZSI="http://www.zolera.com/schemas/ZSI/" ... xmlns:xsd="http://www.w3.org/2001/XMLSchema" ... xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> ... <SOAP-ENV:Header></SOAP-ENV:Header> ... <SOAP-ENV:Body xmlns:ns1="urn:ws-xwebservices-com:XWebEmailValidation:EmailValidation:v2:Messages"> ... <ns1:ValidateEmailRequest> ... <ns1:Email>[email protected]</ns1:Email> ... </ns1:ValidateEmailRequest> ... </SOAP-ENV:Body> ... </SOAP-ENV:Envelope>""" % (user_name, user_password)) HTTP/1.0 200 OK Content-Length: ... Content-Type: text/xml <BLANKLINE> [email protected] is OK...
z3c.soap
/z3c.soap-0.5.5.zip/z3c.soap-0.5.5/z3c/soap/README.txt
README.txt
import re from cgi import FieldStorage, escape from ZPublisher.Converters import get_converter from ZPublisher.HTTPRequest import * from z3c.soap.interfaces import ISOAPRequest from ZPublisher.TaintedString import TaintedString from zope.interface import directlyProvides xmlrpc=None # Placeholder for module that we'll import if we have to. soap=None def processInputs( self, # "static" variables that we want to be local for speed SEQUENCE=1, DEFAULT=2, RECORD=4, RECORDS=8, REC=12, # RECORD | RECORDS EMPTY=16, CONVERTED=32, hasattr=hasattr, getattr=getattr, setattr=setattr, search_type=re.compile('(:[a-zA-Z][-a-zA-Z0-9_]+|\\.[xy])$').search, ): """Process request inputs We need to delay input parsing so that it is done under publisher control for error handling purposes. """ response = self.response environ = self.environ method = environ.get('REQUEST_METHOD','GET') if method != 'GET': fp = self.stdin else: fp = None form = self.form other = self.other taintedform = self.taintedform # If 'QUERY_STRING' is not present in environ # FieldStorage will try to get it from sys.argv[1] # which is not what we need. if 'QUERY_STRING' not in environ: environ['QUERY_STRING'] = '' meth = None fs = ZopeFieldStorage(fp=fp,environ=environ,keep_blank_values=1) if not hasattr(fs,'list') or fs.list is None: # XXX begin monkeypatch contentType = None if fs.headers.has_key('content-type'): contentType = fs.headers['content-type'] # cut off a possible charset definition if contentType.find(';') >= 0: contentType = contentType[0:contentType.find(';')] # Hm, maybe it's an SOAP # SOAP 1.1 has HTTP SOAPAction Field # SOAP 1.2 has Content-Type application/soap+xml # # found a Content-Type of text/xml-SOAP on a Microsoft page # this page points 3 HTTP-Fields for SOAP Requests: # MethodName, InterfaceName (opt) and MessageCall # if (environ.has_key('HTTP_SOAPACTION') or (contentType in ['application/soap+xml', 'text/xml', 'text/xml-SOAP']) and fs.value.find('SOAP-ENV:Body') > 0): global soap if soap is None: import soap fp.seek(0) directlyProvides(self, ISOAPRequest) sparser = soap.SOAPParser(fp.read()) meth = sparser.method self.args = sparser.parse() response = soap.SOAPResponse(response) response._soap11 = environ.has_key('HTTP_SOAPACTION') response._soap12 = (contentType == 'application/soap+xml') response._contentType = contentType response._method = meth response._error_format = 'text/xml' other['RESPONSE'] = self.response = response other['REQUEST_METHOD'] = method self.maybe_webdav_client = 0 # XXX end monkeypatch # Stash XML request for interpretation by a SOAP-aware view other['SOAPXML'] = fs.value # Hm, maybe it's an XML-RPC elif ('content-type' in fs.headers and 'text/xml' in fs.headers['content-type'] and method == 'POST'): # Ye haaa, XML-RPC! global xmlrpc if xmlrpc is None: from ZPublisher import xmlrpc meth, self.args = xmlrpc.parse_input(fs.value) response = xmlrpc.response(response) other['RESPONSE'] = self.response = response self.maybe_webdav_client = 0 else: self._file = fs.file else: fslist = fs.list tuple_items = {} lt = type([]) CGI_name = isCGI_NAMEs defaults = {} tainteddefaults = {} converter = None for item in fslist: isFileUpload = 0 key = item.name if (hasattr(item,'file') and hasattr(item,'filename') and hasattr(item,'headers')): if (item.file and (item.filename is not None # RFC 1867 says that all fields get a content-type. # or 'content-type' in map(lower, item.headers.keys()) )): item = FileUpload(item) isFileUpload = 1 else: item = item.value flags = 0 character_encoding = '' # Variables for potentially unsafe values. tainted = None converter_type = None # Loop through the different types and set # the appropriate flags # We'll search from the back to the front. # We'll do the search in two steps. First, we'll # do a string search, and then we'll check it with # a re search. l = key.rfind(':') if l >= 0: mo = search_type(key,l) if mo: l = mo.start(0) else: l = -1 while l >= 0: type_name = key[l+1:] key = key[:l] c = get_converter(type_name, None) if c is not None: converter = c converter_type = type_name flags = flags | CONVERTED elif type_name == 'list': flags = flags | SEQUENCE elif type_name == 'tuple': tuple_items[key] = 1 flags = flags | SEQUENCE elif (type_name == 'method' or type_name == 'action'): if l: meth = key else: meth = item elif (type_name == 'default_method' or type_name == \ 'default_action'): if not meth: if l: meth = key else: meth = item elif type_name == 'default': flags = flags | DEFAULT elif type_name == 'record': flags = flags | RECORD elif type_name == 'records': flags = flags | RECORDS elif type_name == 'ignore_empty': if not item: flags = flags | EMPTY elif has_codec(type_name): character_encoding = type_name l = key.rfind(':') if l < 0: break mo = search_type(key,l) if mo: l = mo.start(0) else: l = -1 # Filter out special names from form: if key in CGI_name or key[:5] == 'HTTP_': continue # If the key is tainted, mark it so as well. tainted_key = key if '<' in key: tainted_key = TaintedString(key) if flags: # skip over empty fields if flags & EMPTY: continue #Split the key and its attribute if flags & REC: key = key.split(".") key, attr = ".".join(key[:-1]), key[-1] # Update the tainted_key if necessary tainted_key = key if '<' in key: tainted_key = TaintedString(key) # Attributes cannot hold a <. if '<' in attr: raise ValueError( "%s is not a valid record attribute name" % escape(attr)) # defer conversion if flags & CONVERTED: try: if character_encoding: # We have a string with a specified character # encoding. This gets passed to the converter # either as unicode, if it can handle it, or # crunched back down to latin-1 if it can not. item = unicode(item,character_encoding) if hasattr(converter,'convert_unicode'): item = converter.convert_unicode(item) else: item = converter( item.encode(default_encoding)) else: item = converter(item) # Flag potentially unsafe values if converter_type in ('string', 'required', 'text', 'ustring', 'utext'): if not isFileUpload and '<' in item: tainted = TaintedString(item) elif converter_type in ('tokens', 'lines', 'utokens', 'ulines'): is_tainted = 0 tainted = item[:] for i in range(len(tainted)): if '<' in tainted[i]: is_tainted = 1 tainted[i] = TaintedString(tainted[i]) if not is_tainted: tainted = None except: if (not item and not (flags & DEFAULT) and key in defaults): item = defaults[key] if flags & RECORD: item = getattr(item,attr) if flags & RECORDS: item = getattr(item[-1], attr) if tainted_key in tainteddefaults: tainted = tainteddefaults[tainted_key] if flags & RECORD: tainted = getattr(tainted, attr) if flags & RECORDS: tainted = getattr(tainted[-1], attr) else: raise elif not isFileUpload and '<' in item: # Flag potentially unsafe values tainted = TaintedString(item) # If the key is tainted, we need to store stuff in the # tainted dict as well, even if the value is safe. if '<' in tainted_key and tainted is None: tainted = item #Determine which dictionary to use if flags & DEFAULT: mapping_object = defaults tainted_mapping = tainteddefaults else: mapping_object = form tainted_mapping = taintedform #Insert in dictionary if key in mapping_object: if flags & RECORDS: #Get the list and the last record #in the list. reclist is mutable. reclist = mapping_object[key] x = reclist[-1] if tainted: # Store a tainted copy as well if tainted_key not in tainted_mapping: tainted_mapping[tainted_key] = deepcopy( reclist) treclist = tainted_mapping[tainted_key] lastrecord = treclist[-1] if not hasattr(lastrecord, attr): if flags & SEQUENCE: tainted = [tainted] setattr(lastrecord, attr, tainted) else: if flags & SEQUENCE: getattr(lastrecord, attr).append(tainted) else: newrec = record() setattr(newrec, attr, tainted) treclist.append(newrec) elif tainted_key in tainted_mapping: # If we already put a tainted value into this # recordset, we need to make sure the whole # recordset is built. treclist = tainted_mapping[tainted_key] lastrecord = treclist[-1] copyitem = item if not hasattr(lastrecord, attr): if flags & SEQUENCE: copyitem = [copyitem] setattr(lastrecord, attr, copyitem) else: if flags & SEQUENCE: getattr(lastrecord, attr).append(copyitem) else: newrec = record() setattr(newrec, attr, copyitem) treclist.append(newrec) if not hasattr(x,attr): #If the attribute does not #exist, setit if flags & SEQUENCE: item = [item] setattr(x,attr,item) else: if flags & SEQUENCE: # If the attribute is a # sequence, append the item # to the existing attribute y = getattr(x, attr) y.append(item) setattr(x, attr, y) else: # Create a new record and add # it to the list n = record() setattr(n,attr,item) mapping_object[key].append(n) elif flags & RECORD: b = mapping_object[key] if flags & SEQUENCE: item = [item] if not hasattr(b, attr): # if it does not have the # attribute, set it setattr(b, attr, item) else: # it has the attribute so # append the item to it setattr(b, attr, getattr(b, attr) + item) else: # it is not a sequence so # set the attribute setattr(b, attr, item) # Store a tainted copy as well if necessary if tainted: if tainted_key not in tainted_mapping: tainted_mapping[tainted_key] = deepcopy( mapping_object[key]) b = tainted_mapping[tainted_key] if flags & SEQUENCE: seq = getattr(b, attr, []) seq.append(tainted) setattr(b, attr, seq) else: setattr(b, attr, tainted) elif tainted_key in tainted_mapping: # If we already put a tainted value into this # record, we need to make sure the whole record # is built. b = tainted_mapping[tainted_key] if flags & SEQUENCE: seq = getattr(b, attr, []) seq.append(item) setattr(b, attr, seq) else: setattr(b, attr, item) else: # it is not a record or list of records found = mapping_object[key] if tainted: # Store a tainted version if necessary if tainted_key not in tainted_mapping: copied = deepcopy(found) if isinstance(copied, lt): tainted_mapping[tainted_key] = copied else: tainted_mapping[tainted_key] = [copied] tainted_mapping[tainted_key].append(tainted) elif tainted_key in tainted_mapping: # We may already have encountered a tainted # value for this key, and the tainted_mapping # needs to hold all the values. tfound = tainted_mapping[tainted_key] if isinstance(tfound, lt): tainted_mapping[tainted_key].append(item) else: tainted_mapping[tainted_key] = [tfound, item] if type(found) is lt: found.append(item) else: found = [found,item] mapping_object[key] = found else: # The dictionary does not have the key if flags & RECORDS: # Create a new record, set its attribute # and put it in the dictionary as a list a = record() if flags & SEQUENCE: item = [item] setattr(a,attr,item) mapping_object[key] = [a] if tainted: # Store a tainted copy if necessary a = record() if flags & SEQUENCE: tainted = [tainted] setattr(a, attr, tainted) tainted_mapping[tainted_key] = [a] elif flags & RECORD: # Create a new record, set its attribute # and put it in the dictionary if flags & SEQUENCE: item = [item] r = mapping_object[key] = record() setattr(r,attr,item) if tainted: # Store a tainted copy if necessary if flags & SEQUENCE: tainted = [tainted] r = tainted_mapping[tainted_key] = record() setattr(r, attr, tainted) else: # it is not a record or list of records if flags & SEQUENCE: item = [item] mapping_object[key] = item if tainted: # Store a tainted copy if necessary if flags & SEQUENCE: tainted = [tainted] tainted_mapping[tainted_key] = tainted else: # This branch is for case when no type was specified. mapping_object = form if not isFileUpload and '<' in item: tainted = TaintedString(item) elif '<' in key: tainted = item #Insert in dictionary if key in mapping_object: # it is not a record or list of records found = mapping_object[key] if tainted: # Store a tainted version if necessary if tainted_key not in taintedform: copied = deepcopy(found) if isinstance(copied, lt): taintedform[tainted_key] = copied else: taintedform[tainted_key] = [copied] elif not isinstance(taintedform[tainted_key], lt): taintedform[tainted_key] = [ taintedform[tainted_key]] taintedform[tainted_key].append(tainted) elif tainted_key in taintedform: # We may already have encountered a tainted value # for this key, and the taintedform needs to hold # all the values. tfound = taintedform[tainted_key] if isinstance(tfound, lt): taintedform[tainted_key].append(item) else: taintedform[tainted_key] = [tfound, item] if type(found) is lt: found.append(item) else: found = [found,item] mapping_object[key] = found else: mapping_object[key] = item if tainted: taintedform[tainted_key] = tainted #insert defaults into form dictionary if defaults: for key, value in defaults.items(): tainted_key = key if '<' in key: tainted_key = TaintedString(key) if key not in form: # if the form does not have the key, # set the default form[key] = value if tainted_key in tainteddefaults: taintedform[tainted_key] = \ tainteddefaults[tainted_key] else: #The form has the key tdefault = tainteddefaults.get(tainted_key, value) if isinstance(value, record): # if the key is mapped to a record, get the # record r = form[key] # First deal with tainted defaults. if tainted_key in taintedform: tainted = taintedform[tainted_key] for k, v in tdefault.__dict__.items(): if not hasattr(tainted, k): setattr(tainted, k, v) elif tainted_key in tainteddefaults: # Find out if any of the tainted default # attributes needs to be copied over. missesdefault = 0 for k, v in tdefault.__dict__.items(): if not hasattr(r, k): missesdefault = 1 break if missesdefault: tainted = deepcopy(r) for k, v in tdefault.__dict__.items(): if not hasattr(tainted, k): setattr(tainted, k, v) taintedform[tainted_key] = tainted for k, v in value.__dict__.items(): # loop through the attributes and value # in the default dictionary if not hasattr(r, k): # if the form dictionary doesn't have # the attribute, set it to the default setattr(r,k,v) form[key] = r elif isinstance(value, lt): # the default value is a list l = form[key] if not isinstance(l, lt): l = [l] # First deal with tainted copies if tainted_key in taintedform: tainted = taintedform[tainted_key] if not isinstance(tainted, lt): tainted = [tainted] for defitem in tdefault: if isinstance(defitem, record): for k, v in defitem.__dict__.items(): for origitem in tainted: if not hasattr(origitem, k): setattr(origitem, k, v) else: if not defitem in tainted: tainted.append(defitem) taintedform[tainted_key] = tainted elif tainted_key in tainteddefaults: missesdefault = 0 for defitem in tdefault: if isinstance(defitem, record): try: for k, v in \ defitem.__dict__.items(): for origitem in l: if not hasattr( origitem, k): missesdefault = 1 raise NestedLoopExit except NestedLoopExit: break else: if not defitem in l: missesdefault = 1 break if missesdefault: tainted = deepcopy(l) for defitem in tdefault: if isinstance(defitem, record): for k, v in ( defitem.__dict__.items()): for origitem in tainted: if not hasattr( origitem, k): setattr(origitem, k, v) else: if not defitem in tainted: tainted.append(defitem) taintedform[tainted_key] = tainted for x in value: # for each x in the list if isinstance(x, record): # if the x is a record for k, v in x.__dict__.items(): # loop through each # attribute and value in # the record for y in l: # loop through each # record in the form # list if it doesn't # have the attributes # in the default # dictionary, set them if not hasattr(y, k): setattr(y, k, v) else: # x is not a record if not x in l: l.append(x) form[key] = l else: # The form has the key, the key is not mapped # to a record or sequence so do nothing pass # Convert to tuples if tuple_items: for key in tuple_items.keys(): # Split the key and get the attr k = key.split( ".") k,attr = '.'.join(k[:-1]), k[-1] a = attr new = '' # remove any type_names in the attr while not a =='': a = a.split( ":") a,new = ':'.join(a[:-1]), a[-1] attr = new if k in form: # If the form has the split key get its value tainted_split_key = k if '<' in k: tainted_split_key = TaintedString(k) item =form[k] if isinstance(item, record): # if the value is mapped to a record, check if it # has the attribute, if it has it, convert it to # a tuple and set it if hasattr(item,attr): value = tuple(getattr(item,attr)) setattr(item,attr,value) else: # It is mapped to a list of records for x in item: # loop through the records if hasattr(x, attr): # If the record has the attribute # convert it to a tuple and set it value = tuple(getattr(x,attr)) setattr(x,attr,value) # Do the same for the tainted counterpart if tainted_split_key in taintedform: tainted = taintedform[tainted_split_key] if isinstance(item, record): seq = tuple(getattr(tainted, attr)) setattr(tainted, attr, seq) else: for trec in tainted: if hasattr(trec, attr): seq = getattr(trec, attr) seq = tuple(seq) setattr(trec, attr, seq) else: # the form does not have the split key tainted_key = key if '<' in key: tainted_key = TaintedString(key) if key in form: # if it has the original key, get the item # convert it to a tuple item = form[key] item = tuple(form[key]) form[key] = item if tainted_key in taintedform: tainted = tuple(taintedform[tainted_key]) taintedform[tainted_key] = tainted if meth: if 'PATH_INFO' in environ: path = environ['PATH_INFO'] while path[-1:] == '/': path = path[:-1] else: path = '' other['PATH_INFO'] = path = "%s/%s" % (path,meth) self._hacked_path = 1 #XXX this monkey patch does not seems useful anymore??? HTTPRequest.processInputs = processInputs import logging logger = logging.getLogger('Zope') logger.info("z3c.soap: monkeypatched ZPublisher.HTTPRequest.processInputs") # vi:ts=4
z3c.soap
/z3c.soap-0.5.5.zip/z3c.soap-0.5.5/z3c/soap/HTTPRequest.py
HTTPRequest.py
import zope.configuration.fields from zope.security.zcml import Permission from zope.interface import Interface from zope.schema import TextLine class IViewDirective(Interface): """View Directive for SOAP methods.""" for_ = zope.configuration.fields.GlobalObject( title=u"Published Object Type", description=u"""The types of objects to be published via SOAP This can be expressed with either a class or an interface """, required=True) interface = zope.configuration.fields.Tokens( title=u"Interface to be published.", required=False, value_type=zope.configuration.fields.GlobalInterface()) methods = zope.configuration.fields.Tokens( title=u"Methods (or attributes) to be published", required=False, value_type=zope.configuration.fields.PythonIdentifier()) class_ = zope.configuration.fields.GlobalObject( title=u"Class", description=u"A class that provides attributes used by the view.", required=False) permission = Permission( title=u"Permission", description=u"""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 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 = TextLine( title=u"The name of the view.", description=u""" 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, )
z3c.soap
/z3c.soap-0.5.5.zip/z3c.soap-0.5.5/z3c/soap/metadirectives.py
metadirectives.py
from zope.interface import Interface from zope.security.checker import CheckerPublic from zope.component.interface import provideInterface from Products.Five.security import protectClass, protectName try: from zope.app.publisher.browser.viewmeta import _handle_for except: from zope.browserpage.metaconfigure import _handle_for # XXX handler is non-public. Should call directives instead try: from zope.app.component.metaconfigure import handler except ImportError: from zope.component.zcml import handler from inspect import ismethod from interfaces import ISOAPRequest from Globals import InitializeClass as initializeClass from Products.Five.security import getSecurityInfo from Products.Five.metaclass import makeClass from Products.Five.browser import BrowserView from Products.Five.browser.metaconfigure import ViewMixinForAttributes from Products.Five.security import CheckerPrivateId 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_)) cdict = getSecurityInfo(class_) if name: cdict['__name__'] = name new_class = makeClass(class_.__name__, (class_, BrowserView), cdict) _handle_for(_context, for_) # Register the new view. _context.action( discriminator = ('view', (for_, ), name, ISOAPRequest), callable = handler, args = ('registerAdapter', new_class, (for_, ISOAPRequest), Interface, name, _context.info) ) _context.action( discriminator = ('five:protectClass', new_class), callable = protectClass, args = (new_class, permission)) for name in require: _context.action( discriminator = ('five:protectName', new_class, name), callable = protectName, args = (new_class, name, permission)) #else its private: allowed = require private_attrs = [name for name in dir(new_class) if (not name.startswith('_')) and (name not in allowed) and ismethod(getattr(new_class, name))] for attr in private_attrs: _context.action( discriminator = ('five:protectName', new_class, attr), callable = protectName, args = (new_class, attr, CheckerPrivateId)) else: for name in require: cdict.update({'__page_attribute__': name, '__name__': name}) new_class = makeClass(class_.__name__, (class_, ViewMixinForAttributes), cdict) func = getattr(new_class, name) if not func.__doc__: # cannot test for MethodType/UnboundMethod here # because of ExtensionClass if hasattr(func, 'im_func'): # you can only set a docstring on functions, not # on method objects func = func.im_func func.__doc__ = "Stub docstring to make ZPublisher work" _context.action( discriminator = ('view', (for_, ), name, ISOAPRequest), callable = handler, args = ('registerAdapter', new_class, (for_, ISOAPRequest), Interface, name, _context.info)) _context.action( discriminator = ('five:protectClass', new_class), callable = protectClass, args = (new_class, permission)) _context.action( discriminator = ('five:protectName', new_class, name), callable = protectName, args = (new_class, name, permission)) _context.action( discriminator = ('five:initialize:class', new_class), callable = initializeClass, args = (new_class, ) ) # Register the used interfaces with the interface service if for_ is not None: _context.action( discriminator = None, callable = provideInterface, args = ('', for_))
z3c.soap
/z3c.soap-0.5.5.zip/z3c.soap-0.5.5/z3c/soap/metaconfigure.py
metaconfigure.py
Change log ========== 2.1 (2023-07-05) ---------------- - Support ``SQLAlchemy >= 2.0``. (`#15 <https://github.com/zopefoundation/z3c.sqlalchemy/issues/15>`_) 2.0 (2023-03-01) ---------------- - Add support for Python 3.10, 3.11. - Drop support for Python 2.7, 3.5, 3.6. 1.5.2 (2020-11-13) ------------------ - Fix ``MANIFEST`` to include the change log. 1.5.1 (2020-11-13) ------------------ - Add linting to ``tox`` configuration and apply linting fixes. - Fix installation error in setup.py (release 1.5.0 is broken). 1.5.0 (2020-11-13) ------------------ - Add support for Python 3.5-3.9. - Standardize namespace __init__. - Fix to work with zope.sqlalchemy 1.2. 1.4.0 (2009-12-02) ------------------ - Remove compatibility code with older Zope versions. - Fix import issue with modern zope.component versions. - Fix registering of custom mappers. 1.3.11 (26.10.2009) ------------------- - Don't create a new MetaData in LazyMapperCollection, but use the one created in the wrapper. In some cases, you could have some tables in the metadata created in the wrapper, and some tables in the metadata created in the LazyMapperCollection, which gave an error when trying to create relations. - When generating the mapper class, make sure table.name is a string. It can be unicode when use_unicode=1 with MySQL engine. 1.3.10 (04.08.2009) ------------------- - removed SA deprecation warning 1.3.9 (06.01.2009) ------------------ - made 'twophase' configurable 1.3.8 (06.01.2009) ------------------ - replace asDict() with a dictish proxy implementation 1.3.7 (12.12.2008) ------------------ - better support for SQLAlchemy declarative layer 1.3.6 (23.11.2008) ------------------ - zip_safe=False 1.3.5 (05.09.2008) ------------------ - restored compatibiltiy with SA 0.4.X 1.3.4 (04.09.2008) ------------------ - added 'extension_options' parameter 1.3.2 (29.07.2008) ------------------ - updated dependencies to latest zope.sqlalchemy release 1.3.1 (24.06.2008) ------------------ - relaxed zope.* dependencies 1.3.0 (02.06.2008) ------------------ - support for sqlalchemy.ext.declarative 1.2.0 (25.05.2008) ------------------ - now using zope.sqlalchemy for ZODB transaction integration - internal class renaming - removed PythonBaseWrapper. Now there is only *one* ZopeWrappe class. - requires SQLAlchemy 0.4.6 or higher - requires zope.sqlalchemy 0.1 or higher 1.1.5 (08.05.2008) ------------------ - better error handling in case of a rollback (patch by Dieter Maurer) 1.1.4 (15.03.2008) ------------------ - reorganized .txt files 1.1.3 (20.02.2008) ------------------- - another savepoint fix - fixed regression error introduced by previous change: commit the zope transaction when ready in tpc_finish [maurits] - fixed issue where session's transaction.nested was being called as a callable (it should be straight attribute access) [Rocky] 1.1.2 (16.02.2008) ------------------- - fixed ZODB savepoint implementation. Now returning a proper dummy savepoint 1.1.1 (13.02.2008) ------------------- - the SessionDataManager now supports ZODB savepoints 1.1.0 (17.01.2008) ------------------- - WARNING: this version requires SA 0.4.X and higher - fixed import issues with the upcoming SA 0.4.X series - create_session() calls (for SA 0.4.X) - the unittests support an optional $TEST_DSN environment in order to run the test against an existing database (other than SQLite) - major overhoul of the Zope transaction integration: now using one DataManager for the session object and the connection. The connection as returned through the 'connection' property is also used for creating a new 'session'. Older z3c.sqlalchemy version used separate connections. This allows applications to use both a session and a connection within the same Zope request/thread without running into transaction problems. SQL actions and session related modifications should happen within the same transaction. - Wrapper constructor now accepts two new optional dicts 'engine_options' and 'session_options' that will be passed down to the engine and the sessionmaker. Patch provided by Klaus Barthelmann. - mapped objects now provide a method asDict() to return the values of an objects as dict. 1.0.11 (30.07.2007) ------------------- - replaced BoundMetaData() with MetaData() (requires SA 0.3.9+) - removed zope.* dependencies in order to avoid zope.* version mismatches for now 1.0.10 (16.07.2007) ------------------- - using Zope 3.3.X as a fixed depenceny 1.0.9 (08.07.2007) ------------------ - added namespace declarations - reST-ified documentation 1.0.8 (28.06.2007) ------------------ - SessionDataManager: create a session transaction as late as possible and only if necessary in order to minimize deadlocks. So z3c.sqlalchemy won't create a transaction any more if there only SELECT operations within the current session. 1.0.7 (27.06.2007) ------------------ - SessionDataManager: moved commit code from tpc_vote() to tpc_finish() (Thanks to Christian Theune for the hint) 1.0.6 (25.06.2007) ------------------ - added 'namespace_packages' directive to setup.py - cache 'metadata' property 1.0.5 (13.06.2007) ------------------ - It should be now safe to use sessions from multiple wrappers within one Zope transaction. In former versions of z3c.sqlalchemy calling wrapper1.session and wrapper2.session within the same transaction would return a session bound to wrapper1 in both cases. 1.0.4 (09.06.2007) ------------------ - added new 'transactional' flag (used by SQLAlchemyDA only) 1.0.3 (26.05.2007) ------------------ - new 'cascade' parameter for the Model.add() - tweaked the ZODB transaction integration a bit 1.0.2 (13.05.2007) ------------------ - MappedClassBase has a new convinience method getMapper() that returns a mapper class associated through a relation with the current mapper 1.0.1 (unreleased) ------------------ - MappedClassBase: new clone() method - more checks in Model.add() 1.0.0 (05.05.2007) ------------------ - source code polishing - documentation update 0.1.13 (05.05.2007) ------------------- - sessions were returned from the wrong cache - moved the rollback/commit handling inside the SessionDataManager in order to play more nicely with the TPC. See http://mail.zope.org/pipermail/zodb-dev/2007-May/010996.html 0.1.12 (03.05.2007) ------------------- - createSAWrapper() got a new optional 'name' parameter in order to register the wrapper automatically instead of using a dedicated registerSAWrapper(wrapper, name) call 0.1.11 (02.05.2007) ------------------- - added check for the 'mapper_class' attribute (classes from now on must be a subclass of MapperClassBase) - a Zope-aware SAWrapper now has a 'connection' property that can be used to execute SQL statements directly. 'connection' is an instance of sqlalchemy.Connection and directly tied to the current Zope transaction. - changed the caching of the connection and session object for Zope wrapper since the id of a transaction is not reliable (different transaction object can re-use the same memory address leading to cache errors) 0.1.10 (30.04.2007) ------------------- - fixed a bug in mapper (unfortunately I forgot to commit a necessary change) - removed the 'primary_key' parameter introduced in 0.1.9 because we don't need. It can be defined within the model using a PrimaryKeyConstraint() - createSAWrapper: setting forZope=True for a non-postgres DSN now also returns a Zope-aware wrapper instance (instead of a BaseWrapper instance). (Reported by Martin Aspeli) 0.1.9 (26.04.2007) ------------------ - base.py: the 'model' parameter can now also be a callable returning an instance of model.Model - base.py: calling a model provider or a method providing a model with a BoundMetaData instance in order to allow table auto-loading - Model.add() got a new parameter 'primary_key' in order to specify a primary_key hint. This is useful when you are trying to auto-load a view as Table() having no primary key information. The 'primary_key' parameter is either None or a sequence of column names. 0.1.8 (23.04.2007) ------------------ - added shorter method names as aliases - don't generate a new mapper class if a custom mapper class is defined within the model 0.1.7 (21.04.2007) ------------------ - replaced 'echo' parameter of the constructor with a generic keyword parameter in order to provide full parameter support for create_engine. Optional arguments passed to the constructur are passed directly to create_engine() - fixed the documentation a bit - added registerMapper() to BaseWrapper class - registerSQLAlchemyWrapper() now defers the registration until the Wrapper is used first when calling getSQLAlchemyWrapper() - the 'name' parameter of Model.add() now supports schemas (if available). E.g. when using Postgres you can reference as table within a different schema through '<schema>.<tablename>'. - Model.add() accepts a new optional parameter 'table_name' that can be used to specify the name of a table (including schema information) when you want to use the 'name' parameter as an alias for the related table/mapper. 0.1.6 (28.03.2007) ------------------ - fixed a bug in registerSQLAlchemyWrapper 0.1.5 (28.03.2007) ------------------ - registerSQLAlchemyWrapper() should now work with Zope 2.8-2.10 - abort() was defined twice inside the DataManager class 0.1.4 (21.03.2007) ------------------ - the Model class now behave (where needed) as a sorted dictionary. Its items() method must returned all items in insertion order. 0.1.3 (20.03.2007) ------------------ - added getMappers() convenience method - the Zope wrapper uses SessionTransactions in order to be able to flush() as session with a transaction in order to read row previously inserted within the same transaction 0.1.2 (unreleased) ------------------ - fixed class hierarchy issues with Postgres wrapper classes 0.1.1 (unreleased) ------------------ - fixed setup.py 0.1 (18.03.2007) ---------------- - initial version
z3c.sqlalchemy
/z3c.sqlalchemy-2.1.tar.gz/z3c.sqlalchemy-2.1/CHANGES.rst
CHANGES.rst
===================================================== z3c.sqlalchemy - A SQLAlchemy wrapper for Python/Zope ===================================================== What is z3c.sqlalchemy? ======================= z3c.sqlalchemy is yet another wrapper around SQLAlchemy. The functionality of the wrapper is basically focused on easy integration with Zope. The wrapper cares about connection handling, optional transaction integration with Zope and wrapper management (caching, introspection). z3c.sqlalchemy gives you flexible control over the mapper creation. Mapper classes can be - auto-generated (with or without autodetection of table relationships) - configured by the developer What z3c.sqlalchemy does not do and won't do: ============================================= - no support for Zope 3 schemas - no support for Archetypes schemas z3c.sqlachemy just tries to provide you with the basic functionalities you need to write SQLAlchemy-based applications with Zope. Higher-level functionalities like integration with Archetypes/Zope 3 schemas are subject to higher-level frameworks. z3c.sqlalchemy does not address these frameworks. Requirements: ============= - Zope 5 or higher - SQLAlchemy 1.4 or higher - zope.sqlalchemy 1.2.0 or higher - Python 3.7 or higher Installation: ============= Using pip:: pip install z3c.sqlalchemy Note: ----- z3c.sqlalchemy depends on the modules **zope.component**, **zope.schema** and **zope.interface**. If you are using z3c.sqlalchemy in a Python-only environment, ensure the these components have to be installed either as eggs or by setting the PYTHONPATH to a corresponding Zope installation. Usage ===== Basic usage:: from z3c.sqlalchemy import createSAWrapper wrapper = createSAWrapper('postgres://postgres:postgres@host/someDB') session = wrapper.session FormatMapper = wrapper.getMapper('format') # auto-generated mapper for table 'format' for row in session.query(FormatMapper).select(...): print row session.flush() # if necessary The session will participate automatically in a Zope transaction. The wrapper will call automatically session.flush() upon a transaction commit. Please note that 'wrapper.session' will always return the same session instance within the same transaction and same thread. For a real-world application you don't want to create a new wrapper for every new request. Instead you want to register a wrapper instance as named utility (ISQLAlchemyWrapper) and lookup up the wrapper (the utility!) by name from within your application. This approach is very similiar to looking up an databases adapter or a ZSQL method through acquisition. By default "wrapper.getMapper(name)" will always auto-generate a new mapper class by using SQLAlchemy auto-load feature. The drawback of this approach is that the mapper class does not know about relationships to other tables. Assume we have a one-to-many relationship between table A and B and you want z3c.sqlalchemy to generate a mapper that is aware of this relationship. For this purpose you can create a wrapper with a "model" as optional parameter. A model is basically a configuration or a series of hints in order to tell z3c.sqlalchemy how mappers a generated. Example:: from z3c.sqlalchemy import createSAWrapper, Model model = Model() model.add(name='A', relations=('B',)) wrapper = createSAWrapper('postgres://postgres:postgres@host/someDB', model=model) AMapper= wrapper.getMapper('A') This will generate a mapper AMapper where all instances of AMapper have a property 'B' that relates to all corresponding rows in B (see the SQLAlchemy documentation on mappers, properties and relation()). In this example you define the relationship between A and B explictly through the 'relations' parameter (as a sequence of related table names). z3c.sqlalchemy also supports the auto-detection of relationships between tables. Unfortunately SQLAlchemy does not support this feature out-of-the-box and in a portable way. Therefore this feature of z3c.sqlalchemy is highly experimental and currently only available for Postgres (tested with Postgres 8.X).:: from z3c.sqlalchemy import createSAWrapper, Model model = Model() model.add(name='A', autodetect_relations=True) wrapper = createSAWrapper('postgres://postgres:postgres@host/someDB', model=model) AMapper= wrapper.getMapper('A') In this case z3c.sqlalchemy will scan all tables in order to detect relationships automatically and build the mapper class and its properties according to the found relationships. Warning: this feature is experimental and it might take some time to scan all tables before the first request. Currently only Postgres tables in the 'public' schema are supported). In same cases you might be interested to use your own base classes for a generated mapper. Also this usecase is supported by passing the base class to the model using the 'mapper_class' parameter:: from z3c.sqlalchemy import createSAWrapper, Model from z3c.sqlalchemy.mapper import MappedClassBase class MyAMapper(MappedClassBase): pass model = Model() model.add(name='A', relations=('B',) mapper_class = MyAMapper) wrapper = createSAWrapper('postgres://postgres:postgres@host/someDB', model=model) AMapper= wrapper.getMapper('A') # AMapper will be an instance of MyAMapper When you are working with wrapper in a Zope environment you are usually interested to to register a wrapper instance as named utility implementing ISQLAlchemyWrapper. You can can perform the registration lazily by passing the name utility as 'name' parameter to the createSAWrapper(..., name='my.postgres.test.db') method. A convenience method for obtaining a wrapper instance by name is available through getSAWrapper:: createSAWrapper(dsn,..., name='my.name') ... wrapper = getSAWrapper('my.name') Supported systems ================= z3c.sqlalchemy was developed with Zope and basically tested against Postgres 7.4.X and 8.X and SQLite 3.3. Known issues ============ Running z3c.sqalchemy against MySQL databases without transaction support might cause trouble upon the implicit commit() operation. For this reason MySQL without transaction support isn't supported right now Author ====== z3c.sqlalchemy was written by Andreas Jung for Haufe Mediengruppe, Freiburg, Germany and ZOPYX Ltd. & Co. KG, Tuebingen, Germany. License ======= z3c.sqlalchemy is licensed under the Zope Public License 2.1. See LICENSE.txt. Credits ======= Parts of the code are influenced by z3c.zalchemy (Juergen Kartnaller, Michael Bernstein & others) and Alchemist/ore.alchemist (Kapil Thangavelu). Thanks to Martin Aspeli for giving valuable feedback.
z3c.sqlalchemy
/z3c.sqlalchemy-2.1.tar.gz/z3c.sqlalchemy-2.1/README.rst
README.rst
from sqlalchemy.engine.url import make_url from zope.component import getUtilitiesFor from zope.component import getUtility from zope.interface.interfaces import ComponentLookupError from z3c.sqlalchemy.base import ZopeWrapper from z3c.sqlalchemy.interfaces import ISQLAlchemyWrapper from z3c.sqlalchemy.postgres import ZopePostgresWrapper __all__ = ('createSQLAlchemyWrapper', 'registerSQLAlchemyWrapper', 'allRegisteredSQLAlchemyWrappers', 'getSQLAlchemyWrapper', 'createSAWrapper', 'registerSAWrapper', 'allRegisteredSAWrappers', 'getSAWrapper', 'allSAWrapperNames') registeredWrappers = {} def createSAWrapper(dsn, model=None, name=None, transactional=True, engine_options={}, session_options={}, extension_options={}, **kw): """ Convenience method to generate a wrapper for a DSN and a model. This method hides all database related magic from the user. 'dsn' - something like 'postgres://user:password@host/dbname' 'model' - None or an instance of model.Model or a string representing a named utility implementing IModelProvider or a method/callable returning an instance of model.Model. 'transactional' - True|False, only used for SQLAlchemyDA *don't change it* 'name' can be set to register the wrapper automatically in order to avoid a dedicated registerSAWrapper() call. 'engine_options' can be set to a dict containing keyword parameters passed to create_engine. 'session_options' can be set to a dict containing keyword parameters passed to create_session or sessionmaker. 'extension_options' can be set to a dict containing keyword parameters passed to ZopeTransactionExtension() """ url = make_url(dsn) driver = url.drivername klass = ZopeWrapper if driver == 'postgres': klass = ZopePostgresWrapper wrapper = klass(dsn, model, transactional=transactional, engine_options=engine_options, session_options=session_options, extension_options=extension_options, **kw) if name is not None: registerSAWrapper(wrapper, name) return wrapper createSQLAlchemyWrapper = createSAWrapper def registerSAWrapper(wrapper, name): """ deferred registration of the wrapper as named utility """ if name not in registeredWrappers: registeredWrappers[name] = wrapper else: raise ValueError("SAWrapper '%s' already registered.\n" "You can not register a wrapper twice under the " "same name." % name) registerSQLAlchemyWrapper = registerSAWrapper def _registerSAWrapper(wrapper, name): """ register a SQLAlchemyWrapper as named utility. (never call this method directly) """ from zope.component import provideUtility provideUtility(wrapper, name=name) def getSAWrapper(name): """ return a SQLAlchemyWrapper instance by name """ if name not in registeredWrappers: raise ValueError('No registered SQLAlchemyWrapper with ' 'name %s found' % name) # Perform a late and lazy registration of the wrapper as # named utility. Late initialization is necessary for Zope 2 # application if you want to register wrapper instances during # the product initialization phase of Zope when the Z3 registries # are not yet initializied. try: return getUtility(ISQLAlchemyWrapper, name) except ComponentLookupError: wrapper = registeredWrappers[name] _registerSAWrapper(wrapper, name) return wrapper getSQLAlchemyWrapper = getSAWrapper def allRegisteredSAWrappers(): """ return a dict containing information for all registered wrappers. """ for name, wrapper in getUtilitiesFor(ISQLAlchemyWrapper): yield {'name': name, 'dsn': wrapper.dsn, 'kw': wrapper.kw, } allRegisteredSQLAlchemyWrappers = allRegisteredSAWrappers def allSAWrapperNames(): """ return list of all registered wrapper names """ names = registeredWrappers.keys() return sorted(names) if __name__ == '__main__': print(createSAWrapper('postgres://test:[email protected]/TestDB'))
z3c.sqlalchemy
/z3c.sqlalchemy-2.1.tar.gz/z3c.sqlalchemy-2.1/src/z3c/sqlalchemy/util.py
util.py
from zope.interface import Interface from zope.schema import Bool from zope.schema import Int from zope.schema import TextLine class ISQLAlchemyWrapper(Interface): """ A SQLAlchemyWrapper wraps sqlalchemy and deals with connection and transaction handling. """ dsn = TextLine(title='A RFC-1738 style connection string', required=True) dbname = TextLine(title='Database name', required=True) host = TextLine(title='Hostname of database', required=True) port = Int(title='Port of database', required=True) username = TextLine(title='Database user', required=True) password = TextLine(title='Password of database user', required=True) echo = Bool(title='Echo all SQL statements to the console', required=True) def registerMapper(mapper, name): """ register your own mapper under a custom name """ def getMapper(tablename, schema='public'): """ return a mapper class for a table given by its 'tablename' and an optional 'schema' name """ def getMappers(*tablenames): """ return a sequence of mapper classes for a given list of table names. ATT: Schema support? """ class IModelProvider(Interface): """ A model providers provides information about the tables to be used and the mapper classes. """ def getModel(metadata=None): """ The model is described as an ordered dictionary. The entries are (tablename, some_dict) where 'some_dict' is a dictionary containing a key 'table' referencing a Table() instance and an optional key 'relationships' referencing a sequence of related table names. An optional mapper class can be specified through the 'class' key (otherwise a default mapper class will be autogenerated). """ class IModel(Interface): """ A model represents a configuration hint for SQLAlchemy wrapper instances in order to deliver mappers for a given name. """ def add(name, table=None, mapper_class=None, relations=None, autodetect_relations=False, table_name=None): """ 'name' -- name of table (no schema support so far!) 'table' -- a sqlalchemy.Table instance (None, for autoloading) 'mapper_class' -- an optional class to be used as mapper class for 'table' 'relations' -- an optional list of table names referencing 'table'. This is used for auto-constructing the relation properties of the mapper class. 'autodetect_relations' -- try to autodetect the relationships between tables and auto-construct the relation properties of the mapper if 'relations' is omitted (set to None) 'table_name' -- optional full name of a table (e.g. 'someschema.sometable') if you want to use 'name' as alias for the table. """ def items(): """ return items in insertion order """
z3c.sqlalchemy
/z3c.sqlalchemy-2.1.tar.gz/z3c.sqlalchemy-2.1/src/z3c/sqlalchemy/interfaces.py
interfaces.py
from sqlalchemy import MetaData from sqlalchemy import create_engine from sqlalchemy.engine.url import make_url from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from zope.component import getUtility from zope.interface import implementer from zope.interface.interfaces import ComponentLookupError from zope.sqlalchemy import register from z3c.sqlalchemy.interfaces import IModelProvider from z3c.sqlalchemy.interfaces import ISQLAlchemyWrapper from z3c.sqlalchemy.mapper import LazyMapperCollection from z3c.sqlalchemy.model import Model @implementer(ISQLAlchemyWrapper) class ZopeWrapper: def __init__(self, dsn, model=None, transactional=True, twophase=False, engine_options={}, session_options={}, extension_options={}, **kw): """ 'dsn' - a RFC-1738-style connection string 'model' - optional instance of model.Model 'engine_options' - optional keyword arguments passed to create_engine() 'session_options' - optional keyword arguments passed to create_session() or sessionmaker() 'extension_options' - optional keyword argument passed to ZopeTransactionExtension() 'transactional' - True|False, only used by SQLAlchemyDA, *don't touch it* """ self.dsn = dsn self.url = make_url(dsn) self.host = self.url.host self.port = self.url.port self.username = self.url.username self.password = self.url.password self.dbname = self.url.database self.twophase = twophase self.drivername = self.url.drivername self.transactional = transactional self.engine_options = engine_options if 'echo' in kw: self.engine_options.update(echo=kw['echo']) self.session_options = session_options self.extension_options = extension_options self._model = None self._createEngine() if model: if isinstance(model, Model): self._model = model elif isinstance(model, str): try: util = getUtility(IModelProvider, model) except ComponentLookupError: msg = "No named utility '%s' providing IModelProvider" raise ComponentLookupError(msg % model) self._model = util.getModel(self.metadata) elif callable(model): self._model = model(self.metadata) else: raise ValueError("The 'model' parameter passed to constructor " "must either be the name of a named utility " "implementing IModelProvider or an instance " "of z3c.sqlalchemy.model.Model.") if not isinstance(self._model, Model): raise TypeError('_model is not an instance of model.Model') # mappers must be initialized at last since we need to acces # the 'model' from within the constructor of LazyMapperCollection self._mappers = LazyMapperCollection(self) @property def metadata(self): if not hasattr(self, '_v_metadata'): self._v_metadata = MetaData() return self._v_metadata @property def session(self): """ Return thread-local session """ return self._session @property def connection(self): """ Return underlying connection """ session = self.session # Return the ConnectionFairy return session.connection().connection # instead of the raw connection # return session.connection().connection.connection def registerMapper(self, mapper, name): self._mappers._registerMapper(mapper, name) def getMapper(self, tablename, schema='public'): return self._mappers.getMapper(tablename, schema) def getMappers(self, *names): return tuple([self.getMapper(name) for name in names]) @property def engine(self): """ only for private purposes! """ return self._engine @property def model(self): """ only for private purposes! """ return self._model def _createEngine(self): self._engine = create_engine(self.dsn, **self.engine_options) self._sessionmaker = scoped_session(sessionmaker(bind=self._engine, autocommit=not self.transactional, twophase=self.twophase, autoflush=True, **self.session_options)) register(self._sessionmaker) self._session = self._sessionmaker()
z3c.sqlalchemy
/z3c.sqlalchemy-2.1.tar.gz/z3c.sqlalchemy-2.1/src/z3c/sqlalchemy/base.py
base.py
import threading from sqlalchemy import Table from sqlalchemy.ext.declarative import DeclarativeMeta from sqlalchemy.orm import class_mapper from sqlalchemy.orm import registry from sqlalchemy.orm import relationship marker = object class Proxy(dict): """ Dict-Proxy for mapped objects providing attribute-style access. """ def __init__(self, obj): super(dict, self).__init__() self.update(obj.__dict__.copy()) for attr in getattr(obj, 'proxied_properties', ()): self[attr] = getattr(obj, attr) del self['_sa_instance_state'] def __getattribute__(self, name): if name in dict.keys(self): return self.get(name) return super(dict, self).__getattribute__(name) def __getattr__(self, name, default=None): if name in dict.keys(self): return self.get(name, default) return super(dict, self).__getattr__(name, default) class MappedClassBase: """ base class for all mapped classes """ # Zope 2 security magic.......buuuuuuuhhhhhh __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, **kw): """ accepts keywords arguments used for initialization of mapped attributes/columns. """ self.wrapper = None for k, v in kw.items(): setattr(self, k, v) def clone(self): """ Create a pristine copy. Use this method if you need to reinsert a copy of the current mapper instance back into the database. """ d = dict() for col in self.c.keys(): d[col] = getattr(self, col) return self.__class__(**d) def asDict(self): """ Returns current object as a dict""" return Proxy(self) def getMapper(self, name): """ Return a mapper associated with the current mapper. If this mapper represents a table A having a relationship to table B then the mapper for B can be obtained through self.getMapper('B'). This method is useful if you don't want to pass the wrapper around this the wrapper is officially the only way to get hold of a mapper by name. See also http://groups.google.com/group/sqlalchemy/browse_thread/thread/18fb2e2818bdc032/5c2dfd71679925cb#5c2dfd71679925cb # NOQA: E501 """ try: return class_mapper( self.__class__).get_property(name).mapper.class_ except AttributeError: return class_mapper(self.__class__).props[name].mapper.class_ class MapperFactory: """ a factory for table and mapper objects """ def __init__(self, metadata): self.metadata = metadata def __call__(self, table, properties={}, cls=None): """ Returns a tuple (mapped_class, table_class). 'table' - sqlalchemy.Table to be mapped 'properties' - dict containing additional informations about 'cls' - (optional) class used as base for creating the mapper class (will be autogenerated if not available). """ if cls is None: newCls = type('_mapped_%s' % str(table.name), (MappedClassBase,), {}) else: newCls = cls registry().map_imperatively(newCls, table, properties=properties) return newCls class LazyMapperCollection(dict): """ Implements a cache for table mappers """ def __init__(self, wrapper): super().__init__() self._wrapper = wrapper self._engine = wrapper.engine self._model = wrapper.model or {} self._metadata = wrapper.metadata self._mapper_factory = MapperFactory(self._metadata) self._dependent_tables = None self._lock = threading.Lock() def getMapper(self, name, schema='public'): """ return a (cached) mapper class for a given table 'name' """ if name not in self: # no-cached data, let's lookup the table ourselfs table = None # check if the optional model provides a table definition if name in self._model: table = self._model[name].get('table') # support for SA declarative layer mapper_class = self._model[name].get('mapper_class') if isinstance(mapper_class, DeclarativeMeta): self._registerMapper(mapper_class, name) return mapper_class # if not: introspect table definition if table is None: tname = self._model.get(name, {}).get('table_name') table_name = tname or name # check for 'schema.tablename' if '.' in table_name: schema, tablename = table_name.split('.') else: tablename, schema = table_name, None table = Table(tablename, self._metadata, schema=schema, autoload_with=self._engine) # check if the model contains an optional mapper class mapper_class = None if name in self._model: mapper_class = self._model[name].get('mapper_class') # use auto-introspected table dependencies for creating # the 'properties' dict that tells the mapper about # relationships to other tables dependent_table_names = [] if name in self._model: adr = self._model[name].get('autodetect_relations', False) if self._model[name].get('relations') is not None: dependent_table_names = self._model[name].get('relations', []) or [] elif adr is True: if self._dependent_tables is None: # Introspect table dependencies once. The introspection # is deferred until the moment where we really need to # introspect them meth = getattr(self._wrapper, 'findDependentTables', None) if meth is not None: self._dependent_tables = meth(ignoreErrors=True) else: self._dependent_tables = {} dependent_table_names = ( self._dependent_tables.get(name, []) or []) # build additional property dict for mapper properties = {} # find all dependent tables (referencing the current table) for table_refname in dependent_table_names: # create or get a mapper for the referencing table table_ref_mapper = self.getMapper(table_refname) # add the mapper as relation to the properties dict properties[table_refname] = ( relationship( table_ref_mapper, cascade=self._model.get(name, {}).get('cascade'), ) ) # create a mapper and cache it if mapper_class and 'c' in mapper_class.__dict__: mapper = mapper_class else: mapper = self._mapper_factory(table, properties=properties, cls=mapper_class) self._registerMapper(mapper, name) return self[name] def _registerMapper(self, mapper, name): """ register a mapper under a given name """ self._lock.acquire() self[name] = mapper self._lock.release()
z3c.sqlalchemy
/z3c.sqlalchemy-2.1.tar.gz/z3c.sqlalchemy-2.1/src/z3c/sqlalchemy/mapper.py
mapper.py
import sqlalchemy from zope.interface import implementer from .interfaces import IModel __all__ = ('Model',) @implementer(IModel) class Model(dict): """ The Model is an optional helper class that can be passed to the constructor of a SQLAlchemy wrapper in order to provide hints for the mapper generation. """ def __init__(self, *args): """ The constructor can be called with a series of dict. Each dict represents a single table and its data (see add() method). """ super().__init__() self.names = [] for d in args: self.add(**d) def add(self, name, table=None, mapper_class=None, relations=None, autodetect_relations=False, table_name=None, cascade=None): """ 'name' -- name of table (no schema support so far!) 'table' -- a sqlalchemy.Table instance (None, for autoloading) 'mapper_class' -- an optional class to be used as mapper class for 'table' 'relations' -- an optional list of table names referencing 'table'. This is used for auto-constructing the relation properties of the mapper class. 'autodetect_relations' -- try to autodetect the relationships between tables and auto-construct the relation properties of the mapper if 'relations' is omitted (set to None) 'table_name' -- optional full name of a table (e.g. 'someschema.sometable') if you want to use 'name' as alias for the table. 'cascade' -- optional cascade parameter directly passed to the relation() call """ if table is not None and not isinstance(table, sqlalchemy.Table): raise TypeError( "'table' must be an instance or sqlalchemy.Table or None") # sqlalchemy.ext.declarative can be used on _any_ base class # if mapper_class is not None and \ # not issubclass(mapper_class, MappedClassBase): # raise TypeError( # "'mapper_class' must be a subclass of MappedClassBase") if relations is not None: if not isinstance(relations, (tuple, list)): raise TypeError( 'relations must be specified a sequence of strings') for r in relations: if not isinstance(r, str): raise TypeError( 'relations must be specified a sequence of strings') if relations is not None and autodetect_relations is True: raise ValueError("'relations' and 'autodetect_relations' can't " "be specified at the same time") self.names.append(name) self[name] = {'name': name, 'table': table, 'relations': relations, 'mapper_class': mapper_class, 'autodetect_relations': autodetect_relations, 'cascade': cascade, 'table_name': table_name, } def items(self): """ return items in insertion order """ for name in self.names: yield name, self[name] if __name__ == '__main__': m = Model() md = sqlalchemy.MetaData() m.add('users') m.add('groups', sqlalchemy.Table('groups', md, sqlalchemy.Column('id', sqlalchemy.Integer))) m = Model() md = sqlalchemy.MetaData() col = sqlalchemy.Column('id', sqlalchemy.Integer) m = Model({'name': 'users'}, {'name': 'groups', 'table': sqlalchemy.Table('groups', md, col)})
z3c.sqlalchemy
/z3c.sqlalchemy-2.1.tar.gz/z3c.sqlalchemy-2.1/src/z3c/sqlalchemy/model.py
model.py
Introduction ============ z3c.suds manages a connection pool of `suds`_ client objects in the context of a ZODB-based application. (suds is a lightweight client library for consuming SOAP web services in Python.) Using it avoids the need for instantiating a new client for the same webservice in multiple requests (which may be expensive due to parsing WSDL, etc.) .. _`suds`: https://fedorahosted.org/suds/ Usage ----- A client may be obtained via the `get_suds_client` method:: client = get_suds_client(wsdl_uri, context=None) This returns an existing suds client if one is found in the cache for the given WSDL; otherwise it returns a new client object and stores it in the cache. `wsdl_path` is the URI of the WSDL (web service definition language) description of the web service. (Use a file:// URI for a locally stored WSDL.) `context` is a persistent object (in the ZODB sense). If not provided, the `getSite` method of zope.site.hooks will be used to obtain an object (which is probably only sensible within the context of a Zopish framework). If the context object is associated with a ZODB connection, the client will be cached in the connection's `foreign_connections` dictionary. If the context object is not yet associated with a ZODB connection, the client will be cached in a volatile attribute instead. This approach to piggybacking a pool of connections on the ZODB connection pool is based on `alm.solrindex`, and further documented there. .. _`alm.solrindex`: http://pypi.python.org/pypi/alm.solrindex
z3c.suds
/z3c.suds-1.0.zip/z3c.suds-1.0/README.txt
README.txt
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] try: import pkg_resources import setuptools if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) reload(sys.modules['pkg_resources']) import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
z3c.suds
/z3c.suds-1.0.zip/z3c.suds-1.0/bootstrap.py
bootstrap.py
======= CHANGES ======= 3.0 (2023-03-31) ---------------- - Add support for Python 3.11. - Drop support for Python 2.7, 3.5, 3.6. - Protect against bad input in request parameters -- don't fail hard, use defaults 2.2 (2022-02-11) ---------------- - Add support for Python 3.8, 3.9 and 3.10. 2.1.1 (2019-03-26) ------------------ - Fix: escape special HTML characters at ``Column.renderHeadCell``, ``NameColumn.getName``, ``CheckBoxColumn`` name and value, ``RadioColumn`` name and value, ``LinkColumn`` href and link content. 2.1 (2019-01-27) ---------------- - Added support for Python 3.7 and PyPy3. - Dropped support for running the tests using `python setup.py test`. - Reformatted the code using black and flake8. 2.0.1 (2017-04-19) ------------------ - Required future>=0.14.0 so `html` package is available in Python 2.7. 2.0.0 (2017-04-17) ------------------ - Updated to support Python 2.7, 3.5, and 3.6 only. - Added html title attribute on LinkColumn 2.0.0a1 (2013-02-26) -------------------- - Added support for Python 3.3, dropped support for Python 2.5 and below. - Got rid of testing dependencies on z3.testing and zope.app.testing. 1.0.0 (2012-08-09) ------------------ - Added sorting (``cssClassSortedOn`` and ``getCSSSortClass``) CSS options - Added cell highlight (``getCSSHighlightClass``) CSS option - Added ``GetItemColumn`` which gets the value by index/key access. 0.9.1 (2011-08-03) ------------------ - Fixed SelectedItemColumn.update when just one item was selected 0.9.0 (2010-08-09) ------------------ - Added ``EMailColumn`` which can be used to display mailto links. - Fixed the default BatchProvider not to lose table sorting query arguments from the generated links; now batching and sorting play with each other nicely. - Split single doctest file (README.txt) into different files 0.8.1 (2010-07-31) ------------------ - Added translation for the link title in the column header of the sortable table. 0.8.0 (2009-12-29) ------------------ - Added translation for ``LinkColumn.linkContent``. - Added ``I18nGetAttrColumn`` which translates its content. 0.7.0 (2009-12-29) ------------------ - Allow to initialze the column definitions without requiring an entire table update. - Fixed tests, so they no longer use ``zope.app.container`` (which was even not declared as test dependency). - Head cell contents are now translated. 0.6.1 (2009-02-22) ------------------ - Be smart to not ``IPhysicallyLocatable`` objects if we lookup the ``__name__`` value in columns. 0.6.0 (2008-11-12) ------------------ - Bugfix: Allow to switch the sort order on the header link. This was blocked to descending after the first click - Bugfix: CheckBoxColumn, ensure that we allways use a list for compare selected items. It was possible that if only one item get selected we compared a string. If this string was a sub string of another existing item the other item get selected too. - Moved advanced batching implementation into z3c.batching - Implemented GetAttrFormatterColumn. This column can be used for simple value formatting columns. - Bad typo in columns.py: Renamed ``getLinkConent`` to ``getLinkContent`` - Bug: Changed return string in getLinkCSS. It was using css="" instead of class="" for CSS classes. Thanks to Dan for reporting this bugs. - Implemented SelectedItemColumn - Fix CheckBoxColumn, use always the correct selectedItems. Use always real selectedItems form the table - Fix RadioColumn, use always the correct selectedItem from the selectedItems list. Use always the first selectedItems form the tables selectedItems 0.5.0 (2008-04-13) ------------------ - Initial Release.
z3c.table
/z3c.table-3.0.tar.gz/z3c.table-3.0/CHANGES.rst
CHANGES.rst
.. image:: https://img.shields.io/pypi/v/z3c.table.svg :target: https://pypi.python.org/pypi/z3c.table/ :alt: Latest release .. image:: https://img.shields.io/pypi/pyversions/z3c.table.svg :target: https://pypi.org/project/z3c.table/ :alt: Supported Python versions .. image:: https://github.com/zopefoundation/z3c.table/actions/workflows/tests.yml/badge.svg :target: https://github.com/zopefoundation/z3c.table/actions/workflows/tests.yml .. image:: https://coveralls.io/repos/github/zopefoundation/z3c.table/badge.svg :target: https://coveralls.io/github/zopefoundation/z3c.table This package provides a modular table rendering implementation for Zope3.
z3c.table
/z3c.table-3.0.tar.gz/z3c.table-3.0/README.rst
README.rst
Miscellaneous ------------- Make coverage report happy and test different things. Test if the getWeight method returns 0 (zero) on AttributeError: >>> from z3c.table.table import getWeight >>> getWeight(None) 0 Create a container: >>> from z3c.table.testing import Container >>> container = Container() Try to call a simple table and call renderBatch which should return an empty string: >>> from z3c.table import table >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> simpleTable = table.Table(container, request) >>> simpleTable.renderBatch() u'' Try to render an empty table adapting an empty mapping: >>> simpleTable = table.Table({}, request) >>> simpleTable.cssClassSortedOn = None >>> simpleTable.render() u'' Since we register an adapter for IColumn on None (IOW on an empty mapping). >>> from zope.component import provideAdapter >>> from z3c.table import column >>> from z3c.table import interfaces >>> provideAdapter(column.NameColumn, ... (None, None, interfaces.ITable), provides=interfaces.IColumn, ... name='secondColumn') Initializing rows definitions for the empty table initializes the columns attribute list. >>> simpleTable.columns >>> simpleTable.initColumns() >>> simpleTable.columns [<NameColumn u'secondColumn'>] Rendering the empty table now return the string: >>> print(simpleTable.render()) <table> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> </tbody> </table> Let's see if the addColumn raises a ValueError if there is no Column class: >>> column.addColumn(simpleTable, column.Column, u'dummy') <Column u'dummy'> >>> column.addColumn(simpleTable, None, u'dummy') Traceback (most recent call last): ... ValueError: class_ None must implement IColumn. Test if we can set additional kws in addColumn: >>> simpleColumn = column.addColumn(simpleTable, column.Column, u'dummy', ... foo='foo value', bar=u'something else', counter=99) >>> simpleColumn.foo 'foo value' >>> simpleColumn.bar u'something else' >>> simpleColumn.counter 99 The NoneCell class provides some methods which never get called. But these are defined in the interface. Let's test the default values and make coverage report happy. Let's get an container item first: >>> from z3c.table.testing import Content >>> firstItem = Content('First', 1) >>> noneCellColumn = column.addColumn(simpleTable, column.NoneCell, u'none') >>> noneCellColumn.renderCell(firstItem) u'' >>> noneCellColumn.getColspan(firstItem) 0 >>> noneCellColumn.renderHeadCell() u'' >>> noneCellColumn.renderCell(firstItem) u'' The default ``Column`` implementation raises an NotImplementedError if we do not override the renderCell method: >>> defaultColumn = column.addColumn(simpleTable, column.Column, u'default') >>> defaultColumn.renderCell(firstItem) Traceback (most recent call last): ... NotImplementedError: Subclass must implement renderCell
z3c.table
/z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/miscellaneous.rst
miscellaneous.rst
========= z3c Table ========= .. contents:: The goal of this package is to offer a modular table rendering library. We use the content provider pattern and the column are implemented as adapters which will give us a powerful base concept. Some important concepts we use ------------------------------ - separate implementation in update render parts, This allows to manipulate data after update call and before we render them. - allow to use page templates if needed. By default all is done in python. - allow to use the rendered batch outside the existing table HTML part. No skins -------- This package does not provide any kind of template or skin support. Most the time if you need to render a table, you will use your own skin concept. This means you can render the table or batch within your own templates. This will ensure that we have as few dependencies as possible in this package and the package can get reused with any skin concept. Note ---- As you probably know, batching is only possible after sorting columns. This is a nightmare if it comes to performance. The reason is, all data need to get sorted before the batch can start at the given position. And sorting can most of the time only be done by touching each object. This means you have to be careful if you are using a large set of data, even if you use batching. Sample data setup ----------------- Let's create a sample container which we can use as our iterable context: >>> from zope.container import btree >>> class Container(btree.BTreeContainer): ... """Sample container.""" ... __name__ = u'container' >>> container = Container() and set a parent for the container: >>> root['container'] = container and create a sample content object which we use as container item: >>> class Content(object): ... """Sample content.""" ... def __init__(self, title, number): ... self.title = title ... self.number = number Now setup some items: >>> container[u'first'] = Content('First', 1) >>> container[u'second'] = Content('Second', 2) >>> container[u'third'] = Content('Third', 3) Table ----- Create a test request and represent the table: >>> from zope.publisher.browser import TestRequest >>> from z3c.table import table >>> request = TestRequest() >>> plainTable = table.Table(container, request) >>> plainTable.cssClassSortedOn = None Now we can update and render the table. As you can see with an empty container we will not get anything that looks like a table. We just get an empty string: >>> plainTable.update() >>> plainTable.render() u'' Column Adapter -------------- We can create a column for our table: >>> import zope.component >>> from z3c.table import interfaces >>> from z3c.table import column >>> class TitleColumn(column.Column): ... ... weight = 10 ... header = u'Title' ... ... def renderCell(self, item): ... return u'Title: %s' % item.title Now we can register the column: >>> zope.component.provideAdapter(TitleColumn, ... (None, None, interfaces.ITable), provides=interfaces.IColumn, ... name='firstColumn') Now we can render the table again: >>> plainTable.update() >>> print(plainTable.render()) <table> <thead> <tr> <th>Title</th> </tr> </thead> <tbody> <tr> <td>Title: First</td> </tr> <tr> <td>Title: Second</td> </tr> <tr> <td>Title: Third</td> </tr> </tbody> </table> We can also use the predefined name column: >>> zope.component.provideAdapter(column.NameColumn, ... (None, None, interfaces.ITable), provides=interfaces.IColumn, ... name='secondColumn') Now we will get an additional column: >>> plainTable.update() >>> print(plainTable.render()) <table> <thead> <tr> <th>Name</th> <th>Title</th> </tr> </thead> <tbody> <tr> <td>first</td> <td>Title: First</td> </tr> <tr> <td>second</td> <td>Title: Second</td> </tr> <tr> <td>third</td> <td>Title: Third</td> </tr> </tbody> </table> Colspan ------- Now let's show how we can define a colspan condition of 2 for a column: >>> class ColspanColumn(column.NameColumn): ... ... weight = 999 ... ... def getColspan(self, item): ... # colspan condition ... if item.__name__ == 'first': ... return 2 ... else: ... return 0 ... ... def renderHeadCell(self): ... return u'Colspan' ... ... def renderCell(self, item): ... return u'colspan: %s' % item.title Now we register this column adapter as colspanColumn: >>> zope.component.provideAdapter(ColspanColumn, ... (None, None, interfaces.ITable), provides=interfaces.IColumn, ... name='colspanColumn') Now you can see that the colspan of the ColspanAdapter is larger than the table. This will raise a ValueError: >>> plainTable.update() Traceback (most recent call last): ... ValueError: Colspan for column '<ColspanColumn u'colspanColumn'>' is larger than the table. But if we set the column as first row, it will render the colspan correctly: >>> class CorrectColspanColumn(ColspanColumn): ... """Colspan with correct weight.""" ... ... weight = -1 # NameColumn is 0 Register and render the table again: >>> zope.component.provideAdapter(CorrectColspanColumn, ... (None, None, interfaces.ITable), provides=interfaces.IColumn, ... name='colspanColumn') >>> plainTable.update() >>> print(plainTable.render()) <table> <thead> <tr> <th>Colspan</th> <th>Name</th> <th>Title</th> </tr> </thead> <tbody> <tr> <td colspan="2">colspan: First</td> <td>Title: First</td> </tr> <tr> <td>colspan: Second</td> <td>second</td> <td>Title: Second</td> </tr> <tr> <td>colspan: Third</td> <td>third</td> <td>Title: Third</td> </tr> </tbody> </table> Setup columns ------------- The existing implementation allows us to define a table in a class without using the modular adapter pattern for columns. First we need to define a column which can render a value for our items: >>> class SimpleColumn(column.Column): ... ... weight = 0 ... ... def renderCell(self, item): ... return item.title Let's define our table which defines the columns explicitly. you can also see that we do not return the columns in the correct order: >>> class PrivateTable(table.Table): ... cssClassSortedOn = None ... ... def setUpColumns(self): ... firstColumn = TitleColumn(self.context, self.request, self) ... firstColumn.__name__ = u'title' ... firstColumn.weight = 1 ... secondColumn = SimpleColumn(self.context, self.request, self) ... secondColumn.__name__ = u'simple' ... secondColumn.weight = 2 ... secondColumn.header = u'The second column' ... return [secondColumn, firstColumn] Now we can create, update and render the table and see that this renders a nice table too: >>> privateTable = PrivateTable(container, request) >>> privateTable.update() >>> print(privateTable.render()) <table> <thead> <tr> <th>Title</th> <th>The second column</th> </tr> </thead> <tbody> <tr> <td>Title: First</td> <td>First</td> </tr> <tr> <td>Title: Second</td> <td>Second</td> </tr> <tr> <td>Title: Third</td> <td>Third</td> </tr> </tbody> </table> Cascading Style Sheet --------------------- Our table and column implementation supports css class assignment. Let's define a table and columns with some css class values: >>> class CSSTable(table.Table): ... ... cssClasses = {'table': 'table', ... 'thead': 'thead', ... 'tbody': 'tbody', ... 'th': 'th', ... 'tr': 'tr', ... 'td': 'td'} ... cssClassSortedOn = None ... ... def setUpColumns(self): ... firstColumn = TitleColumn(self.context, self.request, self) ... firstColumn.__name__ = u'title' ... firstColumn.__parent__ = self ... firstColumn.weight = 1 ... firstColumn.cssClasses = {'th':'thCol', 'td':'tdCol'} ... secondColumn = SimpleColumn(self.context, self.request, self) ... secondColumn.__name__ = u'simple' ... secondColumn.__parent__ = self ... secondColumn.weight = 2 ... secondColumn.header = u'The second column' ... return [secondColumn, firstColumn] Now let's see if we got the css class assigned which we defined in the table and column. Note that the ``th`` and ``td`` got CSS declarations from the table and from the column: >>> cssTable = CSSTable(container, request) >>> cssTable.update() >>> print(cssTable.render()) <table class="table"> <thead class="thead"> <tr class="tr"> <th class="thCol th">Title</th> <th class="th">The second column</th> </tr> </thead> <tbody class="tbody"> <tr class="tr"> <td class="tdCol td">Title: First</td> <td class="td">First</td> </tr> <tr class="tr"> <td class="tdCol td">Title: Second</td> <td class="td">Second</td> </tr> <tr class="tr"> <td class="tdCol td">Title: Third</td> <td class="td">Third</td> </tr> </tbody> </table> Alternating table ----------------- We offer built in support for alternating table rows based on even and odd CSS classes. Let's define a table including other CSS classes. For even/odd support, we only need to define the ``cssClassEven`` and ``cssClassOdd`` CSS classes: >>> class AlternatingTable(table.Table): ... ... cssClasses = {'table': 'table', ... 'thead': 'thead', ... 'tbody': 'tbody', ... 'th': 'th', ... 'tr': 'tr', ... 'td': 'td'} ... ... cssClassEven = u'even' ... cssClassOdd = u'odd' ... cssClassSortedOn = None ... ... def setUpColumns(self): ... firstColumn = TitleColumn(self.context, self.request, self) ... firstColumn.__name__ = u'title' ... firstColumn.__parent__ = self ... firstColumn.weight = 1 ... firstColumn.cssClasses = {'th':'thCol', 'td':'tdCol'} ... secondColumn = SimpleColumn(self.context, self.request, self) ... secondColumn.__name__ = u'simple' ... secondColumn.__parent__ = self ... secondColumn.weight = 2 ... secondColumn.header = u'The second column' ... return [secondColumn, firstColumn] Now update and render the new table. As you can see the given ``tr`` class is added to the even and odd classes: >>> alternatingTable = AlternatingTable(container, request) >>> alternatingTable.update() >>> print(alternatingTable.render()) <table class="table"> <thead class="thead"> <tr class="tr"> <th class="thCol th">Title</th> <th class="th">The second column</th> </tr> </thead> <tbody class="tbody"> <tr class="even tr"> <td class="tdCol td">Title: First</td> <td class="td">First</td> </tr> <tr class="odd tr"> <td class="tdCol td">Title: Second</td> <td class="td">Second</td> </tr> <tr class="even tr"> <td class="tdCol td">Title: Third</td> <td class="td">Third</td> </tr> </tbody> </table> Class based Table setup ----------------------- There is a more elegant way to define table rows at class level. We offer a method which you can use if you need to define some columns called ``addColumn``. Before we define the table. let's define some cell renderer: >>> def headCellRenderer(): ... return u'My items' >>> def cellRenderer(item): ... return u'%s item' % item.title Now we can define our table and use the custom cell renderer: >>> class AddColumnTable(table.Table): ... ... cssClasses = {'table': 'table', ... 'thead': 'thead', ... 'tbody': 'tbody', ... 'th': 'th', ... 'tr': 'tr', ... 'td': 'td'} ... ... cssClassEven = u'even' ... cssClassOdd = u'odd' ... cssClassSortedOn = None ... ... def setUpColumns(self): ... return [ ... column.addColumn(self, TitleColumn, u'title', ... cellRenderer=cellRenderer, ... headCellRenderer=headCellRenderer, ... weight=1, colspan=0), ... column.addColumn(self, SimpleColumn, name=u'simple', ... weight=2, header=u'The second column', ... cssClasses = {'th':'thCol', 'td':'tdCol'}) ... ] Add some more content:: >>> container[u'fourth'] = Content('Fourth', 4) >>> container[u'zero'] = Content('Zero', 0) >>> addColumnTable = AddColumnTable(container, request) >>> addColumnTable.update() >>> print(addColumnTable.render()) <table class="table"> <thead class="thead"> <tr class="tr"> <th class="th">My items</th> <th class="thCol th">The second column</th> </tr> </thead> <tbody class="tbody"> <tr class="even tr"> <td class="td">First item</td> <td class="tdCol td">First</td> </tr> <tr class="odd tr"> <td class="td">Fourth item</td> <td class="tdCol td">Fourth</td> </tr> <tr class="even tr"> <td class="td">Second item</td> <td class="tdCol td">Second</td> </tr> <tr class="odd tr"> <td class="td">Third item</td> <td class="tdCol td">Third</td> </tr> <tr class="even tr"> <td class="td">Zero item</td> <td class="tdCol td">Zero</td> </tr> </tbody> </table> As you can see the table columns provide all attributes we set in the addColumn method: >>> titleColumn = addColumnTable.rows[0][0][1] >>> titleColumn <TitleColumn u'title'> >>> titleColumn.__name__ u'title' >>> titleColumn.__parent__ <AddColumnTable None> >>> titleColumn.colspan 0 >>> titleColumn.weight 1 >>> titleColumn.header u'Title' >>> titleColumn.cssClasses {} and the second column: >>> simpleColumn = addColumnTable.rows[0][1][1] >>> simpleColumn <SimpleColumn u'simple'> >>> simpleColumn.__name__ u'simple' >>> simpleColumn.__parent__ <AddColumnTable None> >>> simpleColumn.colspan 0 >>> simpleColumn.weight 2 >>> simpleColumn.header u'The second column' >>> sorted(simpleColumn.cssClasses.items()) [('td', 'tdCol'), ('th', 'thCol')] Headers ------- We can change the rendering of the header of, e.g, the Title column by registering a IHeaderColumn adapter. This may be useful for adding links to column headers for an existing table implementation. We'll use a fresh almost empty container.: >>> container = Container() >>> root['container-1'] = container >>> container[u'first'] = Content('First', 1) >>> container[u'second'] = Content('Second', 2) >>> container[u'third'] = Content('Third', 3) >>> class myTableClass(table.Table): ... cssClassSortedOn = None >>> myTable = myTableClass(container, request) >>> class TitleColumn(column.Column): ... ... header = u'Title' ... weight = -2 ... ... def renderCell(self, item): ... return item.title Now we can register a column adapter directly to our table class: >>> zope.component.provideAdapter(TitleColumn, ... (None, None, myTableClass), provides=interfaces.IColumn, ... name='titleColumn') And add a registration for a column header - we'll use here the provided generic sorting header implementation: >>> from z3c.table.header import SortingColumnHeader >>> zope.component.provideAdapter(SortingColumnHeader, ... (None, None, interfaces.ITable, interfaces.IColumn), ... provides=interfaces.IColumnHeader) Now we can render the table and we shall see a link in the header. Note that it is set to switch to descending as the table initially will display the first column as ascending: >>> myTable.update() >>> print(myTable.render()) <table> <thead> <tr> <th><a href="?table-sortOn=table-titleColumn-0&table-sortOrder=descending" title="Sort">Title</a></th> ... </table> If the table is initially set to descending, the link should allow to switch to ascending again: >>> myTable.sortOrder = 'descending' >>> print(myTable.render()) <table> <thead> <tr> <th><a href="?table-sortOn=table-titleColumn-0&table-sortOrder=ascending" title="Sort">Title</a></th> ... </table> If the table is ascending but the request was descending, the link should allow to switch again to ascending: >>> descendingRequest = TestRequest(form={'table-sortOn': 'table-titleColumn-0', ... 'table-sortOrder':'descending'}) >>> myTable = myTableClass(container, descendingRequest) >>> myTable.sortOrder = 'ascending' >>> myTable.update() >>> print(myTable.render()) <table> <thead> <tr> <th><a href="?table-sortOn=table-titleColumn-0&table-sortOrder=ascending" title="Sort">Title</a></th> ... </table>
z3c.table
/z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/README.rst
README.rst
__docformat__ = "reStructuredText" import html from urllib.parse import urlencode import zope.i18n import zope.i18nmessageid import zope.interface import zope.location from zope.dublincore.interfaces import IZopeDublinCore from zope.security.interfaces import Unauthorized from zope.traversing import api from zope.traversing.browser import absoluteURL from z3c.table import interfaces _ = zope.i18nmessageid.MessageFactory("z3c") def addColumn( self, class_, name, cellRenderer=None, headCellRenderer=None, colspan=None, weight=None, header=None, cssClasses=None, **kws ): if not interfaces.IColumn.implementedBy(class_): raise ValueError("class_ %s must implement IColumn." % class_) column = class_(self.context, self.request, self) column.__parent__ = self column.__name__ = name if cellRenderer is not None: # overload method column.renderCell = cellRenderer if headCellRenderer is not None: # overload method column.renderHeadCell = headCellRenderer if colspan is not None: column.colspan = colspan if weight is not None: column.weight = weight if header is not None: column.header = header if cssClasses is not None: column.cssClasses = cssClasses for name, value in kws.items(): setattr(column, name, value) return column def getName(item): # probably not IPhysicallyLocatable but still could have a __name__ try: return api.getName(item) except TypeError: return item.__name__ def safeGetAttr(obj, attr, default): try: return getattr(obj, attr, default) except Unauthorized: return default @zope.interface.implementer(interfaces.IColumn) class Column(zope.location.Location): """Column provider.""" # variables will be set by table id = None # customize this part if needed colspan = 0 weight = 0 header = "" cssClasses = {} def __init__(self, context, request, table): self.__parent__ = context self.context = context self.request = request self.table = table def update(self): pass def getColspan(self, item): """Returns the colspan value.""" return self.colspan def getSortKey(self, item): """Returns the sort key used for column sorting.""" return self.renderCell(item) def renderHeadCell(self): """Header cell content.""" header = zope.component.queryMultiAdapter( (self.context, self.request, self.table, self), interfaces.IColumnHeader, ) if header: header.update() # HTML escaping is the responsibility of IColumnHeader.render return header.render() # make sure we don't output HTML special chars return html.escape( zope.i18n.translate(self.header, context=self.request) ) def renderCell(self, item): """Cell content.""" raise NotImplementedError("Subclass must implement renderCell") def __repr__(self): return "<{} {!r}>".format(self.__class__.__name__, self.__name__) @zope.interface.implementer(interfaces.INoneCell) class NoneCell(Column): """None cell is used for mark a previous colspan.""" def getColspan(self, item): return 0 def renderHeadCell(self): return "" def renderCell(self, item): return "" # predefined columns class NameColumn(Column): """Name column.""" header = _("Name") def renderCell(self, item): return html.escape(getName(item)) try: apply except NameError: def apply(f, *a): return f(*a) class RadioColumn(Column): """Radio column.""" header = _("X") @apply def selectedItem(): # use the items form the table def get(self): if len(self.table.selectedItems): return list(self.table.selectedItems).pop() def set(self, value): self.table.selectedItems = [value] return property(get, set) def getSortKey(self, item): return getName(item) def getItemKey(self, item): return "%s-selectedItem" % self.id def getItemValue(self, item): return getName(item) def update(self): items = [ item for item in self.table.values if self.getItemValue(item) in self.request.get(self.getItemKey(item), []) ] if len(items): self.selectedItem = items.pop() def renderCell(self, item): selected = "" if item == self.selectedItem: selected = ' checked="checked"' return ( '<input type="radio" class="{}" name="{}" value="{}"{} />'.format( "radio-widget", html.escape(self.getItemKey(item)), html.escape(self.getItemValue(item)), selected, )) class CheckBoxColumn(Column): """Checkbox column.""" header = _("X") weight = 10 @apply def selectedItems(): # use the items form the table def get(self): return self.table.selectedItems def set(self, values): self.table.selectedItems = values return property(get, set) def getSortKey(self, item): return getName(item) def getItemKey(self, item): return "%s-selectedItems" % self.id def getItemValue(self, item): return getName(item) def isSelected(self, item): v = self.request.get(self.getItemKey(item), []) v = ensureList(v) if self.getItemValue(item) in v: return True return False def update(self): self.selectedItems = [ item for item in self.table.values if self.isSelected(item) ] def renderCell(self, item): selected = "" if item in self.selectedItems: selected = ' checked="checked"' return ( '<input type="checkbox" class="%s" name="%s" value="%s"%s />' % ( "checkbox-widget", html.escape(self.getItemKey(item)), html.escape(self.getItemValue(item)), selected, ) ) class GetAttrColumn(Column): """Get attribute column.""" attrName = None defaultValue = "" def getValue(self, obj): if obj is not None and self.attrName is not None: return safeGetAttr(obj, self.attrName, self.defaultValue) return self.defaultValue def renderCell(self, item): return self.getValue(item) class GetItemColumn(Column): """Get value from item index/key column.""" idx = None defaultValue = "" def getValue(self, obj): if obj is not None and self.idx is not None: try: return obj[self.idx] except (KeyError, IndexError, Unauthorized): return self.defaultValue return self.defaultValue def renderCell(self, item): return self.getValue(item) class I18nGetAttrColumn(GetAttrColumn): """GetAttrColumn which translates its content.""" def renderCell(self, item): return zope.i18n.translate(self.getValue(item), context=self.request) class FormatterColumn(Column): """Formatter column.""" formatterCategory = "dateTime" formatterLength = "medium" formatterName = None formatterCalendar = "gregorian" def getFormatter(self): return self.request.locale.dates.getFormatter( self.formatterCategory, self.formatterLength, self.formatterName, self.formatterCalendar, ) class GetAttrFormatterColumn(FormatterColumn, GetAttrColumn): """Get attribute and formatter column.""" def renderCell(self, item): formatter = self.getFormatter() value = self.getValue(item) if value: value = formatter.format(value) return value class CreatedColumn(FormatterColumn, GetAttrColumn): """Created date column.""" header = _("Created") weight = 100 formatterCategory = "dateTime" formatterLength = "short" attrName = "created" def renderCell(self, item): formatter = self.getFormatter() dc = IZopeDublinCore(item, None) value = self.getValue(dc) if value: value = formatter.format(value) return value class ModifiedColumn(FormatterColumn, GetAttrColumn): """Created date column.""" header = _("Modified") weight = 110 formatterCategory = "dateTime" formatterLength = "short" attrName = "modified" def renderCell(self, item): formatter = self.getFormatter() dc = IZopeDublinCore(item, None) value = self.getValue(dc) if value: value = formatter.format(value) return value class LinkColumn(Column): """Name column.""" header = _("Name") linkName = None linkTarget = None linkContent = None linkCSS = None linkTitle = None def getLinkURL(self, item): """Setup link url.""" if self.linkName is not None: return "{}/{}".format( absoluteURL(item, self.request), self.linkName) return absoluteURL(item, self.request) def getLinkCSS(self, item): """Setup link css.""" return self.linkCSS and ' class="%s"' % self.linkCSS or "" def getLinkTitle(self, item): """Setup link title.""" return ( ' title="%s"' % html.escape(self.linkTitle) if self.linkTitle else "" ) def getLinkTarget(self, item): """Setup link target.""" return self.linkTarget and ' target="%s"' % self.linkTarget or "" def getLinkContent(self, item): """Setup link content.""" if self.linkContent: return zope.i18n.translate(self.linkContent, context=self.request) return getName(item) def renderCell(self, item): # setup a tag return '<a href="{}"{}{}{}>{}</a>'.format( html.escape(self.getLinkURL(item)), self.getLinkTarget(item), self.getLinkCSS(item), self.getLinkTitle(item), html.escape(self.getLinkContent(item)), ) class EMailColumn(LinkColumn, GetAttrColumn): "Column to display mailto links." header = _("E-Mail") attrName = None # attribute name which contains the mail address defaultValue = "" # value which is rendered when no value is found linkContent = None def getLinkURL(self, item): return "mailto:%s" % self.getValue(item) def getLinkContent(self, item): if self.linkContent: return zope.i18n.translate(self.linkContent, context=self.request) return self.getValue(item) def renderCell(self, item): value = self.getValue(item) if value is self.defaultValue or value is None: return self.defaultValue return super().renderCell(item) def ensureList(item): if not isinstance(item, (list, tuple)): return [item] return item class SelectedItemColumn(LinkColumn): """Link which can set an item.""" selectedItem = None @property def viewURL(self): return "{}/{}".format( absoluteURL(self.context, self.request), self.table.__name__, ) def getItemKey(self, item): return "%s-selectedItems" % self.id def getItemValue(self, item): return getName(item) def getSortKey(self, item): """Returns the sort key used for column sorting.""" return self.getLinkContent(item) def getLinkContent(self, item): """Setup link content.""" return self.linkContent or getName(item) def getLinkURL(self, item): """Setup link url.""" return "{}?{}".format( self.viewURL, urlencode({self.getItemKey(item): self.getItemValue(item)}), ) def update(self): items = [ item for item in self.table.values if self.getItemValue(item) in ensureList(self.request.get(self.getItemKey(item), [])) ] if len(items): self.selectedItem = items.pop() self.table.selectedItems = [self.selectedItem] class ContentsLinkColumn(LinkColumn): """Link pointing to contents.html.""" linkName = "contents.html" class IndexLinkColumn(LinkColumn): """Link pointing to index.html.""" linkName = "index.html" class EditLinkColumn(LinkColumn): """Link pointing to edit.html.""" linkName = "edit.html"
z3c.table
/z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/column.py
column.py
__docformat__ = "reStructuredText" from urllib.parse import urlencode import zope.i18n import zope.interface import z3c.table.interfaces from z3c.table.i18n import _ from z3c.table.table import getCurrentSortID @zope.interface.implementer(z3c.table.interfaces.IColumnHeader) class ColumnHeader: """ColumnHeader renderer provider""" _request_args = [] def __init__(self, context, request, table, column): self.__parent__ = context self.context = context self.request = request self.table = table self.column = column def update(self): """Override this method in subclasses if required""" pass def render(self): """Override this method in subclasses""" return self.column.header def getQueryStringArgs(self): """ Collect additional terms from the request and include in sorting column headers Perhaps this should be in separate interface only for sorting headers? """ args = {} for key in self._request_args: value = self.request.get(key, None) if value: args.update({key: value}) return args class SortingColumnHeader(ColumnHeader): """Sorting column header.""" def render(self): table = self.table prefix = table.prefix colID = self.column.id currentSortID = getCurrentSortID(table.getSortOn()) currentSortOrder = table.getSortOrder() sortID = colID.rsplit("-", 1)[-1] sortOrder = table.sortOrder if int(sortID) == currentSortID: # ordering the same column so we want to reverse the order if currentSortOrder in table.reverseSortOrderNames: sortOrder = "ascending" elif currentSortOrder == "ascending": sortOrder = table.reverseSortOrderNames[0] args = self.getQueryStringArgs() args.update( {"%s-sortOn" % prefix: colID, "%s-sortOrder" % prefix: sortOrder} ) queryString = "?%s" % (urlencode(sorted(args.items()))) return '<a href="{}" title="{}">{}</a>'.format( queryString, zope.i18n.translate(_("Sort"), context=self.request), zope.i18n.translate(self.column.header, context=self.request), )
z3c.table
/z3c.table-3.0.tar.gz/z3c.table-3.0/src/z3c/table/header.py
header.py