desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Serialize the form list as JSON (EdenMobile) @returns: a JSON string'
def json(self):
return json.dumps(self.formlist, separators=SEPARATORS)
'Constructor @param resource - the S3Resource'
def __init__(self, resource):
self.resource = resource self._references = {} self._schema = None self._form = None self._subheadings = DEFAULT
'Serialize the table schema @return: a JSON-serializable dict containing the table schema'
def serialize(self):
schema = self._schema if (schema is None): schema = {} self._references = {} fields = self.fields() for field in fields: description = self.describe(field) if description: schema[field.name] = description self._schema = schema r...
'Tables (and records) referenced in this schema (lazy property) @return: a dict {tablename: [recordID, ...]} of all referenced tables and records'
@property def references(self):
if (self._references is None): self.serialize() return self._references
'The mobile form (field order) for the resource (lazy property)'
@property def form(self):
if (self._form is None): self.serialize() return self._form
'The subheadings for the mobile form (lazy property)'
@property def subheadings(self):
subheadings = self._subheadings if (subheadings is DEFAULT): setting = self.resource.get_config('subheadings') subheadings = self._subheadings = self.subheadings_l10n(setting) return subheadings
'Construct a field description for the schema @param field: a Field instance @return: the field description as JSON-serializable dict'
def describe(self, field):
fieldtype = str(field.type) SUPPORTED_FIELD_TYPES = set(self.SUPPORTED_FIELD_TYPES) if (fieldtype[:9] == 'reference'): key = s3_get_foreign_key(field)[1] if (key and (key != 'id')): return None is_foreign_key = True lookup = fieldtype[10:].split('.')[0] re...
'Encode settings for the field description @param field: a Field instance @return: a dict with the field settings'
@classmethod def settings(cls, field):
settings = {} if (not field.readable): settings['readable'] = False if (not field.writable): settings['writable'] = False if cls.is_required(field): settings['required'] = True return settings
'Determine whether a value is required for a field @param field: the Field @return: True|False'
@staticmethod def is_required(field):
required = field.notnull if ((not required) and field.requires): error = field.validate('')[1] if (error is not None): required = True return required
'Get the options for a field with IS_IN_SET @param field: the Field @param lookup: the look-up table name (if field is a foreign key) @return: a list of tuples (key, label) with the field options'
def get_options(self, field, lookup=None):
requires = field.requires if (not requires): return None if isinstance(requires, (list, tuple)): requires = requires[0] if isinstance(requires, IS_EMPTY_OR): requires = requires.other fieldtype = str(field.type) if (fieldtype[:9] == 'reference'): if (field.writabl...
'Get the default value for a field @param field: the Field @returns: the default value for the field'
def get_default(self, field, lookup=None):
default = field.default if (default is not None): fieldtype = str(field.type) if (fieldtype[:9] == 'reference'): uuid = self.get_uuid(lookup, default) if uuid: self._references[lookup].add(default) default = uuid else: ...
'Determine which fields need to be included in the schema @returns: a list of Field instances'
def fields(self):
resource = self.resource tablename = resource.tablename fields = [] mobile_form = self._form = [] fnames = set() include = fnames.add form = self.mobile_form(resource) for element in form.elements: if isinstance(element, S3SQLField): rfield = resource.resolve_selector...
'Check whether a table exposes a mobile form @param tablename: the table name @return: True|False'
@staticmethod def has_mobile_form(tablename):
from s3model import DYNAMIC_PREFIX if tablename.startswith(DYNAMIC_PREFIX): ttable = current.s3db.s3_table query = (((ttable.name == tablename) & (ttable.mobile_form == True)) & (ttable.deleted != True)) row = current.db(query).select(ttable.id, limitby=(0, 1)).first() if row: ...
'Get the mobile form for a resource @param resource: the S3Resource @returns: an S3SQLForm instance'
@staticmethod def mobile_form(resource):
form = resource.get_config('mobile_form') if (form is None): form = resource.get_config('crud_form') if (not form): readable_fields = resource.readable_fields() fields = [field.name for field in readable_fields if (field.type != 'id')] form = S3SQLCustomForm(*fields) retu...
'Look up the UUID of a record @param tablename: the table name @param record_id: the record ID @return: the UUID of the specified record, or None if the record does not exist or has no UUID'
@staticmethod def get_uuid(tablename, record_id):
table = current.s3db.table(tablename) if ((not table) or ('uuid' not in table.fields)): return None query = (table._id == record_id) if ('deleted' in table.fields): query &= (table.deleted == False) row = current.db(query).select(table.uuid, limitby=(0, 1)).first() return ((row.u...
'Helper to translate form subheadings @param setting: the subheadings-setting (a dict) @return: the subheadings dict with translated headers'
@classmethod def subheadings_l10n(cls, setting):
if (setting is None): return None T = current.T output = {} for (header, fields) in setting.items(): if isinstance(fields, dict): subheadings = fields.get('subheadings') fields = {'fields': fields.get('fields')} if subheadings: fields['...
'Constructor @param resource: the S3Resource @param form: an S3SQLForm instance to override settings'
def __init__(self, resource, form=None):
self.resource = resource self._form = form self._config = DEFAULT
'The mobile form configuration (lazy property) @returns: a dict {tablename, title, options}'
@property def config(self):
config = self._config if (config is DEFAULT): tablename = self.resource.tablename config = {'tablename': tablename, 'title': None, 'options': {}} forms = current.deployment_settings.get_mobile_forms() if forms: for form in forms: options = None ...
'Serialize the mobile form configuration for the target resource @param msince: include look-up records only if modified after this datetime ("modified since") @return: a JSON-serialiable dict containing the mobile form configuration for export to the mobile client'
def serialize(self, msince=None):
s3db = current.s3db resource = self.resource ms = S3MobileSchema(resource) schema = ms.serialize() main = {'tablename': resource.tablename, 'schema': schema, 'form': ms.form} strings = self.strings() if strings: main['strings'] = strings subheadings = ms.subheadings if subhea...
'Add CRUD strings for mobile form @return: a dict with CRUD strings for the resource'
def strings(self):
tablename = self.resource.tablename config = self.config title = config.get('title') if (not title): crud_strings = current.response.s3.crud_strings.get(tablename) if crud_strings: title = crud_strings.get('title_list') if (not title): name = tablename.split('_', ...
'Add component declarations to the mobile form @return: a dict with component declarations for the resource'
def components(self):
resource = self.resource tablename = resource.tablename pkey = resource._id.name options = self.config.get('options') components = {} aliases = (options.get('components') if options else None) if aliases: hooks = current.s3db.get_components(tablename, names=aliases) for (alia...
'Entry point for REST interface. @param r: the S3Request instance @param attr: controller attributes'
def apply_method(self, r, **attr):
http = r.http method = r.method representation = r.representation output = {} if (method == 'mform'): if (representation == 'json'): if (http == 'GET'): output = self.mform(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) ...
'Get the mobile form for the target resource @param r: the S3Request instance @param attr: controller attributes @returns: a JSON string'
def mform(self, r, **attr):
resource = self.resource msince = r.get_vars.get('msince') if msince: msince = s3_parse_datetime(msince) mform = S3MobileForm(resource).serialize(msince=msince) mform['controller'] = r.controller mform['function'] = r.function output = json.dumps(mform, separators=SEPARATORS) cur...
'API Method to decode a source into an ElementTree, to be implemented by the subclass @param resource: the S3Resource @param source: the source @return: an S3XML ElementTree'
def decode(self, resource, source, **attr):
raise NotImplementedError
'API Method to encode an ElementTree into the target format, to be implemented by the subclass @param resource: the S3Resource @return: a handle to the output'
def encode(self, resource, **attr):
raise NotImplementedError
'XML-escape a string @param s: the string'
@classmethod def xml_encode(cls, s):
if s: s = escape(s, cls.PY2XML) return s
'XML-unescape a string @param s: the string'
@classmethod def xml_decode(cls, s):
if s: s = unescape(s, cls.XML2PY) return s
'Get a CRUD string @param tablename: the table name @param name: the name of the CRUD string'
@staticmethod def crud_string(tablename, name):
crud_strings = current.response.s3.crud_strings _crud_strings = crud_strings.get(tablename, crud_strings) return _crud_strings.get(name, crud_strings.get(name, None))
'Provide a nicely-formatted JSON Message @param success: action succeeded or failed @param status_code: the HTTP status code @param message: the message text @param kwargs: other elements for the message @keyword tree: error tree to include as JSON object (rather than as string) for easy decoding'
@staticmethod def json_message(success=True, statuscode=None, message=None, **kwargs):
if (statuscode is None): statuscode = ((success and 200) or 404) status = ((success and 'success') or 'failed') code = str(statuscode) output = {'status': status, 'statuscode': str(code)} tree = kwargs.get('tree', None) if message: output['message'] = s3_unicode(message) for ...
'Export resource as CSV @param resource: the resource to export @note: export does not include components! @todo: implement audit'
def csv(self, resource):
request = current.request response = current.response if response: servername = ((request and ('%s_' % request.env.server_name)) or '') filename = ('%s%s.csv' % (servername, resource.tablename)) from gluon.contenttype import contenttype response.headers['Content-Type'] = cont...
'Export a resource as JSON @param resource: the resource to export from @param start: index of the first record to export @param limit: maximum number of records to export @param fields: list of field selectors for fields to include in the export (None for all fields) @param orderby: ORDERBY expression @param represent...
def json(self, resource, start=None, limit=None, fields=None, orderby=None, represent=False, tooltip=None):
if (fields is None): fields = resource.list_fields('json_fields', id_column=0) if (orderby is None): orderby = resource.get_config('orderby', None) tooltip_function = None if tooltip: if (type(tooltip) is list): tooltip = tooltip[(-1)] import re match ...
'Traceback constructor'
def __init__(self, text):
self.text = text
'Returns the xml'
def xml(self):
output = self.make_links(CODE(self.text).xml()) return output
'Create a link from a path'
def make_link(self, path):
tryFile = path.replace('\\', '/') if (os.path.isabs(tryFile) and os.path.isfile(tryFile)): (folder, filename) = os.path.split(tryFile) (base, ext) = os.path.splitext(filename) app = current.request.args[0] editable = {'controllers': '.py', 'models': '.py', 'views': '.html'} ...
'Make links using the given traceback'
def make_links(self, traceback):
lwords = traceback.split('"') result = (((len(lwords) != 0) and lwords[0]) or '') i = 1 while (i < len(lwords)): link = self.make_link(lwords[i]) if (link == ''): result += ('"' + lwords[i]) else: result += link if ((i + 1) < len(lwords)): ...
'Use a custom view template @param template: name of the template (determines the path) @param filename: name of the view template file'
@classmethod def _view(cls, template, filename):
if ('.' in template): (subfolder, template) = template.split('.', 1) view = os.path.join(current.request.folder, current.deployment_settings.get_template_location(), 'templates', subfolder, template, 'views', filename) else: view = os.path.join(current.request.folder, current.deployment_...
'Convert b into the data type of a @raise TypeError: if any of the data types are not supported or the types are incompatible @raise ValueError: if the value conversion fails'
@classmethod def convert(cls, a, b):
if isinstance(a, lazyT): a = str(a) if (b is None): return None if (type(a) is type): if (a in (str, unicode)): return cls._str(b) if (a is int): return cls._int(b) if (a is bool): return cls._bool(b) if (a is long): ...
'Convert into bool'
@staticmethod def _bool(b):
if isinstance(b, bool): return b if isinstance(b, basestring): if (b.lower() in ('true', '1')): return True elif (b.lower() in ('false', '0')): return False if isinstance(b, (int, long)): if (b == 0): return False else: ...
'Convert into string'
@staticmethod def _str(b):
if isinstance(b, basestring): return b return str(b)
'Convert into int'
@staticmethod def _int(b):
if isinstance(b, int): return b return int(b)
'Convert into long'
@staticmethod def _long(b):
if isinstance(b, long): return b return long(b)
'Convert into float'
@staticmethod def _float(b):
if isinstance(b, long): return b return float(b)
'Convert into datetime.datetime'
@staticmethod def _datetime(b):
if isinstance(b, datetime.datetime): return b elif isinstance(b, basestring): dt = None try: (y, m, d, hh, mm, ss, t0, t1, t2) = time.strptime(b, ISOFORMAT) except ValueError: dt = b else: dt = datetime.datetime(y, m, d, hh, mm, ss) ...
'Convert into datetime.date'
@classmethod def _date(cls, b):
if isinstance(b, datetime.date): return b elif isinstance(b, basestring): from s3validators import IS_UTC_DATE (value, error) = IS_UTC_DATE(format='%Y-%m-%d')(b) if error: (value, error) = IS_UTC_DATE()(b) if error: value = cls._datetime(b).date() ...
'Convert into datetime.time'
@staticmethod def _time(b):
if isinstance(b, datetime.time): return b elif isinstance(b, basestring): validator = IS_TIME() (value, error) = validator(v) if error: raise ValueError return value else: raise TypeError
'Constructor'
def __init__(self, paths=None):
self.paths = [] if isinstance(paths, S3MultiPath): self.paths = list(paths.paths) else: if (paths is None): paths = [] elif (type(paths) is str): paths = self.__parse(paths) elif (not isinstance(paths, (list, tuple))): paths = [paths] ...
'Append a new ancestor path to this multi-path @param path: the ancestor path'
def append(self, path):
Path = self.Path if isinstance(path, Path): path = path.nodes else: path = Path(path).nodes multipath = None paths = self.__normalize(path) append = self.paths.append for p in paths: p = Path(p) if (not (self & p)): append(p) multipath ...
'Extend this multi-path with a new vertex ancestors<-head @param head: the head node @param ancestors: the ancestor (multi-)path of the head node'
def extend(self, head, ancestors=None, cut=None):
if isinstance(ancestors, S3MultiPath): extend = self.extend for p in ancestors.paths: extend(head, p, cut=cut) return self extensions = [] Path = self.Path append = extensions.append for p in self.paths: if cut: pos = p.find(cut) if...
'Cut off the vertex ancestor<-head in this multi-path @param head: the head node @param ancestor: the ancestor node to cut off'
def cut(self, head, ancestor=None):
for p in self.paths: p.cut(head, ancestor) return self.clean()
'Remove any duplicate and empty paths from this multi-path'
def clean(self):
mp = S3MultiPath(self) pop = mp.paths.pop self.paths = [] append = self.paths.append while len(mp): item = pop(0) if (len(item) and (not (mp & item)) and (not (self & item))): append(item) return self
'Parse a multi-path-string into nodes'
def __parse(self, value):
return value.split(',')
'Serialize this multi-path as string'
def __repr__(self):
return ','.join([str(p) for p in self.paths])
'Return this multi-path as list of node lists'
def as_list(self):
return [p.as_list() for p in self.paths if len(p)]
'The number of paths in this multi-path'
def __len__(self):
return len(self.paths)
'Check whether sequence is the start sequence of any of the paths in this multi-path (for de-duplication) @param sequence: sequence of node IDs (or path)'
def __and__(self, sequence):
for p in self.paths: if p.startswith(sequence): return 1 return 0
'Check whether sequence is contained in any of the paths (can also be used to check whether this multi-path contains a path to a particular node) @param sequence: the sequence (or node ID)'
def __contains__(self, sequence):
for p in self.paths: if (sequence in p): return 1 return 0
'Get all nodes from this path'
def nodes(self):
nodes = [] for p in self.paths: n = [i for i in p.nodes if (i not in nodes)] nodes.extend(n) return nodes
'Get all nodes from all paths @param paths: list of multi-paths'
@staticmethod def all_nodes(paths):
nodes = [] for p in paths: n = [i for i in p.nodes() if (i not in nodes)] nodes.extend(n) return nodes
'Normalize a path into a sequence of non-recurrent paths @param path: the path as a list of node IDs'
@staticmethod def __normalize(path):
seq = map(str, path) l = zip(seq, seq[1:]) if (not l): return [path] seq = S3MultiPath.__resolve(seq) pop = seq.pop paths = [] append = paths.append while len(seq): p = pop(0) s = (paths + seq) contained = False lp = len(p) for i in s: ...
'Resolve a sequence of vertices (=pairs of node IDs) into a sequence of non-recurrent paths @param seq: the vertex sequence'
@staticmethod def __resolve(seq):
resolve = S3MultiPath.__resolve if seq: head = seq[0] tail = seq[1:] tails = [] index = tail.index append = tails.append while (head in tail): pos = index(head) append(tail[:pos]) tail = tail[(pos + 1):] append(tail) ...
'Constructor'
def __init__(self, nodes=None):
self.nodes = [] if isinstance(nodes, S3MultiPath.Path): self.nodes = list(nodes.nodes) else: if (nodes is None): nodes = [] elif (type(nodes) is str): nodes = self.__parse(nodes) elif (not isinstance(nodes, (list, tuple))): nodes = [nodes] ...
'Append a node to this path @param node: the node'
def append(self, node=None):
if (node is None): return True n = str(node) if (not n): return True if (n not in self.nodes): self.nodes.append(n) return True return False
'Extend this path with a new vertex ancestors<-head, if this path ends at the head node @param head: the head node @param ancestors: the ancestor sequence'
def extend(self, head, ancestors=None):
if (ancestors is None): path = S3MultiPath.Path(head) head = path.first() ancestors = path.nodes[1:] last = self.last() if ((last is None) or (last == str(head))): append = self.append path = S3MultiPath.Path(ancestors) for i in path.nodes: if (not...
'Cut off the ancestor<-head vertex from this path, retaining the head node @param head: the head node @param ancestor: the ancestor node'
def cut(self, head, ancestor=None):
if (ancestor is not None): sequence = [str(head), str(ancestor)] pos = self.find(sequence) if (pos > 0): self.nodes = self.nodes[:pos] elif (str(head) == self.first()): self.nodes = [] return self
'Represent this path as a string'
def __repr__(self):
return ('[|%s|]' % '|'.join(self.nodes))
'Parse a string into nodes'
def __parse(self, value):
return value.strip().strip('[').strip(']').strip('|').split('|')
'Return the list of nodes'
def as_list(self):
return list(self.nodes)
'Get the node at position i'
def __getitem__(self, i):
try: return self.nodes.__getitem__(i) except IndexError: return None
'Get the first node in this path (the nearest ancestor)'
def first(self):
return self[0]
'Get the last node in this path (the most distant ancestor)'
def last(self):
return self[(-1)]
'Check whether this path contains sequence @param sequence: sequence of node IDs'
def __contains__(self, sequence):
if (self.find(sequence) != (-1)): return 1 else: return 0
'Get the number of nodes in this path'
def __len__(self):
return len(self.nodes)
'Find a sequence of node IDs in this path @param sequence: sequence of node IDs (or path) @return: position of the sequence (index+1), 0 if the path is empty, -1 if the sequence wasn\'t found'
def find(self, sequence):
path = S3MultiPath.Path(sequence) sequence = path.nodes nodes = self.nodes if (not sequence): return (-1) if (not nodes): return 0 (head, tail) = (sequence[0], sequence[1:]) pos = 0 l = len(tail) index = nodes.index while (head in nodes[pos:]): pos = (inde...
'Check whether this path starts with sequence @param sequence: sequence of node IDs (or path)'
def startswith(self, sequence):
sequence = S3MultiPath.Path(sequence).nodes if (self.nodes[0:len(sequence)] == sequence): return True else: return False
'Constructor'
def __init__(self):
self.ERROR = Storage(PIL_ERROR='PIL (Python Image Library) not installed, images cannot be embedded in the PDF report', RL_ERROR='Python needs the ReportLab module installed for PDF export') set_fonts(self)
'Export data as a PDF document @param resource: the resource @param attr: dictionary of keyword arguments, in s3_rest_controller passed through from the calling controller @keyword request: the S3Request @keyword method: "read" to not include a list view when no component is specified @keyword list_fields: fields to in...
def encode(self, resource, **attr):
if (not PILImported): current.session.warning = self.ERROR.PIL_ERROR if (not reportLabImported): current.session.error = self.ERROR.RL_ERROR redirect(URL(extension='')) r = self.r = attr.get('request', None) self.list_fields = attr.get('list_fields') self.pdf_groupby = attr.g...
'Function to convert the rules passed in to a flowable. The rules (for example) could be an rHeader callback @param rules: the HTML (web2py helper class) or a callback to produce it. The callback receives the S3Request as parameter. @param printable_width: the printable width @param styles: styles for HTML=>PDF convers...
def get_html_flowable(self, rules, printable_width, styles=None):
if callable(rules): r = self.r if (r is not None): representation = r.representation r.representation = 'html' try: html = rules(r) except: if current.response.s3.debug: raise else: import sys...
'Get a list of fields, if the list_fields attribute is provided then use that to extract the fields that are required, otherwise use the list of readable fields.'
def get_resource_flowable(self, resource, doc):
fields = self.list_fields if fields: list_fields = [f for f in fields if (f != 'id')] else: list_fields = [f.name for f in resource.readable_fields() if (((f.type != 'id') and (f.name != 'comments')) or (not self.pdf_hide_comments))] get_vars = Storage(current.request.get_vars) get_v...
'Set up the standard page templates'
def __init__(self, title='Sahana Eden', margin=((0.5 * inch), (0.3 * inch), (0.5 * inch), (0.3 * inch)), margin_inside=(0.0 * inch), paper_size=None, paper_alignment='Portrait'):
self.output = StringIO() self.defaultPage = paper_alignment if paper_size: self.paper_size = paper_size elif (current.deployment_settings.get_paper_size() == 'Letter'): self.paper_size = LETTER else: self.paper_size = A4 self.topMargin = margin[0] self.leftMargin = ma...
'Function to return the size a flowable will require'
def get_flowable_size(self, flowable):
if (not flowable): return (0, 0) if (not isinstance(flowable, list)): flowable = [flowable] w = 0 h = 0 for f in flowable: if f: size = f.wrap(self.printable_width, self.printable_height) if (size[0] > w): w = size[PDF_WIDTH] ...
'Helper function to calculate the various sizes of the page'
def calc_body_size(self, header_flowable, footer_flowable):
self._calc() self.height = self.pagesize[PDF_HEIGHT] self.width = self.pagesize[PDF_WIDTH] self.printable_width = (((self.width - self.leftMargin) - self.rightMargin) - self.insideMargin) self.printable_height = ((self.height - self.topMargin) - self.bottomMargin) header_size = self.get_flowable...
'Build the document using the flowables. Set up the page templates that the document can use'
def build(self, header_flowable, body_flowable, footer_flowable, canvasmaker=canvas.Canvas):
self.header_flowable = header_flowable self.body_flowable = body_flowable self.footer_flowable = footer_flowable self.calc_body_size(header_flowable, footer_flowable) showBoundary = 0 body_frame = Frame(self.leftMargin, (self.bottomMargin + self.footer_height), self.printable_width, self.body_he...
''
def add_page_decorators(self, canvas, doc):
if self.header_flowable: top = (self.bottomMargin + self.printable_height) for flow in self.header_flowable: height = self.get_flowable_size(flow)[PDF_HEIGHT] bottom = (top - height) flow.drawOn(canvas, self.leftMargin, bottom) top = bottom if self...
'Method to create a paragraph that may be inserted into the document @param text: The text for the paragraph @param append: If True then the paragraph will be stored in the document flow ready for generating the pdf. @return The paragraph This method can return the paragraph rather than inserting into the document. Thi...
def addParagraph(self, text, style=None, append=True):
if (text != ''): if (style == None): styleSheet = getSampleStyleSheet() style = styleSheet['Normal'] text = biDiText(text) para = Paragraph(text, style) if (append and self.body_flowable): self.body_flowable.append(para) return para ret...
'Add special styles to the text in a cell'
def cellStyle(self, style, cell):
if (style == '*GREY'): return [('TEXTCOLOR', cell, cell, colors.lightgrey)] elif (style == '*RED'): return [('TEXTCOLOR', cell, cell, colors.red)] return []
'Add special styles to the text in a table'
def addCellStyling(self, table, style):
row = 0 for line in table: col = 0 for cell in line: try: if cell.startswith('*'): (instruction, sep, text) = cell.partition(' ') style += self.cellStyle(instruction, (col, row)) table[row][col] = text ...
'Method to create a table object @param document: A S3PDF object @param raw_data: A list of rows @param rfields: A list of field selectors @param groupby: A field name that is to be used as a sub-group All the records that share the same pdf_groupby value will be clustered together @param hide_comments: Any comment fie...
def __init__(self, document, rfields, raw_data, groupby=None, hide_comments=False, autogrow=False, body_height=0):
if (current.deployment_settings.get_paper_size() == 'Letter'): self.paper_size = LETTER else: self.paper_size = A4 set_fonts(self) rtl = current.response.s3.rtl self.pdf = document self.rfields = rfields rdata = [] rappend = rdata.append for row in raw_data: d...
'Method to build the table. @return: A list of Table objects. Normally this will be a list with just one table object, but if the table needs to be split across columns then one object per page will be created.'
def build(self):
if self.pdf_groupby: data = self.group_data() data = ([self.labels] + data) elif (self.raw_data != None): data = ([self.labels] + self.raw_data) if ((not data) or (not data[0])): return None endCol = (len(self.labels) - 1) rowCnt = len(data) self.style = self.tabl...
''
def group_data(self):
groups = self.pdf_groupby.split(',') newData = [] data = self.raw_data level = 0 list_fields = self.list_fields for field in groups: level += 1 field = field.strip() i = 0 rowlength = len(list_fields) while (i < rowlength): if (list_fields[i] =...
'This will convert the S3PDFTABLE object to a format that can be used to add to a S3PDF document object. This is only used internally but could be used to generate a copy of a previously generated table'
def presentation(self):
content = [] currentPage = 0 totalPagesAcross = len(self.newColWidth) if ((self.autogrow == 'H') or (self.autogrow == 'B')): printable_width = self.pdf.printable_width newColWidth = [] for cols in self.newColWidth: col_width = 0 for col in cols: ...
'Internally used method to calculate the amount of space available on the width of a page.'
def getAvailableMarginSpace(self):
_pdf = self.pdf availableMarginSpace = ((_pdf.leftMargin + _pdf.rightMargin) - (2 * _pdf.MINIMUM_MARGIN_SIZE)) return availableMarginSpace
'Internally used method to adjust the document margins so that the table will fit into the available space'
def tweakMargin(self, tableWidth):
availableMarginSpace = self.getAvailableMarginSpace() currentOverlap = (tableWidth - self.tempDoc.printable_width) endCol = (len(self.labels) - 1) rowCnt = len(self.data) if (currentOverlap < availableMarginSpace): _pdf = self.pdf _pdf.leftMargin -= (currentOverlap / 2) _pdf....
'Internally used method to adjust the font size used so that the table will fit into the available space on the page.'
def tweakFont(self, tableWidth, newFontSize, colWidths):
adjustedWidth = ((tableWidth * newFontSize) / self.fontsize) if ((adjustedWidth - self.tempDoc.printable_width) < self.getAvailableMarginSpace()): for i in range(len(colWidths)): colWidths[i] *= (float(newFontSize) / float(self.fontsize)) self.newColWidth = [colWidths] self.f...
'Internally used method to tweak the formatting so that the table will fit into the available space on the page.'
def minorTweaks(self, tableWidth, colWidths):
if self.tweakMargin(tableWidth): return True originalFont = self.fontsize if self.tweakFont(tableWidth, (originalFont - 1), colWidths): return True if self.tweakFont(tableWidth, (originalFont - 2), colWidths): return True if self.tweakFont(tableWidth, (originalFont - 3), colW...
'Internally used method to adjust the table so that it will fit into the available space on the page. @return: True if it is able to perform minor adjustments and have the table fit in the page. False means that the table will need to be split across the columns.'
def tweakDoc(self, table):
tableWidth = 0 for colWidth in table._colWidths: tableWidth += colWidth colWidths = table._colWidths if (tableWidth > self.tempDoc.printable_width): colNo = 0 for label in self.labels: if (label.lower() == 'comments'): currentWidth = table._colWidths[c...
'Internally used method to split the table across columns so that it will fit into the available space on the page.'
def splitTable(self, tempTable):
colWidths = tempTable._colWidths rowHeights = tempTable._rowHeights total = 0 colNo = 0 colSplit = [] newColWidth = [] pageColWidth = [] for colW in colWidths: if ((colNo > 0) and ((total + colW) > self.tempDoc.printable_width)): colSplit.append(colNo) new...
'Internally used method to assign a style to the table @param startRow: The row from the data that the first data row in the table refers to. When a table is split the first row in the table (ignoring the label header row) will not always be the first row in the data. This is needed to align the two. Currently this par...
def tableStyle(self, startRow, rowCnt, endCol, colour_required=False):
font_name_bold = self.font_name_bold style = [('FONTNAME', (0, 0), ((-1), (-1)), self.font_name), ('FONTSIZE', (0, 0), ((-1), (-1)), self.fontsize), ('VALIGN', (0, 0), ((-1), (-1)), 'TOP'), ('LINEBELOW', (0, 0), (endCol, 0), 1, Color(0, 0, 0)), ('FONTNAME', (0, 0), (endCol, 0), font_name_bold)] sappend = st...
'Constructor @param pageWidth: the printable width @param exclude_class_list: list of classes for elements to skip @param styles: the styles dict from the caller'
def __init__(self, pageWidth, exclude_class_list=[], styles=None):
set_fonts(self) self.exclude_class_list = exclude_class_list self.pageWidth = pageWidth self.fontsize = 10 styleSheet = getSampleStyleSheet() self.plainstyle = styleSheet['Normal'] self.plainstyle.fontName = self.font_name self.plainstyle.fontSize = 9 self.boldstyle = deepcopy(styleS...
'Entry point for class'
def parse(self, html):
result = self.select_tag(html) return result
''
def select_tag(self, html, title=False):
if self.exclude_tag(html): return None if isinstance(html, TABLE): return self.parse_table(html) elif isinstance(html, A): return self.parse_a(html) elif isinstance(html, (P, H1, H2, H3, H4, H5, H6)): return self.parse_p(html) elif isinstance(html, IMG): retur...