def sendmail_record(self, record=None, thermo=None, storagekey=None,**kwargs): record.update(self.batch_parameters) as_pdf = self.batch_parameters['as_pdf'] to_address = templateReplace(self.mail_pars.getItem('to_address',''),record) subject = templateReplace(self.mail_pars.getItem('subject',''),record) cc_address = templateReplace(self.mail_pars.getItem('cc_address',''),record) htmlContent=templateReplace(self.compiledTemplate,record, safeMode=True,noneIsBlank=False, locale=self.page.locale, formats=self.compiledTemplate.getItem('main?formats'), masks=self.compiledTemplate.getItem('main?masks'), localizer=self.page.localizer) result = self.htmlMaker(htmlContent=htmlContent, filename='%s.html' %record['id'], record=record, thermo=thermo, pdf=as_pdf, **self.batch_parameters) if result: attachments = templateReplace(self.mail_pars.getItem('attachments',''),record) attachments = attachments.split(',') if attachments else [] body = None if as_pdf: attachments.append(result) body = '' else: body = result attachments = attachments or None self.send_one_email(to_address=to_address,cc_address=cc_address,subject=subject,body=body,attachments=attachments,_record_id=record[self.tblobj.pkey])
def sendMailTemplate(self, tpl, mailto, params, locale=None, **kwargs): locale = locale or self.locale localelang = locale.split('-')[0] mailtpl = self.getMailTemplate(tpl, locale=localelang) if mailtpl: subject = templateReplace(mailtpl['subject'], params) body = templateReplace(mailtpl['body'], params) self.application.sendmail(mailtpl['from_address'], mailto, subject, body) return 'mail sent'
def sendMailTemplate(self, tpl, mailto, params, locale=None, **kwargs): locale = locale or self.locale localelang = locale.split("-")[0] mailtpl = self.getMailTemplate(tpl, locale=localelang) if mailtpl: subject = templateReplace(mailtpl["subject"], params) body = templateReplace(mailtpl["body"], params) self.application.sendmail(mailtpl["from_address"], mailto, subject, body) return "mail sent"
def print_record(self, record=None, thermo=None, storagekey=None, **kwargs): record.update(self.batch_parameters) htmlContent = templateReplace( self.compiledTemplate, record, safeMode=True, noneIsBlank=False, locale=self.page.locale, formats=self.compiledTemplate.getItem('main?formats'), masks=self.compiledTemplate.getItem('main?masks'), dtypes=self.compiledTemplate.getItem('main?dtypes'), localizer=self.page.localizer, urlformatter=self.page.externalUrl) result = self.htmlMaker(htmlContent=htmlContent, filename='%s.html' % record['id'], record=record, thermo=thermo, pdf=self.pdf_make, **self.batch_parameters) if result: self.storeResult(storagekey, result, record, filepath=self.htmlMaker.filepath)
def te_renderTemplate(self, templateBuilder, record_id=None, extraData=None, locale=None,contentOnly=False,**kwargs): record = Bag() if record_id: record = templateBuilder.data_tblobj.record(pkey=record_id, virtual_columns=templateBuilder.virtual_columns).output('bag') else: record = templateBuilder.data_tblobj.record(pkey='*sample*',ignoreMissing=True, virtual_columns=templateBuilder.virtual_columns).output('sample') if extraData: record.update(extraData) locale = locale or templateBuilder.locale formats = templateBuilder.formats or dict() masks = templateBuilder.masks or dict() editcols = templateBuilder.editcols or dict() df_templates = templateBuilder.df_templates or dict() dtypes = templateBuilder.dtypes or dict() record.setItem('_env_', Bag(self.db.currentEnv)) #record.setItem('_template_', templateBuilder.doctemplate_info) htmlContent = templateReplace(templateBuilder.doctemplate,record, safeMode=True,noneIsBlank=False,locale=locale, formats=formats,masks=masks,editcols=editcols,df_templates=df_templates, dtypes=dtypes,localizer=self.localizer, urlformatter=self.externalUrl) if contentOnly: return htmlContent body = templateBuilder(htmlContent=htmlContent, record=record,page_debug='silver',**kwargs) return body
def te_renderChunk(self, record_id=None, template_address=None, templates=None, template_id=None, **kwargs): data, dataInfo = self.loadTemplate(template_address=template_address, asSource=True) if not data: return '<div class="chunkeditor_emptytemplate">Template not yet created</div>', dataInfo compiled = data['compiled'] result = Bag() if not compiled: content = data['content'] record = self.db.table( template_address.split(':')[0]).recordAs(record_id) result['rendered'] = templateReplace(content, record) result['template_data'] = data return result, dataInfo tplbuilder = self.te_getTemplateBuilder(compiled=compiled, templates=templates) result['rendered'] = self.te_renderTemplate( tplbuilder, record_id=record_id, extraData=Bag(dict(host=self.request.host)), contentOnly=True) result['template_data'] = data return result, dataInfo
def sendMailTemplateMany(self, tpl, mailto_param, locale_param, params_list, **kwargs): mailtpldict = {} send_errors = [] for params in params_list: locale = params.get(locale_param) or self.locale mailtpl = mailtpldict.get(locale) if not mailtpl: mailtpl = self.getMailTemplate(tpl, locale=locale) mailtpldict[locale] = mailtpl try: subject = templateReplace(mailtpl["subject"], params) body = templateReplace(mailtpl["body"], params) self.application.sendmail(mailtpl["from_address"], params[mailto_param], subject, body) except: send_errors.append(params[mailto_param]) return send_errors
def templateReplaceRow(self, row, totals=False): if not row: return '' if totals or row.get('_gnr_tbl_footer'): row_template = '<tfoot>%s</tfoot>' % (self.row_template_totals or self.row_template) else: row_template = self.row_template return gnrstring.templateReplace(row_template, row, safeMode=True)# per debug
def sendmail_record(self, record=None, thermo=None, storagekey=None, **kwargs): record.update(self.batch_parameters) as_pdf = self.batch_parameters['as_pdf'] to_address = templateReplace(self.mail_pars.getItem('to_address', ''), record) subject = templateReplace(self.mail_pars.getItem('subject', ''), record) cc_address = templateReplace(self.mail_pars.getItem('cc_address', ''), record) htmlContent = templateReplace( self.compiledTemplate, record, safeMode=True, noneIsBlank=False, locale=self.page.locale, formats=self.compiledTemplate.getItem('main?formats'), masks=self.compiledTemplate.getItem('main?masks'), localizer=self.page.localizer) result = self.htmlMaker(htmlContent=htmlContent, filename='%s.html' % record['id'], record=record, thermo=thermo, pdf=as_pdf, **self.batch_parameters) if result: attachments = templateReplace( self.mail_pars.getItem('attachments', ''), record) attachments = attachments.split(',') if attachments else [] body = None if as_pdf: attachments.append(result) body = '' else: body = result attachments = attachments or None self.send_one_email(to_address=to_address, cc_address=cc_address, subject=subject, body=body, attachments=attachments, _record_id=record[self.tblobj.pkey])
def test_templateReplace(): """docstring for test_templateReplace""" assert gnrstring.templateReplace( '$foo loves $bar but she loves $aux and not $foo', { 'foo': 'John', 'bar': 'Sandra', 'aux': 'Steve' }) == 'John loves Sandra but she loves Steve and not John'
def te_compileBagForm(self,table=None,sourcebag=None,varsbag=None,parametersbag=None,record_id=None,templates=None): result = Bag() varsdict = dict() for varname,fieldpath in varsbag.digest('#v.varname,#v.fieldpath'): varsdict[varname] = '$%s' %fieldpath for k,v in sourcebag.items(): if v: result[k] = templateReplace(v, varsdict, True,False,urlformatter=self.externalUrl) return result
def templateReplaceRow(self, row, totals=False): if not row: return '' if totals or row.get('_gnr_tbl_footer'): row_template = '<tfoot>%s</tfoot>' % (self.row_template_totals or self.row_template) else: row_template = self.row_template return gnrstring.templateReplace(row_template, row, safeMode=True) # per debug
def sendMailTemplateMany(self, tpl, mailto_param, locale_param, params_list, **kwargs): mailtpldict = {} send_errors = [] for params in params_list: locale = params.get(locale_param) or self.locale mailtpl = mailtpldict.get(locale) if not mailtpl: mailtpl = self.getMailTemplate(tpl, locale=locale) mailtpldict[locale] = mailtpl try: subject = templateReplace(mailtpl['subject'], params) body = templateReplace(mailtpl['body'], params) self.application.sendmail(mailtpl['from_address'], params[mailto_param], subject, body) except: send_errors.append(params[mailto_param]) return send_errors
def openPage(self): html = """ <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <style type="text/css"> $all_css </style> <script type="text/javascript"> var genro = window.parent.genro; </script> <title>$title</title> </head> <body class="$bodyclasses tableWindow"> $header <table class="full_page $tableclass" id="maintable"> """ all_css = [] self.page.theme = getattr(self.page, 'theme', 'tundra') styles = self.page.get_css_genro() print_styles = styles.pop('print', []) for cssmedia, cssnames in styles.items(): for cssname in cssnames: all_css.append('@import url("%s") %s;' % (cssname, cssmedia)) for cssname in print_styles: all_css.append('@import url("%s") print;' % (cssname, )) cssname = self.page.getResourceUri('html_tables/html_tables', 'css') all_css.append('@import url("%s") %s;' % (cssname, 'all')) cssname = self.page.getResourceUri('html_tables/html_tables_print', 'css') all_css.append('@import url("%s") %s;' % (cssname, 'print')) css_path, css_media_path = self.page.get_css_path() for cssname in css_path: all_css.append('@import url("%s");' % cssname) for cssmedia, cssnames in css_media_path.items(): for cssname in cssnames: all_css.append('@import url("%s") %s;' % (cssname, cssmedia)) html = gnrstring.templateReplace( html, dict(all_css='\n'.join(all_css), bodyclasses=self.page.get_bodyclasses(), title=self.title, header=self.header, tableclass=self.tableclass)) return html
def do(self): thermo_s = dict(line_code='selection', message='sending') smspars = dict() smspars.update(self.sms_preference.asDict(True)) pkeys = self.get_selection_pkeys() for pkey in self.btc.thermo_wrapper(pkeys, **thermo_s): smspars['data'] = templateReplace(value, datasource) self.doctemplate_tbl.renderTemplate(self.htmlBuilder, record_id=pkey) smspars['receiver'] = record[self.batch_parameters.get('receiver')] self.sms_handler.sendsms(**smspars)
def renderTemplate(self, templateBuilder, record_id=None, extraData=None): record = Bag() if record_id: record = templateBuilder.data_tblobj.record(pkey=record_id, virtual_columns=templateBuilder.virtual_columns).output('bag') if extraData: record.update(extraData) record.setItem('_env_', Bag(self.db.currentEnv)) record.setItem('_template_', templateBuilder.doctemplate_info) templateBuilder.record = record return templateBuilder(htmlContent=templateReplace(templateBuilder.doctemplate, record, True))
def sendUserTemplateMail(self,record_id=None,letterhead_id=None,template_id=None,table=None,template_code=None,attachments=None,**kwargs): if template_id: tpl,table = self.parent.db.table('adm.userobject').readColumns(pkey=template_id,columns='$data,$tbl',bagFields=True) elif template_code and table: tpl = self.parent.db.table('adm.userobject').readColumns(where='$tbl=:tb AND $code=:tc AND $objtype=:ot', ot='template',tc=template_code,tb=table, columns='$data',bagFields=True) tpl = Bag(tpl) metadata = tpl['metadata'] compiled = tpl['compiled'] email_compiled = metadata['email_compiled'] htmlbuilder = TableTemplateToHtml(table=self.parent.db.table(table)) html_text = htmlbuilder(record=record_id,template=compiled,letterhead_id=letterhead_id or metadata['default_letterhead']) to_address = templateReplace(email_compiled.getItem('to_address',''),htmlbuilder.record) subject = templateReplace(email_compiled.getItem('subject',''),htmlbuilder.record) cc_address = templateReplace(email_compiled.getItem('cc_address',''),htmlbuilder.record) bcc_address = templateReplace(email_compiled.getItem('bcc_address',''),htmlbuilder.record) from_address = templateReplace(email_compiled.getItem('from_address',''),htmlbuilder.record) attachments = attachments or templateReplace(email_compiled.getItem('attachments',''),htmlbuilder.record) if attachments and isinstance(attachments,basestring): attachments = attachments.replace('\n',',').split(',') assert to_address,'Missing email address' kwargs.setdefault('html',True) self.sendmail(to_address=to_address,subject=subject,cc_address=cc_address, bcc_address=bcc_address, from_address=from_address, body=html_text,attachments=attachments,**kwargs)
def renderTemplate(self, templateBuilder, record_id=None, extraData=None): record = Bag() if record_id: record = templateBuilder.data_tblobj.record( pkey=record_id, virtual_columns=templateBuilder.virtual_columns).output('bag') if extraData: record.update(extraData) record.setItem('_env_', Bag(self.db.currentEnv)) record.setItem('_template_', templateBuilder.doctemplate_info) templateBuilder.record = record return templateBuilder(htmlContent=templateReplace( templateBuilder.doctemplate, record, True))
def contentFromTemplate(self,record,template,locale=None,**kwargs): virtual_columns=None if isinstance(template,Bag): kwargs['locale'] = locale or template.getItem('main?locale') kwargs['masks'] = template.getItem('main?masks') kwargs['formats'] = template.getItem('main?formats') kwargs['df_templates'] = template.getItem('main?df_templates') kwargs['dtypes'] = template.getItem('main?dtypes') virtual_columns = template.getItem('main?virtual_columns') self.record = self.tblobj.recordAs(record,virtual_columns=virtual_columns) return templateReplace(template,self.record, safeMode=True,noneIsBlank=False, localizer=self.db.application.localizeText,urlformatter=self.site.externalUrl, **kwargs)
def contentFromTemplate(self,record,template,locale=None,**kwargs): virtual_columns=None if isinstance(template,Bag): kwargs['locale'] = locale or template.getItem('main?locale') kwargs['masks'] = template.getItem('main?masks') kwargs['formats'] = template.getItem('main?formats') kwargs['df_templates'] = template.getItem('main?df_templates') kwargs['dtypes'] = template.getItem('main?dtypes') virtual_columns = template.getItem('main?virtual_columns') self.record = self.tblobj.recordAs(record,virtual_columns=virtual_columns) return templateReplace(template,self.record, safeMode=True,noneIsBlank=False, localizer=self.db.application.localizer,urlformatter=self.site.externalUrl, **kwargs)
def openPage(self): html = """ <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <style type="text/css"> $all_css </style> <script type="text/javascript"> var genro = window.parent.genro; </script> <title>$title</title> </head> <body class="$bodyclasses tableWindow"> $header <table class="full_page $tableclass" id="maintable"> """ all_css = [] self.page.theme = getattr(self.page, 'theme', 'tundra') styles = self.page.get_css_genro() print_styles = styles.pop('print', []) for cssmedia, cssnames in styles.items(): for cssname in cssnames: all_css.append('@import url("%s") %s;' % (cssname, cssmedia)) for cssname in print_styles: all_css.append('@import url("%s") print;' % (cssname, )) cssname = self.page.getResourceUri('html_tables/html_tables', 'css') all_css.append('@import url("%s") %s;' % (cssname, 'all')) cssname = self.page.getResourceUri('html_tables/html_tables_print', 'css') all_css.append('@import url("%s") %s;' % (cssname, 'print')) css_path, css_media_path = self.page.get_css_path() for cssname in css_path: all_css.append('@import url("%s");' % cssname) for cssmedia, cssnames in css_media_path.items(): for cssname in cssnames: all_css.append('@import url("%s") %s;' % (cssname, cssmedia)) html = gnrstring.templateReplace(html, dict(all_css='\n'.join(all_css), bodyclasses=self.page.get_bodyclasses(), title=self.title, header=self.header, tableclass=self.tableclass)) return html
class SmsMobyt(GnrBaseService): def __init__(self, parent, username=None, password=None, url=None, auth=None, sender=None): self.parent = parent self.username = username self.password = password self.url = url self.auth = auth self.sender = sender def sendsms_template(self, receiver=None, sender=None, opcode=None, data=None, quality=None, messageId=None, batchId=None, urlbatch=None, async=False, **kwargs): def get_templated(field): value = datasource.get(field) if value: return templateReplace(value, datasource) receiver = receiver or get_templated('receiver') sender = sender or get_templated('sender') opcode = opcode or get_templated('opcode') sender = sender or get_templated('sender') quality = quality or get_templated('quality') messageId = messageId or get_templated('messageId') urlbatch = urlbatch or get_templated('urlbatch') data = data or get_templated('data') data = templateReplace(data, datasource) self.sendsms(receiver=receiver, sender=sender, opcode=opcode, data=data, quality=quality, messageId=messageId, batchId=batchId, urlbatch=urlbatch, async=async)
def te_renderTemplate(self, templateBuilder, record_id=None, extraData=None, locale=None, contentOnly=False, **kwargs): record = Bag() if record_id: record = templateBuilder.data_tblobj.record( pkey=record_id, virtual_columns=templateBuilder.virtual_columns).output('bag') else: record = templateBuilder.data_tblobj.record( pkey='*sample*', ignoreMissing=True, virtual_columns=templateBuilder.virtual_columns).output( 'sample') if extraData: record.update(extraData) locale = locale or templateBuilder.locale formats = templateBuilder.formats or dict() masks = templateBuilder.masks or dict() editcols = templateBuilder.editcols or dict() df_templates = templateBuilder.df_templates or dict() dtypes = templateBuilder.dtypes or dict() record.setItem('_env_', Bag(self.db.currentEnv)) #record.setItem('_template_', templateBuilder.doctemplate_info) htmlContent = templateReplace(templateBuilder.doctemplate, record, safeMode=True, noneIsBlank=False, locale=locale, formats=formats, masks=masks, editcols=editcols, df_templates=df_templates, dtypes=dtypes, localizer=self.localizer, urlformatter=self.externalUrl) if contentOnly: return htmlContent body = templateBuilder(htmlContent=htmlContent, record=record, page_debug='silver', **kwargs) return body
def te_renderChunk(self, record_id=None,template_address=None,templates=None,template_id=None,**kwargs): data,dataInfo = self.loadTemplate(template_address=template_address,asSource=True) if not data: return '<div class="chunkeditor_emptytemplate">Template not yet created</div>',dataInfo compiled = data['compiled'] result = Bag() if not compiled: content = data['content'] record = self.db.table(template_address.split(':')[0]).recordAs(record_id) result['rendered'] = templateReplace(content,record) result['template_data'] = data return result,dataInfo tplbuilder = self.te_getTemplateBuilder(compiled=compiled, templates=templates) result['rendered'] = self.te_renderTemplate(tplbuilder, record_id=record_id, extraData=Bag(dict(host=self.request.host)),contentOnly=True) result['template_data'] = data return result,dataInfo
def print_record(self, record=None, thermo=None, storagekey=None,**kwargs): record.update(self.batch_parameters) htmlContent=templateReplace(self.compiledTemplate,record, safeMode=True,noneIsBlank=False, locale=self.page.locale, formats=self.compiledTemplate.getItem('main?formats'), masks=self.compiledTemplate.getItem('main?masks'), dtypes= self.compiledTemplate.getItem('main?dtypes'), localizer=self.page.localizer, urlformatter=self.page.externalUrl) result = self.htmlMaker(htmlContent=htmlContent, filename='%s.html' %record['id'], record=record, thermo=thermo, pdf=self.pdf_make, **self.batch_parameters) if result: self.storeResult(storagekey, result, record, filepath=self.htmlMaker.filepath)
def te_compileBagForm(self, table=None, sourcebag=None, varsbag=None, parametersbag=None, record_id=None, templates=None): result = Bag() varsdict = dict() for varname, fieldpath in varsbag.digest('#v.varname,#v.fieldpath'): varsdict[varname] = '$%s' % fieldpath for k, v in sourcebag.items(): if v: result[k] = templateReplace(v, varsdict, True, False, urlformatter=self.externalUrl) return result
def doTable(self): html = [] openpage = gnrstring.templateReplace('<table class="full_page $tableclass" id="maintable">', dict(tableclass=self.tableclass)) html.append(openpage) if hasattr(self.source, 'serverfetch'): rowsource = self.fromServerCursor(50) else: rowsource = self.fromList() html.extend(rowsource) html.append('</tbody>') if self.tot_cb: html.append(self.buildTableRow(self.tot_cb(), totals=True)) html.append('</table>') return '\n'.join(html)
def doTable(self): html = [] openpage = gnrstring.templateReplace( '<table class="full_page $tableclass" id="maintable">', dict(tableclass=self.tableclass)) html.append(openpage) if hasattr(self.source, 'serverfetch'): rowsource = self.fromServerCursor(50) else: rowsource = self.fromList() html.extend(rowsource) html.append('</tbody>') if self.tot_cb: html.append(self.buildTableRow(self.tot_cb(), totals=True)) html.append('</table>') return '\n'.join(html)
def recordCaption(self, record, newrecord=False, rowcaption=None): """add??? :param record: add??? :param newrecord: boolean. add???. Default value is ``False`` :param rowcaption: add???. Default value is ``None`` :returns: add??? """ if newrecord: return '!!New %s' % self.name_long.replace('!!', '') else: fields, mask = self.rowcaptionDecode(rowcaption) if not fields: return '' fields = [f.lstrip('$') for f in fields] if not isinstance(record, Bag): fields = [self.db.colToAs(f) for f in fields] cols = [(c, gnrstring.toText(record[c])) for c in fields] if '$' in mask: caption = gnrstring.templateReplace(mask, dict(cols)) else: caption = mask % tuple([v for k, v in cols]) return caption
def te_compileTemplate(self,table=None,datacontent=None,varsbag=None,parametersbag=None,record_id=None,templates=None,template_id=None): result = Bag() formats = dict() editcols = dict() masks = dict() df_templates = dict() dtypes = dict() columns = [] virtual_columns = [] varsdict = dict() if varsbag: tplvars = varsbag.digest('#v.varname,#v.fieldpath,#v.virtual_column,#v.required_columns,#v.format,#v.mask,#v.editable,#v.df_template,#v.dtype') for varname,fldpath,virtualcol,required_columns,format,mask,editable,df_template,dtype in tplvars: fk='' if format: fk=varname formats[varname] = format if mask: fk=varname masks[varname] = mask if editable: fk=varname editcols[varname] = editable if df_template: fk=varname df_templates[varname] = df_template if dtype: dtypes[varname] = dtype if fk: fk='^%s'%fk varsdict[varname] = '$%s%s' %(fldpath,fk) columns.append(fldpath) if virtualcol: virtual_columns.append(fldpath) if required_columns: prefix = '.'.join(fldpath.split('.')[0:-1]) for c in required_columns.split(','): if not c in virtual_columns: virtual_columns.append('%s.%s' %(prefix,c.replace('$','')) if prefix else c) if parametersbag: tplpars = parametersbag.digest('#v.code,#v.format,#v.mask') for code,format,mask in tplpars: formats[code] = format masks[code] = mask template = templateReplace(datacontent, varsdict, True,False,conditionalMode=False) compiled = Bag() cmain = template if HT: doc = HT.parse(StringIO(template)).getroot() htmltables = doc.xpath('//table') for t in htmltables: attributes = t.attrib if 'row_datasource' in attributes: subname = attributes['row_datasource'] tbody = t.xpath('tbody')[0] tbody_lastrow = tbody.getchildren()[-1] tbody.replace(tbody_lastrow,HT.etree.Comment('TEMPLATEROW:$%s' %subname)) subtemplate=HT.tostring(tbody_lastrow).replace('%s.'%subname,'').replace('%24','$') compiled.setItem(subname.replace('.','_'),subtemplate) cmain = TEMPLATEROW.sub(lambda m: '\n%s\n'%m.group(1),HT.tostring(doc).replace('%24','$')) compiled.setItem('main', cmain, maintable=table,locale=self.locale,virtual_columns=','.join(virtual_columns), columns=','.join(columns),formats=formats,masks=masks,editcols=editcols,df_templates=df_templates,dtypes=dtypes) result.setItem('compiled',compiled) if record_id: result.setItem('preview',self.te_getPreview(compiled=compiled,record_id=record_id,templates=templates,template_id=template_id)) return result
def fillLetterheadSourceData(self, node, **kwargs): if node.label == 'html': node.value = templateReplace(node.value, self.letterhead_sourcedata)
def get_templated(field): value = datasource.getItem('_meta_.%s' % field) if not value: value = datasource.getItem(field) if value: return templateReplace(value, datasource)
def prepareRow(self,row): self.rowCell(value='%s::HTML' %templateReplace(self.row_tpl,Bag(self.currRowDataNode)))
def test_templateReplace(): """docstring for test_templateReplace""" assert gnrstring.templateReplace('$foo loves $bar but she loves $aux and not $foo', {'foo': 'John', 'bar': 'Sandra', 'aux': 'Steve'}) == 'John loves Sandra but she loves Steve and not John'
def get_templated(field): value = datasource.get(field) if value: return templateReplace(value, datasource)
class MailHandler(GnrBaseService): """A class for mail management.""" service_name = 'mail' def __init__(self, parent=None): self.parent = parent self.smtp_accounts = {} self.default_smtp_account = None self.pop_accounts = {} self.default_pop_account = None self.imap_accounts = {} self.default_imap_account = None def set_smtp_account(self, name, from_address=None, smtp_host=None, username=None, password=None, port=None, ssl=False, default=False): """Set the smtp account :param name: the account's name :param from_address: the address that will appear in the recipients from field. Default value is ``None`` :param smtp_host: the smtp host to send this email. Default value is ``None`` :param username: add???. Default value is ``None`` :param password: the username's password (if a username is required for authentication). Default value is ``None`` :param port: if a non standard port is used then it can be overridden. Default value is ``None`` :param ssl: boolean. If ``True``, attempt to use the ssl port. Else standard smtp port is used. Default value is ``None`` :param default: boolean. add???. Default value is ``False`` """ self.smtp_accounts[name] = dict(from_address=from_address, smtp_host=smtp_host, username=username, password=password, port=port, ssl=ssl) if default: self.default_smtp_account = name def set_smtp_default_account(self, name): """Allow to use the saved account parameters for the subsequent SMTP mails :param name: the default account's name """ self.default_smtp_account = name def set_pop_default_account(self, name): """Allow to use the saved account parameters for the subsequent POP mails :param name: the default account's name """ self.default_pop_account = name def set_imap_default_account(self, name): """Allow to use the saved account parameters for the subsequent IMAP mails :param name: the default account's name """ self.default_imap_account = name def get_account_params(self, account=None, from_address=None, smtp_host=None, port=None, user=None, password=None, ssl=False, tls=False, **kwargs): """Set the account parameters :param account: if an account has been defined previously with :meth:`set_smtp_account` then this account can be used instead of having to repeat all the mail parameters contained. Default value is ``None`` :param from_address: the address that will appear in the recipients from field. Default value is ``None`` :param smtp_host: the smtp host to send this email. Default value is ``None`` :param port: if a non standard port is used then it can be overridden. Default value is ``None`` :param user: if a username is required for authentication. Default value is ``None`` :param password: the username's password (if a username is required for authentication). Default value is ``None`` :param ssl: boolean. If ``True``, attempt to use the ssl port. Else standard smtp port is used. Default value is ``None`` :param tls: boolean. Allow to communicate with an smtp server. Default value is ``False``. You may choose three ways: 1. no encryption 2. ssl -> all data is encrypted on a ssl layer 3. tls -> server and client begin communitation in a unsecure way and after a starttls command they start to encrypt data (this is the way you use to connect to gmail smtp) :returns: the account parameters """ account = account or self.default_smtp_account if account: account_params = self.smtp_accounts[account] else: account_params = dict(smtp_host=smtp_host, port=port, user=user, password=password, ssl=ssl, tls=tls, from_address=from_address) return account_params def get_smtp_connection(self, account=None, smtp_host=None, port=None, user=None, password=None, ssl=False, tls=False, **kwargs): """Get the smtp connection :param account: if an account has been defined previously with :meth:`set_smtp_account` then this account can be used instead of having to repeat all the mail parameters contained. Default value is ``None`` :param smtp_host: the smtp host to send this email. Default value is ``None`` :param port: if a non standard port is used then it can be overridden. Default value is ``None`` :param user: if a username is required for authentication. Default value is ``None`` :param password: the username's password (if a username is required for authentication). Default value is ``None`` :param ssl: boolean. If ``True``, attempt to use the ssl port. Else standard smtp port is used. Default value is ``None`` :param tls: allow to communicate with an smtp server. Default value is ``False``. You may choose three ways: 1. no encryption 2. ssl -> all data is encrypted on a ssl layer 3. tls -> server and client begin communitation in a unsecure way and after a starttls command they start to encrypt data (this is the way you use to connect to gmail smtp) :returns: the smtp connection """ if ssl: smtp = getattr(smtplib, 'SMTP_SSL') else: smtp = getattr(smtplib, 'SMTP') if port: smtp_connection = smtp(host=str(smtp_host), port=str(port)) else: smtp_connection = smtp(host=smtp_host) if tls: smtp_connection.starttls() if user: smtp_connection.login(user, password) return smtp_connection def handle_addresses(self, from_address=None, to_address=None, multiple_mode=None): """Handle the mail addresses :param from_address: the address that will appear in the recipients from field. Default value is ``None`` :param to_address: address where the email will be sent. Default value is ``None`` :param multiple_mode: add???. Default value is ``None`` :returns: lists of addresses """ cc = bcc = None if isinstance(to_address, basestring): to_address = [address.strip() for address in to_address.replace(';', ',').split(',') if address] multiple_mode = (multiple_mode or '').lower().strip() if multiple_mode == 'to': to = [','.join(to_address)] elif multiple_mode == 'bcc': # jbe changed this from ccn to bcc to = [from_address] bcc = ','.join(to_address) elif multiple_mode == 'cc': to = [from_address] cc = ','.join(to_address) else: to = to_address return to, cc, bcc def build_base_message(self, subject, body, attachments=None, html=None, charset=None): """Add??? :param subject: add??? :param body: body of the email. If you pass ``html=True`` attribute, then you can pass in the body the html tags :param attachments: path of the attachment to be sent with the email. Default value is ``None`` :param html: add???. Default value is ``None`` :param charset: a different charser may be defined by its standard name. Default value is ``None``. :returns: the message """ charset = charset or 'us-ascii' # us-ascii is the email default, gnr default is utf-8. # This is used to prevent explicit "charset = None" to be passed attachments = attachments or [] if not html and not attachments: msg = MIMEText(body, 'text', charset) msg['Subject'] = subject return msg if html: msg = MIMEMultipart('alternative') else: msg = MIMEMultipart() msg['Subject'] = subject for attachment_path in attachments: mime_type = mimetypes.guess_type(attachment_path)[0] mime_family, mime_subtype = mime_type.split('/') attachment_file = open(attachment_path, 'rb') email_attachment = mime_mapping[mime_family](attachment_file.read(), mime_subtype) msg.add_header('content-disposition', 'attachment', filename=os.path.basename(attachment_path)) msg.attach(email_attachment) attachment_file.close() if html: msg.attach(MIMEText(clean_and_unescape(body), 'text', charset)) msg.attach(MIMEText(body, 'html', charset)) else: msg.attach(MIMEText(body, 'text', charset)) return msg def sendmail_template(self, datasource, to_address=None, cc_address=None, bcc_address=None, subject=None, from_address=None, body=None, attachments=None, account=None, smtp_host=None, port=None, user=None, password=None, ssl=False, tls=False, html=False, charset='utf-8', async=False, **kwargs): """Add??? :param datasource: add??? :param to_address: address where the email will be sent. Default value is ``None`` :param cc_address: can be a comma deliminated str of email addresses or a list or tuple. Default value is ``None`` :param bcc_address: can be a comma deliminated str of email addresses or a list or tuple. Default value is ``None`` :param subject: add???. Default value is ``None`` :param from_address: the address that will appear in the recipients from field. Default value is ``None`` :param body: body of the email. If you pass ``html=True`` attribute, then you can pass in the body the html tags. Default value is ``None`` :param attachments: path of the attachment to be sent with the email. Default value is ``None`` :param account: if an account has been defined previously with :meth:`set_smtp_account` then this account can be used instead of having to repeat all the mail parameters contained. Default value is ``None`` :param smtp_host: the smtp host to send this email. Default value is ``None`` :param port: if a non standard port is used then it can be overridden. Default value is ``None`` :param user: if a username is required for authentication. Default value is ``None`` :param password: the username's password (if a username is required for authentication). Default value is ``None`` :param ssl: boolean. If ``True``, attempt to use the ssl port. Else standard smtp port is used. Default value is ``None`` :param tls: allow to communicate with an smtp server. Default value is ``False``. You may choose three ways: 1. no encryption 2. ssl -> all data is encrypted on a ssl layer 3. tls -> server and client begin communitation in a unsecure way and after a starttls command they start to encrypt data (this is the way you use to connect to gmail smtp) :param html: boolean. If ``True``, html tags can be used in the body of the email. Appropriate headers are attached. The default value is ``False``. :param charset: a different charser may be defined by its standard name. Default value is ``utf-8``. :param async: boolean. If ``True``, then a separate process is spawned to send the email and control is returned immediately to the calling function. The default value is ``False``. """ def get_templated(field): value = datasource.get(field) if value: return templateReplace(value, datasource) to_address = to_address or get_templated('to_address') cc_address = cc_address or get_templated('cc_address') bcc_address = bcc_address or get_templated('bcc_address') from_address = from_address or get_templated('from_address') subject = subject or get_templated('subject') body = body or get_templated('body') body = templateReplace(body, datasource) self.sendmail(to_address, subject=subject, body=body, cc_address=cc_address, bcc_address=bcc_address, attachments=attachments, account=account, from_address=from_address, smtp_host=smtp_host, port=port, user=user, password=password, ssl=ssl, tls=tls, html=html, charset=charset, async=async)
def prepareRow(self, row): self.rowCell(value='%s::HTML' % templateReplace(self.row_tpl, Bag(self.currRowDataNode)))
def fillLetterheadSourceData(self,node,**kwargs): if node.label=='html': node.value = templateReplace(node.value,self.letterhead_sourcedata)
def te_compileTemplate(self, table=None, datacontent=None, varsbag=None, parametersbag=None, record_id=None, templates=None, template_id=None, **kwargs): result = Bag() formats = dict() editcols = dict() masks = dict() df_templates = dict() dtypes = dict() columns = [] virtual_columns = [] varsdict = dict() if varsbag: tplvars = varsbag.digest( '#v.varname,#v.fieldpath,#v.virtual_column,#v.required_columns,#v.format,#v.mask,#v.editable,#v.df_template,#v.dtype,#v.fieldname' ) for varname, fldpath, virtualcol, required_columns, format, mask, editable, df_template, dtype, fieldname in tplvars: varname = varname or fieldname fldpath = fldpath or varname fk = '' if format: fk = varname formats[varname] = format if mask: fk = varname masks[varname] = mask if editable: fk = varname editcols[varname] = editable if df_template: fk = varname df_templates[varname] = df_template if dtype: dtypes[varname] = dtype if fk: fk = '^%s' % fk if table: varsdict[varname] = '$%s%s' % (fldpath, fk) columns.append((varsdict.get(varname) or fldpath).replace('$@', '@')) if virtualcol: virtual_columns.append(fldpath) if required_columns: prefix = '.'.join(fldpath.split('.')[0:-1]) for c in required_columns.split(','): if not c in virtual_columns: virtual_columns.append( '%s.%s' % (prefix, c.replace('$', '')) if prefix else c) if parametersbag: tplpars = parametersbag.digest('#v.code,#v.format,#v.mask') for code, format, mask in tplpars: formats[code] = format masks[code] = mask template = templateReplace(datacontent, varsdict, True, False, conditionalMode=False) compiled = Bag() cmain = template if HT: doc = HT.parse(StringIO(template)).getroot() htmltables = doc.xpath('//table') for t in htmltables: attributes = t.attrib if 'row_datasource' in attributes: subname = attributes['row_datasource'] tbody = t.xpath('tbody')[0] tbody_lastrow = tbody.getchildren()[-1] tbody.replace( tbody_lastrow, HT.etree.Comment('TEMPLATEROW:$%s' % subname)) subtemplate = HT.tostring(tbody_lastrow).replace( '%s.' % subname, '').replace('%24', '$') compiled.setItem(subname.replace('.', '_'), subtemplate) cmain = TEMPLATEROW.sub(lambda m: '\n%s\n' % m.group(1), HT.tostring(doc).replace('%24', '$')) compiled.setItem('main', cmain, maintable=table, locale=self.locale, virtual_columns=','.join(virtual_columns), columns=','.join(columns), formats=formats, masks=masks, editcols=editcols, df_templates=df_templates, dtypes=dtypes) result.setItem('compiled', compiled) if record_id: result.setItem( 'preview', self.te_getPreview(compiled=compiled, record_id=record_id, templates=templates, template_id=template_id)) return result