def get_rss_news(self, context): url = getattr(context.site_root, 'backoffice_rss_news_uri', None) if url is None: return [] # Flux de news RSS try: f = urlopen(url) except Exception: return [] try: feed = RSSFile(string=f.read()) except (XMLError, IndexError): return [] rss_news = [] for item in feed.items[:5]: item['ago'] = datetime_to_ago(item['pubDate']) if item.get('pubDate'): item['pubDate'] = format_date(item['pubDate'], context.accept_language) else: item['pubDate'] = None item['description'] = XMLParser( item['description'].encode('utf-8')) rss_news.append(item) return rss_news
def get_events(self, filename): content = self.get_file(filename) for event in XMLParser(content): if event == XML_DECL: pass else: yield event
def decode(cls, data): events = XMLParser(data, namespaces=xhtml_namespaces, doctype=xhtml_doctype) if cls.sanitize_html is True: events = sanitize_stream(events) return list(events)
def get_namespace(self, context): # Build namespace namespace = { 'author': self.get_namespace_author(context), 'href': context.get_link(self), 'images': self.get_images(context) } for key in ['title', 'note', 'advantages', 'disadvantages']: namespace[key] = self.get_property(key) # Add informations about product product = self.parent.parent namespace['product'] = { 'link': context.get_link(product), 'title': product.get_title() } # Context here = context.resource namespace['is_on_user_view'] = here.class_id == 'user' namespace['is_on_product_view'] = here.class_id == 'product' # Description description = self.get_property('description').encode('utf-8') description = XMLContent.encode(description) namespace['description'] = XMLParser(description.replace( '\n', '<br/>')) # ctime ctime = self.get_property('ctime') accept = context.accept_language namespace['ctime'] = format_datetime(ctime, accept) # Recommendation recommended = self.get_property('recommended') or 0 namespace['recommendation'] = bool(int(recommended)) return namespace
def _format(self, message, **kw): if self.format == 'stl': events = XMLParser(message.encode('utf_8'), namespaces=stl_namespaces) return stl(events=events, namespace=self) return super(INFO, self)._format(message, **kw)
class SelectRadioImages(SelectRadio): template = list( XMLParser( """ <ul style="list-style-type:none;margin:0;padding:0;"> <li stl:if="has_empty_option" style="width:110px;height=110px;float:left;"> <input id="${id}" type="radio" name="${name}" value="" checked="checked" stl:if="none_selected"/> <input id="${id}" type="radio" name="${name}" value="" stl:if="not none_selected"/> <label for="${id}" style="width:60px;height:60px;display:block;border:1px dashed gray; padding:20px;"> No picture </label> </li> <li style="float:left;width:110px;height=110px;" stl:repeat="option options"> <input type="radio" id="${id}-${option/name}" name="${name}" value="${option/name}" checked="checked" stl:if="option/selected"/> <input type="radio" id="${id}-${option/name}" name="${name}" value="${option/name}" stl:if="not option/selected"/> <label for="${id}-${option/name}"> <img src="${option/link}/;thumb?width=100&height=100" title=" ${option/value}"/> </label> </li> </ul> """, stl_namespaces))
def _load_state_from_file(self, file): # FIXME The XML parser does not support reading from a StringIO if type(file) is InputType: file = file.read() stream = XMLParser(file) self.events = list(stream)
def get_before_namespace(self, resource, context): # Set organizer infos in ${before} owner = resource.get_owner() owner = resource.get_resource(owner).get_title() owner_msg = MSG(u'<p id="event-owner">Created by <em>{owner}</em></p>') owner_msg = owner_msg.gettext(owner=owner).encode('utf-8') return XMLParser(owner_msg)
class BirthdayWidget(Widget): template = list( XMLParser( """ ${day} ${month} ${year} <input type="hidden" name="${name}" value="1"/> """, stl_namespaces)) def get_namespace(self, datatype, value): namespace = Widget.get_namespace(self, datatype, value) context = get_context() if value and value != '1': try: day, month, year = value.split('/') day = int(day) month = int(month) year = int(year) except: day = month = year = None else: day = context.get_form_value('day', type=Integer) month = context.get_form_value('month', type=Integer) year = context.get_form_value('year', type=Integer) namespace['day'] = SelectWidget('day').to_html(Days, day) namespace['month'] = SelectWidget('month').to_html(Months, month) namespace['year'] = SelectWidget('year').to_html(Years, year) return namespace
class RangeSlider(Widget): template = list( XMLParser( """ <input type="text" id="${id}-amount" style="border:0; color:#f6931f; font-weight:bold;" /> <div id="${id}"/> <script type="text/javascript" src="/ui/shop/js/jquery.slider.js"/> <script type="text/javascript"> $(function() { $("#${id}").slider({ range: true, min: 0, max: 5000, values: [0, 10], slide: function(event, ui) { $("#${id}-amount").val(ui.values[0] + ' - ' + ui.values[1]); } }); }); </script> """, stl_namespaces)) def get_namespace(self, datatype, value): namespace = Widget.get_namespace(self, datatype, value) namespace['title'] = self.title return namespace
def test_stream_to_html_escape(self): parser = XMLParser('<p xmlns="http://www.w3.org/1999/xhtml"></p>') events = list(parser) events.insert(1, (xml_TEXT, '<br/>', 0)) self.assertEqual( stream_to_html(events), '<p xmlns="http://www.w3.org/1999/xhtml"><br/></p>')
def test_html(self): parser = XMLParser( '<p xmlns="http://www.w3.org/1999/xhtml">Bed&Breakfast</p>') out = stream_to_html(parser) # Assert self.assertEqual( out, '<p xmlns="http://www.w3.org/1999/xhtml">Bed&Breakfast</p>')
def get_item_value(self, resource, context, item, column): brain, item_resource = item if column == 'name': link = '%s/%s' % (resource.get_property('shop_uri'), brain.name) return XMLParser("<a href='%s' target='_blank'>%s</a>" % (link, brain.name)) return Folder_BrowseContent.get_item_value(self, resource, context, item, column)
def _load_state_from_file(self, file): text = None self.header = {} messages = {} self.header_notes = {} for event, value, line_number in XMLParser(file.read()): if event == START_ELEMENT: namespace, local_name, attributes = value # Attributes, get rid of the namespace uri (XXX bad) aux = {} for attr_key in attributes: attr_name = attr_key[1] aux[attr_name] = attributes[attr_key] attributes = aux if local_name == 'tmx': self.version = attributes['version'] elif local_name == 'header': self.header = attributes default_srclang = attributes['srclang'] notes = [] elif local_name == 'note': note = TMXNote(attributes=attributes) elif local_name == 'tu': tu = TMXUnit(attributes) notes = [] elif local_name == 'tuv': tuv = Sentence(attributes) notes = [] segment = None elif event == END_ELEMENT: namespace, local_name = value if local_name == 'header': self.header_notes = notes elif local_name == 'note': note.text = text notes.append(note) elif local_name == 'tu': tu.notes = notes srclang = tu.attributes.get('srclang', default_srclang) if srclang == '*all*': raise NotImplementedError, \ 'no support for "*all*" in srclang attribute.' msgid = tu.msgstr[srclang].text messages[msgid] = tu elif local_name == 'tuv': if segment is not None: tuv.notes = notes tuv.text = segment tu.msgstr[tuv.attributes['lang']] = tuv elif local_name == 'seg': segment = text elif event == COMMENT: pass elif event == TEXT: text = unicode(value, 'UTF-8') self.messages = messages
def test_3(self): doctype = DocType(PubidLiteral='-//W3C//DTD XHTML 1.0 Strict//EN', SystemLiteral= 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd', intSubset='\n<!ENTITY entity_test "TEST">\n') data = '<html>À &entity_test;</html>' # No raise list(XMLParser(data, doctype=doctype))
def get_namespace(self, resource, context): proxy = super(Shop_UserConfirmRegistration, self) namespace = proxy.get_namespace(resource, context) confirm_msg = MSG(u""" You have not yet confirmed your registration.<br/> To confirm it, please click on the confirmation link included on the registration confirmation email.<br/> You can also fill your email address and your activation key (received on the mail) in the following form.<br/> If you havn't received your registration key, <a href=";send_confirmation_view"> you can receive it again by clicking here. </a> """) namespace['required_msg'] = (list(XMLParser(confirm_msg.gettext().encode('utf8'))) + list(XMLParser('<br/>')) + list(namespace['required_msg'])) return namespace
def test_serialize(self): data = self.rss.to_str() # Testing the hand-written XML is well-formed events = list(XMLParser(data)) # Testing the XML processing instruction event, value, line_number = events[0] self.assertEqual(event, XML_DECL) version, encoding, standalone = value self.assertEqual(version, '1.0') self.assertEqual(encoding, 'UTF-8')
class FilesWidget(Widget): template = list( XMLParser( """ <input type="file" id="${id}" name="${name}" value="${value}"/><br/> <input type="file" id="${id}" name="${name}" value="${value}"/><br/> <input type="file" id="${id}" name="${name}" value="${value}"/><br/> <input type="file" id="${id}" name="${name}" value="${value}"/><br/> """, stl_namespaces))
def test_3(self): data = ('<?xml version="1.0"?>\n' '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n' '<html>« ƒ Ξ ψ ‰ ℜ ∞ ' '∴ ♣</html>\n') expected = '« ƒ Ξ ψ ‰ ℜ ∞ ∴ ♣' parser = XMLParser(data) self.assertEqual(list(parser)[5][1], expected)
def get_namespace(self, resource, context): namespace = RegisterForm.get_namespace(self, resource, context) # Add register body group = self.get_group(context) register_body = group.get_property('register_body') if register_body is not None: namespace['required_msg'] = (register_body + list(XMLParser('<br/><br/>')) + list(namespace['required_msg'])) return namespace
def get_item_value(self, resource, context, item, column): if column == 'numero': state = item.workflow_state href = './;order_view?id=%s' % item.name name = item.get_reference() return XMLParser(numero_template % (states_color[state], href, name)) elif column == 'state': state = item.workflow_state state_title = states[state].gettext().encode('utf-8') href = './;order_view?id=%s' % item.name return XMLParser(numero_template % (states_color[state], href, state_title)) elif column == 'total_price': price = item.get_property(column) return format_price(price) elif column == 'creation_datetime': value = item.get_property(column) accept = context.accept_language return format_datetime(value, accept=accept) return BrowseForm.get_item_value(self, resource, context, item, column)
def get_options(cls): from products.enumerate import CategoriesEnumerate datatype = CategoriesEnumerate context = get_context() value = context.resource.get_property('specific_category') html = SelectWidget('specific_category').to_html(datatype, value) opt = [{ 'name': 'one_category', 'value': list(XMLParser('Only this category')) + list(html) }] return cls.base_options + opt
class SIRETWidget(Widget): template = list( XMLParser( """ <input type="text" id="${id}" name="${name}" value="${value}"/> <script type="text/javascript" src="/ui/shop/js/jquery.maskedinput-1.2.2.min.js"/> <script type="text/javascript"> $("#${id}").mask("999 999 999 99999"); </script> """, stl_namespaces))
def get_announce(self, context): url = getattr(context.site_root, 'backoffice_announce_uri', None) if url is None: return None try: f = urlopen(url) data = XMLParser(f.read()) except Exception: return None if f.code == 404: return None return data
class MiniProductWidget(Widget): template = list( XMLParser("""${viewbox}<div class="clear"/>""", stl_namespaces)) def get_namespace(self, datatype, value): context = get_context() product = context.resource while product.class_id != 'product': product = product.parent viewbox = product.viewbox return {'viewbox': viewbox.GET(product, context)}
def test_paragraph(self): """Test formatted paragraph""" content = ('<office:text>' '<text:p text:style-name="Standard">' 'hello world' '</text:p>' '</office:text>') content = odt_template % content messages = XMLParser(content) messages = [unit[0] for unit in get_units(messages)] expected = [((TEXT, u'hello world'), )] self.assertEqual(messages, expected)
def test_1(self): dtd = ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ' '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" ' '[\n' '<!ENTITY entity_test "TEST">\n' ']>') data = '<?xml version="1.0"?>\n'+dtd parser = XMLParser(data) name, doctype = list(parser)[2][1] self.assertEqual(get_doctype(name, doctype), dtd)
def test_2(self): data = ('<?xml version="1.0"?>\n' '<!DOCTYPE test [\n' '<!ELEMENT test (#PCDATA) >\n' "<!ENTITY % xx '%zz;'>\n" """<!ENTITY % zz '<!ENTITY tricky "error-prone" >' >\n""" '%xx;\n' ']>\n' '<test>This sample shows a &tricky; method.</test>') parser = XMLParser(data) self.assertEqual(list(parser)[5], (4, 'This sample shows a error-prone method.', 8))
def get_item_value(self, resource, context, item, column): if column == 'buttons': kw = {'id': item['id'], 'way': item['payment_mode']} return XMLParser(self.buttons_template.format(**kw)) if column == 'payment_mode': payment_mode = item['payment_mode'] return PaymentWaysEnumerate.get_value(payment_mode) elif column == 'user_title': return item['user_title'], '/users/%s' % item['username'] elif column == 'state': return item[column] and MSG(u'OK') or '' return item[column]
def get_payment_way_description(self, context, total_amount): msg = MSG(u"Pay {percent}% of {original_amount} now ({amount})") percent = self.get_property('percent') if self.get_property('pay_tax'): total_amount = total_amount['with_tax'].split(' ')[0] total_amount = decimal(total_amount) else: total_amount = total_amount['without_tax'].split(' ')[0] total_amount = decimal(total_amount) amount = total_amount * (percent / decimal('100.0')) msg = msg.gettext(percent=percent, original_amount=format_price(total_amount), amount=format_price(amount)) return list(XMLParser(msg.encode('utf-8'))) + self.get_property('data')