def _storage(self): context = get_context(self) if not hasattr(context, '_inputStorage'): context._inputStorage = {} if self.__name__ not in context._inputStorage: context._inputStorage[self.__name__] = SavedDataBTree() return context._inputStorage[self.__name__]
def onSuccess(self, fields, request): """ saves data in Postgresdb. """ data = OrderedDict() columns = self.getColumns() for tup in columns: if tup[1] in ('Float', 'Decimal') and self.decimal_separator: # treat both '.' and ',' as decimal separator # overriding form widget behaviour, convenient for forms on mobile! val = request.form['form.widgets.{}'.format(tup[0])].replace( ',', '.' ) if val == u'': val = None else: val = float(val) else: val = fields[tup[0]] data[tup[0]] = (val, tup[1]) if self.ExtraData: for f in self.ExtraData: if f == 'dt': data[f] = (str(DateTime()), 'Datetime') else: data[f] = (getattr(request, f, ''), 'Text') context = get_context(self) ret = self.InsertDB(context, data)
def onSuccess(self, fields, request): """e-mails data. """ context = get_context(self) mailtext = self.get_mail_text(fields, request, context) host = api.portal.get_tool(name="MailHost") host.send(mailtext)
def onSuccess(self, fields, request): """ e-mails data. """ context = get_context(self) mailtext = self.get_mail_text(fields, request, context) host = api.portal.get_tool(name='MailHost') host.send(mailtext)
def onSuccess(self, fields, request): """ e-mails data. """ context = get_context(self) mailtext = self.get_mail_text(fields, request, context) host = context.MailHost host.send(mailtext)
def onSuccess(self, fields, request): """Create item on successful form submission """ context = get_context(self) current_user = api.user.get_current() with api.env.adopt_user(user=current_user): with api.env.adopt_roles(roles=['Contributor']): self.createDXItem(fields, request, context)
def test_MailerXMLAttachments(self): """ Test mailer with dummy_send """ mailer = get_actions(self.ff1)["mailer"] mailer.sendXML = True mailer.sendCSV = False context = get_context(mailer) # Test all dexterity field type listed at https://docs.plone.org/external/plone.app.dexterity/docs/reference/fields.html fields = dict( replyto="*****@*****.**", topic="test subject", richtext=RichTextValue(raw="Raw"), comments=u"test comments😀", datetime=datetime.datetime(2019, 4, 1), date=datetime.date(2019, 4, 2), delta=datetime.timedelta(1), bool=True, number=1981, floating=3.14, tuple=("elemenet1", "element2"), list=[1, 2, 3, 4], map=dict(fruit="apple"), choices=set(["A", "B"]), ) request = self.LoadRequestForm(**fields) attachments = mailer.get_attachments(fields, request) self.assertEqual(1, len(attachments)) self.assertIn( u"Content-Type: application/xml\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\nContent-Disposition: attachment", mailer.get_mail_text(fields, request, context), ) name, mime, enc, xml = attachments[0] output_nodes = ( b'<field name="replyto">[email protected]</field>', b'<field name="topic">test subject</field>', b'<field name="richtext">Raw</field>', b'<field name="comments">test comments\xf0\x9f\x98\x80</field>', b'<field name="datetime">2019/04/01, 00:00:00</field>', b'<field name="date">2019/04/02</field>', b'<field name="delta">1 day, 0:00:00</field>', b'<field name="bool">True</field>', b'<field name="number">1981</field>', b'<field name="floating">3.14</field>', b'<field name="tuple">["elemenet1", "element2"]</field>', b'<field name="list">["1", "2", "3", "4"]</field>', b'<field name="map">{"fruit": "apple"}</field>', ) self.assertIn(b"<?xml version='1.0' encoding='utf-8'?>\n<form>", xml) # the order of the nodes can change ... check each line for node in output_nodes: self.assertIn(node, xml) # the order of ["A", "B"] can change ... check separately self.assertIn(b'"A"', xml) self.assertIn(b'"B"', xml)
def test_MailerCSVAttachments(self): """ Test mailer with dummy_send """ mailer = get_actions(self.ff1)["mailer"] mailer.sendXML = False mailer.sendCSV = True context = get_context(mailer) # Test all dexterity field type listed at https://docs.plone.org/external/plone.app.dexterity/docs/reference/fields.html fields = dict( topic="test subject", replyto="*****@*****.**", richtext=RichTextValue(raw="Raw"), comments=u"test comments😀", datetime=datetime.datetime(2019, 4, 1), date=datetime.date(2019, 4, 2), delta=datetime.timedelta(1), bool=True, number=1981, floating=3.14, tuple=("elemenet1", "element2"), list=[1, 2, 3, 4], map=dict(fruit="apple"), choices=set(["A", "B"]), ) request = self.LoadRequestForm(**fields) attachments = mailer.get_attachments(fields, request) self.assertEqual(1, len(attachments)) self.assertIn( u"Content-Type: application/csv\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\nContent-Disposition: attachment", mailer.get_mail_text(fields, request, context), ) name, mime, enc, csv = attachments[0] output = ( b"*****@*****.**", b"test subject", b"Raw", b"test comments\xf0\x9f\x98\x80", b"2019/04/01, 00:00:00", b"2019/04/02", b"1 day, 0:00:00", b"True", b"1981", b"3.14", b'[""elemenet1"", ""element2""]', b'[""1"", ""2"", ""3"", ""4""]', b'{""fruit"": ""apple""}', ) # the order of the columns can change ... check each # TODO should really have a header row for value in output: self.assertIn(value, csv) # the order of [""A"", ""B""] can change ... check separately self.assertIn(b'""A""', csv) self.assertIn(b'""B""', csv)
def getColumnNames(self): # """Returns a list of column names""" context = get_context(self) showFields = getattr(self, "showFields", []) if showFields is None: showFields = [] names = [name for name, field in getFieldsInOrder(get_schema(context)) if not showFields or name in showFields] if self.ExtraData: for f in self.ExtraData: names.append(f) return names
def __call__(self, context): terms = [] if hasattr(context, "interface"): form = get_context(context) elif hasattr(context, "fields_model"): form = context else: return SimpleVocabulary(terms) fields = getFieldsInOrder(get_fields(form)) for name, field in fields: terms.append(SimpleVocabulary.createTerm(name, str(name), field.title)) return SimpleVocabulary(terms)
def FieldsVocabularyFactory(context): terms = [] if hasattr(context, "interface"): form = get_context(context) elif hasattr(context, "fields_model"): form = context else: return SimpleVocabulary(terms) fields = getFieldsInOrder(get_schema(form)) for name, field in fields: terms.append(SimpleVocabulary.createTerm(name, str(name), field.title)) return SimpleVocabulary(terms)
def getColumnNames(self): # """Returns a list of column names""" context = get_context(self) showFields = getattr(self, 'showFields', []) names = [ name for name, field in getFieldsInOrder(get_fields(context)) if not showFields or name in showFields ] if self.ExtraData: for f in self.ExtraData: names.append(f) return names
def getColumnTitles(self): # """Returns a list of column titles""" context = get_context(self) showFields = getattr(self, 'showFields', []) names = [ field.title for name, field in getFieldsInOrder(get_fields(context)) if not showFields or name in showFields ] if self.ExtraData: for f in self.ExtraData: names.append(IExtraData[f].title) return names
def __call__(self, context): terms = [] if hasattr(context, 'interface'): form = get_context(context) elif hasattr(context, 'fields_model'): form = context else: return SimpleVocabulary(terms) fields = getFieldsInOrder(get_fields(form)) for name, field in fields: terms.append( SimpleVocabulary.createTerm(name, str(name), field.title)) return SimpleVocabulary(terms)
def getColumns(self): """ Returns a list of tuples (column names, column type name) in correct order of the fields in the form """ context = get_context(self) showFields = getattr(self, 'showFields', []) if showFields is None: showFields = [] columns = [ (name, type(field).__name__) for name, field in getFieldsInOrder(get_schema(context)) ] return columns
def getColumnTitles(self): # """Returns a list of column titles""" context = get_context(self) showFields = getattr(self, 'showFields', []) if showFields is None: showFields = [] names = [ field.title for name, field in getFieldsInOrder(get_schema(context)) if not showFields or name in showFields ] if self.ExtraData: for f in self.ExtraData: names.append(IExtraData[f].title) return names
def download(self, response, delimiter=""): """This patch combines the data from the sender installation and the receiver installation to one csv / tsv. We assume that the form config is the same on both sides. The concept is to first execute the standard implementation, which sets the response headers and streams the local data. If the context is considered public, the second step is to get the data from the remote realms and append it to the response body (with response.write). This will combine the data of the all sites in a streamed http response. This implementation also works in local development with two plone sites, assuming that the receiver side does not have any realms configured. """ site = getSite() realms = IConfig(site).getRealms() if not realms: return if site.REQUEST.get('is_publisher', None): # Prevent endless loop if sender and receiver are running on the same machine self._old_download(response, delimiter) return pub_state = getMultiAdapter((get_context(self), response), IPublisherContextState) if not pub_state.is_parent_published(): return site_path = '/'.join(site.getPhysicalPath()) context_path = '/'.join(get_context(self).getPhysicalPath()) relative_path = os.path.relpath(context_path, site_path) view_path = '/'.join((relative_path, '@@actions', self.__name__, '@@data')) is_xlsx = getattr(self, 'DownloadFormat', 'tsv') == 'xlsx' is_csv = getattr(self, 'DownloadFormat', 'tsv') == 'csv' if is_csv and len(delimiter) == 0: delimiter = ',' if not is_xlsx: self._old_download(response, delimiter) for realm in realms: try: remote_response = sendRequestToRealm(getSite().REQUEST.form.copy(), realm, view_path.lstrip('/') + '?is_publisher=1', return_response=True) except HTTPError: remote_response = False # Nothing to combine if remote_response and remote_response.code != 200: raise ValueError( 'Bad response from remote realm ({} {}): {!r}..'.format( remote_response.code, remote_response.msg, remote_response.read(100), )) try: if is_xlsx: use_title_row = getattr(self, "UseColumnNames", False) local_excel = self.get_saved_form_input_as_xlsx(use_title_row) combine_excel(response, local_excel, remote_response, use_title_row) else: response.write(remote_response.read()) except ImportError: raise Exception( 'Was not able to combine excel, since openpyxl is missing') finally: if remote_response: remote_response.close()
def get_schema(self): return get_schema(get_context(self.field))
def get_fields(self): return get_fields(get_context(self.field))
def onSuccess(self, fields, request): # Executes the custom script form = get_context(self) resultData = self.sanifyFields(request.form) return self.executeCustomScript(resultData, form, request)