def _subvalue_to_html(cls, value): if issubclass(cls.type, AnyUri): href = getattr(value, 'href', None) if href is None: # this is not a AnyUri.Value instance. href = value text = getattr(cls.type.Attributes, 'text', None) content = None else: text = getattr(value, 'text', None) if text is None: text = getattr(cls.type.Attributes, 'text', None) content = getattr(value, 'content', None) if issubclass(cls.type, ImageUri): retval = E.img(src=href) if text is not None: retval.attrib['alt'] = text # content is ignored with ImageUri. else: retval = E.a(href=href) retval.text = text if content is not None: retval.append(content) else: retval = cls.type.to_string(value) return retval
def _gen_header(self, ctx, cls, name, parent): with parent.element('thead'): with parent.element('tr'): th_attrs = {} if self.field_name_attr is not None: th_attrs[self.field_name_attr] = name # fti is none when the type inside Array is not a ComplexModel. if issubclass(cls, ComplexModelBase): fti = cls.get_flat_type_info(cls) if self.field_name_attr is None: for k, v in fti.items(): if getattr(v.Attributes, 'exc_html', None): continue header_name = self.translate(v, ctx.locale, k) parent.write(E.th(header_name, **th_attrs)) else: for k, v in fti.items(): if getattr(v.Attributes, 'exc_html', None): continue th_attrs[self.field_name_attr] = k header_name = self.translate(v, ctx.locale, k) parent.write(E.th(header_name, **th_attrs)) else: if self.field_name_attr is not None: th_attrs[self.field_name_attr] = name header_name = self.translate(cls, ctx.locale, name) parent.write(E.th(header_name, **th_attrs)) self.extend_header_row(ctx, cls, name, parent)
def test_simple__multiline_paragraph(): test = \ """ This is a test of the assembler. This line should be followed by a br tag """ test = textwrap.dedent(test).strip() expected_text =\ [ "This is a test of the assembler. ", "This line should be followed by a ", E("br"), "br tag" ] root_kwargs = {"class": "brutemark_root"} root = E("div", E("p", *expected_text), **root_kwargs) expected = tostring(root, pretty_print=True, encoding="unicode") actual_string = markdown(test) assert expected == actual_string
def _gen_thead(self, ctx, cls, name, parent): logger.debug("Generate header for %r", cls) with parent.element('thead'): with parent.element('tr'): if issubclass(cls, ComplexModelBase): fti = self.sort_fields(cls) for k, v in fti: attr = self.get_cls_attrs(v) if attr.exc: continue th_attrs = {} if self.field_name_attr is not None: th_attrs[self.field_name_attr] = k if attr.hidden: th_attrs['style'] = 'display:None' header_name = self.trc(v, ctx.locale, k) parent.write(E.th(header_name, **th_attrs)) m = cls.Attributes.methods if m is not None and len(m) > 0: parent.write(E.th()) else: th_attrs = {} if self.field_name_attr is not None: th_attrs[self.field_name_attr] = name header_name = self.trc(cls, ctx.locale, name) parent.write(E.th(header_name, **th_attrs)) self.extend_header_row(ctx, cls, parent, name)
def _gen_header(self, ctx, cls, name, parent): logger.debug("Generate header for %r", cls) with parent.element('thead'): with parent.element('tr'): th_attrs = {} if self.field_name_attr is not None: th_attrs[self.field_name_attr] = name if issubclass(cls, ComplexModelBase): fti = cls.get_flat_type_info(cls) if self.field_name_attr is None: for k, v in fti.items(): attr = get_cls_attrs(self, v) if attr.exc: continue header_name = self.trc(v, ctx.locale, k) parent.write(E.th(header_name, **th_attrs)) else: for k, v in fti.items(): attr = get_cls_attrs(self, v) if attr.exc: continue th_attrs[self.field_name_attr] = k header_name = self.trc(v, ctx.locale, k) parent.write(E.th(header_name, **th_attrs)) else: if self.field_name_attr is not None: th_attrs[self.field_name_attr] = name header_name = self.trc(cls, ctx.locale, name) parent.write(E.th(header_name, **th_attrs)) self.extend_header_row(ctx, cls, parent, name)
def replace_youtube_videos_with_links(self, doc): """Replace any iframe elements found with a link to the src and a placeholder image from youtube""" def get_yt_id(src): """Return the youtube video id""" split_src = src.split("/") if "embed" in split_src: yt_id_index = split_src.index("embed") + 1 return split_src[yt_id_index] iframes = doc.xpath("//iframe") for iframe in iframes: src = iframe.get("src") yt_id = get_yt_id(src) if not yt_id: continue else: yt_img = "https://img.youtube.com/vi/{0}/0.jpg".format(yt_id) yt_href = "https://youtu.be/{0}".format(yt_id) yt_link = E.a( E.img( src=yt_img, width="480", height="360", ), href=yt_href, target="_blank", ) parent = iframe.getparent() parent.replace(iframe, yt_link)
def _gen_thead(self, ctx, cls, parent, name): logger.debug("Generate header for %r", cls) with parent.element('thead'): with parent.element('tr'): if issubclass(cls, ComplexModelBase): fti = self.sort_fields(cls) for k, v in fti: cls_attr = self.get_cls_attrs(v) if cls_attr.exc: continue th_attrs = {} self.add_field_attrs(th_attrs, k, cls) if cls_attr.hidden: self.add_style(th_attrs, 'display:None') header_name = self.trc(v, ctx.locale, k) parent.write(E.th(header_name, **th_attrs)) m = cls.Attributes.methods if m is not None and len(m) > 0: th_attrs = {'class': 'mrpc-cell'} parent.write(E.th(**th_attrs)) else: th_attrs = {} self.add_field_attrs(th_attrs, name, cls) header_name = self.trc(cls, ctx.locale, name) parent.write(E.th(header_name, **th_attrs)) self.extend_header_row(ctx, cls, parent, name)
def _gen_header(self, ctx, cls, name, parent): logger.debug("Generate header for %r", cls) with parent.element('thead'): with parent.element('tr'): th_attrs = {} if self.field_name_attr is not None: th_attrs[self.field_name_attr] = name if issubclass(cls, ComplexModelBase): fti = cls.get_flat_type_info(cls) if self.field_name_attr is None: for k, v in fti.items(): attr = get_cls_attrs(self, v) if attr.exc: continue header_name = self.trc(v, ctx.locale, k) parent.write(E.th(header_name, **th_attrs)) else: for k, v in fti.items(): attr = get_cls_attrs(self, v) if attr.exc: continue th_attrs[self.field_name_attr] = k header_name = self.trc(v, ctx.locale, k) parent.write(E.th(header_name, **th_attrs)) else: if self.field_name_attr is not None: th_attrs[self.field_name_attr] = name header_name = self.trc(cls, ctx.locale, name) parent.write(E.th(header_name, **th_attrs)) self.extend_header_row(ctx, cls, name, parent)
def model_base_to_parent(self, ctx, cls, inst, parent, name, tr_child=False, **kwargs): attrs = {} if self.field_name_attr is not None: attrs = {self.field_name_attr: name} retval = E.td(self.to_string(cls, inst), **attrs) if not tr_child: retval = E.tr(retval) parent.write(retval)
def Render(cls, elements): lines = [] for element in elements: # Codeline does not have preprocessed bodies lines.append(element.content) body = "\n".join(lines) return E("pre", E("code", body))
def Render(cls, elements): lines = [] for token in elements: if hasattr(token, "render"): lines.append(token.render()) else: lines.append(E("li", token.content)) return E("ul", *lines)
def model_base_to_parent(self, ctx, cls, inst, parent, name, from_arr=False, **kwargs): if from_arr: td_attrib = {} if False and self.field_name_attr: td_attrib[self.field_name_attr] = name parent.write(E.tr(E.td(self.to_unicode(cls, inst), **td_attrib))) else: parent.write(self.to_unicode(cls, inst))
def google_fonts(font_names, standalone=False): GOOGLE_API_KEY = "AIzaSyCXe6WAu7i4CYL9ee-RFNZirObwT4zJyqI" url = "https://www.googleapis.com/webfonts/v1/webfonts" https_proxy = os.environ.get("https_proxy") if https_proxy is not None: proxy_support = urllib2.ProxyHandler({"https": https_proxy}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) info = json.loads(urllib2.urlopen(url + "?key=" + GOOGLE_API_KEY).read()) if standalone: css = "" css_template = \ """ @font-face {{ font-family: {name!r}; font-style: {style}; font-weight: {weight}; src: url({file!r}); }} """ for font_name in font_names: for font_info in info["items"]: if font_info["family"] == font_name: variants = font_info["variants"] files = font_info["files"] for variant in variants: subinfo("downloading {0}".format(font_name + " " + variant)) ttf_bytes = urllib.urlopen(files[variant]).read() ttf_path = Path("fonts") / (font_name + " " + variant + ".ttf") ttf_file = (ARTDOC / ttf_path).open("wb") ttf_file.write(ttf_bytes) ttf_file.close() style = "normal" if "italic" not in variant else "italic" weight = re.match("[0-9]*", variant).group() or "400" css += css_template.format(name=font_name, style=style, weight=weight, file=str( Path("..") / ttf_path)) break (ARTDOC / "css" / "fonts.css").open("wb").write(css) return [HTML.link(rel="stylesheet", href=".artdoc/css/fonts.css")] else: families = [] for font_name in font_names: for font_info in info["items"]: if font_info["family"] == font_name: family = font_name.replace(" ", "+") + ":" variants = font_info["variants"] family += ",".join(variants) families.append(family) break family = "|".join(families) + "&subset=latin,latin-ext" url = "http://fonts.googleapis.com/css?family=" + family return [HTML.link(rel="stylesheet", href=url)]
def jquery(url="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.js", standalone=False): if standalone: path = ARTDOC / "js" / "jquery.js" file = path.open("wb") file.write(urllib.urlopen(url).read()) file.close() return [HTML.script(src=str(path))] else: return [HTML.script(src=url)]
def _build_html_header(self): '''Add banner and account links''' header = self.elements.header index_url = self.links.get( 'index', self.handler.reverse_url('index')) header.append(E.div( E.a(self.meta.app_name, href=index_url, id='logo-link'), id='logo-wrapper' ))
def add_footer(self): self.elements.content.append( E.footer( E.a(self.T('Wuff Signal'), href=self.handler.reverse_url('textshow.index')), ' ', E.a(self.T('About'), href=self.handler.reverse_url('textshow.about')) ) )
def google_fonts(font_names, standalone=False): GOOGLE_API_KEY = "AIzaSyCXe6WAu7i4CYL9ee-RFNZirObwT4zJyqI" url = "https://www.googleapis.com/webfonts/v1/webfonts" https_proxy = os.environ.get("https_proxy") if https_proxy is not None: proxy_support = urllib2.ProxyHandler({"https": https_proxy}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) info = json.loads(urllib2.urlopen(url + "?key=" + GOOGLE_API_KEY).read()) if standalone: css = "" css_template = \ """ @font-face {{ font-family: {name!r}; font-style: {style}; font-weight: {weight}; src: url({file!r}); }} """ for font_name in font_names: for font_info in info["items"]: if font_info["family"] == font_name: variants = font_info["variants"] files = font_info["files"] for variant in variants: subinfo("downloading {0}".format(font_name + " " + variant)) ttf_bytes = urllib.urlopen(files[variant]).read() ttf_path = Path("fonts") / (font_name + " " + variant + ".ttf") ttf_file = (ARTDOC / ttf_path).open("wb") ttf_file.write(ttf_bytes) ttf_file.close() style = "normal" if "italic" not in variant else "italic" weight = re.match("[0-9]*", variant).group() or "400" css += css_template.format(name=font_name, style=style, weight=weight, file=str(Path("..") / ttf_path)) break (ARTDOC / "css" / "fonts.css").open("wb").write(css) return [HTML.link(rel="stylesheet", href=".artdoc/css/fonts.css")] else: families = [] for font_name in font_names: for font_info in info["items"]: if font_info["family"] == font_name: family = font_name.replace(" ", "+") + ":" variants = font_info["variants"] family += ",".join(variants) families.append(family) break family = "|".join(families) + "&subset=latin,latin-ext" url = "http://fonts.googleapis.com/css?family=" + family return [HTML.link(rel="stylesheet", href=url)]
def Render(cls, elements): lines = [] for token in elements: if type(token) != cls: lines.append(token.Render([token.content] + [token.children])) elif hasattr(token, "render"): lines.append(token.render()) else: lines.append(E("li", token.content)) return E("ol", *lines)
def model_base_to_parent(self, ctx, cls, inst, parent, name, **kwargs): retval = E.tr() attr = {} if self.field_name_attr is not None: attr = {self.field_name_attr: name} if self.produce_header: retval.append(E.th(self.translate(cls, ctx.locale, name), **attr)) retval.append(E.td(self.to_string(cls, inst), **attr)) parent.write(retval)
def _build_html_footer(self): '''Adds the site visual footer links''' self.elements.footer.extend([ E.nav( E.a(self.handler.application.settings['application_name'], href=self.handler.reverse_url('index')), ' ', E.a(self.T('About'), href=self.handler.reverse_url('index.about')) ) ])
def test_simple_multiple_ordered_list(): test = "\n".join(["1. First item", "2. Second item"]) root_kwargs = {"class": "brutemark_root"} expected = tostring(E( "div", E("ol", E("li", "First item"), E("li", "Second item")), **root_kwargs), pretty_print=True, encoding="unicode") actual = markdown(test) assert actual == expected
def build_title_content(self): self.elements.content.extend([ E.p('''Wuff Signal allows you to share messages without revealing the contents of your message. It lossily scrambles your message and shows them as points on the page. These points are called Signals. '''), E.p('You can view a ', E.a('complete list of recent Signals', href=self.handler.reverse_url('textshow.recent')), '.'), ]) self.add_footer()
def font_awesome(url="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css", standalone_url="http://fortawesome.github.io/Font-Awesome/assets/font-awesome-4.3.0.zip", standalone=False): if standalone: zip_file = tempfile.NamedTemporaryFile(suffix=".zip", delete=False) zip_file.write(urllib.urlopen(standalone_url).read()) zip_filename = zip_file.name zip_file.close() zipfile.ZipFile(zip_filename).extractall(str(ARTDOC)) os.remove(zip_filename) return [HTML.link(rel="stylesheet", href=".artdoc/font-awesome-4.3.0/css/font-awesome.min.css")] else: return [HTML.link(rel="stylesheet", href=url)]
def test_simple_generation_single_header(): test = \ textwrap.dedent(""" # Hello World """).strip() expected = tostring(E("div", E("h1", "Hello World"), **{"class": "brutemark_root"}), pretty_print=True, encoding="unicode") actual = markdown(test) assert actual == expected
def model_base_to_parent(self, ctx, cls, inst, parent, name, from_arr=False, **kwargs): inst_str = '' if inst is not None: inst_str = self.to_unicode(cls, inst) if from_arr: td_attrs = {} self.add_field_attrs(td_attrs, name, cls) parent.write(E.tr(E.td(inst_str, **td_attrs))) else: parent.write(inst_str)
def model_base_to_parent(self, ctx, cls, inst, parent, name, from_arr=False, **kwargs): if from_arr: td_attrs = {} #if self.field_name_attr: # td_attrs[self.field_name_attr] = name parent.write(E.tr( E.td( self.to_string(cls, inst), **td_attrs ) )) else: parent.write(self.to_string(cls, inst))
def _build_html_title(self): if self.meta.title: title_text = '{} – {}'.format(self.meta.title, self.meta.app_name) else: title_text = self.meta.app_name self.elements.head.append(E.title(title_text))
def gen_anchor(self, cls, inst, name, anchor_class=None): assert name is not None cls_attrs = self.get_cls_attrs(cls) href = getattr(inst, 'href', None) if href is None: # this is not a AnyUri.Value instance. href = inst content = None text = cls_attrs.text else: content = getattr(inst, 'content', None) text = getattr(inst, 'text', None) if text is None: text = cls_attrs.text if anchor_class is None: anchor_class = cls_attrs.anchor_class if text is None: text = name retval = E.a(text) if href is not None: retval.attrib['href'] = href if anchor_class is not None: retval.attrib['class'] = anchor_class if content is not None: retval.append(content) return retval
def mathjax( url="http://cdn.mathjax.org/mathjax/latest/MathJax.js", zip_url="https://github.com/mathjax/MathJax/archive/master.zip", config="TeX-AMS_HTML", extra={ "HTML-CSS": { "scale": 90, "availableFonts": ["TeX"], "preferredFont": "TeX" }, "TeX": { "equationNumbers": { "autoNumber": "AMS" } } }, standalone=False): if standalone: zip_file = tempfile.NamedTemporaryFile(suffix=".zip", delete=False) zip_file.write(urllib.urlopen(zip_url).read()) zip_filename = zip_file.name zip_file.close() zipfile.ZipFile(zip_filename).extractall(str(ARTDOC)) os.remove(zip_filename) url = str(ARTDOC / "MathJax-master" / "MathJax.js") if config: url = url + "?config=" + config if extra is not None: js = "MathJax.Hub.Config({0})".format(json.dumps(extra)) else: js = "" return [HTML.script(dict(src=url), js)]
def anyuri_to_parent(self, ctx, cls, inst, parent, name, **kwargs): assert name is not None href = getattr(inst, 'href', None) if href is None: # this is not a AnyUri.Value instance. href = inst text = getattr(cls.Attributes, 'text', name) content = None else: text = getattr(inst, 'text', None) if text is None: text = getattr(cls.Attributes, 'text', name) content = getattr(inst, 'content', None) if text is None: text = name retval = E.a(text) if href is not None: retval.attrib['href'] = href if content is not None: retval.append(content) parent.write(retval)
def model_base_to_parent(self, ctx, cls, inst, parent, name, from_arr=False, **kwargs): if from_arr: td_attrs = {} #if self.field_name_attr: # td_attrs[self.field_name_attr] = name parent.write(E.tr(E.td(self.to_string(cls, inst), **td_attrs))) else: parent.write(self.to_string(cls, inst))
def to_parent(self, ctx, cls, inst, parent, name, **kwargs): s = self.to_unicode(cls._type_info['query'], inst.query) q = urlencode({"q": s}) parent.write( E.a("Search %s" % inst.query, href="{}?{}".format(inst.uri, q)))
def add_field(self, field): translate = self._handler.locale.translate wrapper = E.div() if field.label: wrapper.append(E.label(translate(field.label.text), FOR(field.id))) wrapper.append(lxml.html.fromstring(field())) if field.errors: error_wrapper = E.ul() wrapper.append(error_wrapper) for error in field.errors: error_wrapper.append(E.li(E.strong(str(error)))) self._element.append(wrapper)
def Render(cls, children): lines = [] for child_token in children: child_token.render(lines) paragraph = E("p", *lines) return paragraph
def array_to_parent(self, ctx, cls, inst, parent, name, **kwargs): with parent.element('div'): if issubclass(cls, ComplexModelBase): ret = super(HtmlRowTable, self).array_to_parent( ctx, cls, inst, parent, name, **kwargs) if isgenerator(ret): try: while True: sv2 = (yield) ret.send(sv2) except Break as b: try: ret.throw(b) except StopIteration: pass else: table_attrib = {} if self.table_name_attr: table_attrib = {self.table_name_attr: name} if self.table_width is not None: table_attrib['width'] = self.table_width with parent.element('table', table_attrib): tr_attrib = {} if self.row_class is not None: tr_attrib['class'] = self.row_class with parent.element('tr', tr_attrib): if self.header: parent.write(E.th(self.trc(cls, ctx.locale, cls.get_type_name()))) td_attrs = {} if self.cell_class is not None: self.add_html_attr('class', td_attrs, self.cell_class) self.add_field_attrs(td_attrs, name, cls) cls_attrs = self.get_cls_attrs(cls) if cls_attrs.hidden: self.add_style(td_attrs, 'display:None') with parent.element('td', td_attrs): with parent.element('table'): ret = super(HtmlRowTable, self) \ .array_to_parent(ctx, cls, inst, parent, name, **kwargs) if isgenerator(ret): try: while True: sv2 = (yield) ret.send(sv2) except Break as b: try: ret.throw(b) except StopIteration: pass
def font_awesome( url="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css", standalone_url="http://fortawesome.github.io/Font-Awesome/assets/font-awesome-4.3.0.zip", standalone=False): if standalone: zip_file = tempfile.NamedTemporaryFile(suffix=".zip", delete=False) zip_file.write(urllib.urlopen(standalone_url).read()) zip_filename = zip_file.name zip_file.close() zipfile.ZipFile(zip_filename).extractall(str(ARTDOC)) os.remove(zip_filename) return [ HTML.link( rel="stylesheet", href=".artdoc/font-awesome-4.3.0/css/font-awesome.min.css") ] else: return [HTML.link(rel="stylesheet", href=url)]
def complex_model_to_parent(self, ctx, cls, inst, parent, name, from_arr=False, **kwargs): attrib = {} if self.table_name_attr is not None: attrib[self.table_name_attr] = cls.get_type_name() with parent.element('table', attrib): with parent.element('tbody'): for k, v in cls.get_flat_type_info(cls).items(): try: sub_value = getattr(inst, k, None) except: # to guard against e.g. SQLAlchemy throwing NoSuchColumnError sub_value = None sub_name = v.Attributes.sub_name if sub_name is None: sub_name = k if sub_value is None and cls.Attributes.min_occurs == 0: self.null_to_parent(ctx, cls, sub_value, parent, sub_name, **kwargs) continue tr_attrib = {} if self.row_class is not None: tr_attrib['class'] = self.row_class with parent.element('tr', tr_attrib): th_attrib = {} if self.header_cell_class is not None: th_attrib['class'] = self.header_cell_class if self.field_name_attr is not None: th_attrib[self.field_name_attr] = sub_name if self.produce_header: parent.write(E.th( self.trc(v, ctx.locale, sub_name), **th_attrib )) td_attrib = {} if self.cell_class is not None: td_attrib['class'] = self.cell_class if self.field_name_attr is not None: td_attrib[self.field_name_attr] = sub_name with parent.element('td', td_attrib): ret = self.to_parent(ctx, v, sub_value, parent, sub_name, **kwargs) if isgenerator(ret): try: while True: sv2 = (yield) ret.send(sv2) except Break as b: try: ret.throw(b) except StopIteration: pass
def render(self, container: list): for body_token in self.content: container.append(body_token.render()) if hasattr(container[-1], "endswith"): if container[-1].endswith(" "): container.append(E("br")) return container
def render(self): pieces = [] for element in self.content: if hasattr(element, "render"): pieces.append(element.render()) else: pieces.append(element) return E("li", *pieces)
def complex_model_to_parent(self, ctx, cls, inst, parent, name, from_arr=False, **kwargs): attrib = {} if self.table_name_attr is not None: attrib[self.table_name_attr] = cls.get_type_name() with parent.element('table', attrib, nsmap=NSMAP): with parent.element('tbody'): for k, v in cls.get_flat_type_info(cls).items(): try: sub_value = getattr(inst, k, None) except: # to guard against e.g. SQLAlchemy throwing NoSuchColumnError sub_value = None sub_name = v.Attributes.sub_name if sub_name is None: sub_name = k if sub_value is None and cls.Attributes.min_occurs == 0: self.null_to_parent(ctx, cls, sub_value, parent, sub_name, **kwargs) continue tr_attrib = {} if self.row_class is not None: tr_attrib['class'] = self.row_class with parent.element('tr', tr_attrib): th_attrib = {} if self.header_cell_class is not None: th_attrib['class'] = self.header_cell_class if self.field_name_attr is not None: th_attrib[self.field_name_attr] = sub_name if self.produce_header: parent.write(E.th( self.trc(v, ctx.locale, sub_name), **th_attrib )) td_attrib = {} if self.cell_class is not None: td_attrib['class'] = self.cell_class if self.field_name_attr is not None: td_attrib[self.field_name_attr] = sub_name with parent.element('td', td_attrib): ret = self.to_parent(ctx, v, sub_value, parent, sub_name, **kwargs) if isgenerator(ret): try: while True: sv2 = (yield) ret.send(sv2) except Break as b: try: ret.throw(b) except StopIteration: pass
def __init__(self, app=None, ignore_uncap=False, ignore_wrappers=False, cloth=None, cloth_parser=None, polymorphic=True, doctype="<!DOCTYPE html>", root_tag='div', child_tag='div', field_name_attr='class', field_name_tag=None, field_name_class='field_name', before_first_root=None): """Protocol that returns the response object according to the "html microformat" specification. See https://en.wikipedia.org/wiki/Microformats for more info. The simple flavour is like the XmlDocument protocol, but returns data in <div> or <span> tags. :param app: A spyne.application.Application instance. :param root_tag: The type of the root tag that encapsulates the return data. :param child_tag: The type of the tag that encapsulates the fields of the returned object. :param field_name_attr: The name of the attribute that will contain the field names of the complex object children. """ super(HtmlMicroFormat, self).__init__(app=app, ignore_uncap=ignore_uncap, ignore_wrappers=ignore_wrappers, cloth=cloth, cloth_parser=cloth_parser, polymorphic=polymorphic, hier_delim=None, doctype=doctype) if six.PY2: text_type = basestring else: text_type = str assert isinstance(root_tag, text_type) assert isinstance(child_tag, text_type) assert isinstance(field_name_attr, text_type) assert field_name_tag is None or isinstance(field_name_tag, text_type) self.root_tag = root_tag self.child_tag = child_tag self.field_name_attr = field_name_attr self.field_name_tag = field_name_tag if field_name_tag is not None: self.field_name_tag = E(field_name_tag) self._field_name_class = field_name_class if before_first_root is not None: self.event_manager.add_listener("before_first_root", before_first_root) self.serialization_handlers = cdict({ Array: self.array_to_parent, AnyUri: self.anyuri_to_parent, AnyHtml: self.html_to_parent, ImageUri: self.imageuri_to_parent, ByteArray: self.not_supported, ModelBase: self.model_base_to_parent, ComplexModelBase: self.complex_model_to_parent, })
def __init__(self, form, handler, url='', method='post', submit_label=None): self._handler = handler self._element = E.form(action=url, method=method) self._add_xsrf_field() self.add_all(form) if submit_label: self._add_submit(submit_label)
def serialize(self, ctx, message): """Uses ``ctx.out_object``, ``ctx.out_header`` or ``ctx.out_error`` to set ``ctx.out_body_doc``, ``ctx.out_header_doc`` and ``ctx.out_document`` as an ``lxml.etree._Element instance``. Not meant to be overridden. """ assert message in (self.REQUEST, self.RESPONSE) self.event_manager.fire_event('before_serialize', ctx) if ctx.out_stream is None: ctx.out_stream = StringIO() if ctx.out_error is not None: # All errors at this point must be Fault subclasses. inst = ctx.out_error cls = inst.__class__ name = cls.get_type_name() ctx.out_document = E.div() from lxml import etree with etree.xmlfile(ctx.out_stream) as xf: retval = HtmlBase.HtmlMicroFormat() \ .to_parent(ctx, cls, inst, xf, name) else: assert message is self.RESPONSE result_message_class = ctx.descriptor.out_message name = result_message_class.get_type_name() if ctx.descriptor.body_style == BODY_STYLE_WRAPPED: if self.ignore_wrappers: ctx.out_object = ctx.out_object[0] result_message = ctx.out_object while result_message_class.Attributes._wrapper: result_message_class = next( iter(result_message_class._type_info.values())) else: result_message = result_message_class() for i, attr_name in enumerate( result_message_class._type_info.keys()): setattr(result_message, attr_name, ctx.out_object[i]) else: result_message = ctx.out_object retval = self.incgen(ctx, result_message_class, result_message, name) self.event_manager.fire_event('after_serialize', ctx) return retval
def serialize(self, ctx, message): """Uses ``ctx.out_object``, ``ctx.out_header`` or ``ctx.out_error`` to set ``ctx.out_body_doc``, ``ctx.out_header_doc`` and ``ctx.out_document`` as an ``lxml.etree._Element instance``. Not meant to be overridden. """ assert message in (self.REQUEST, self.RESPONSE) self.event_manager.fire_event('before_serialize', ctx) if ctx.out_stream is None: ctx.out_stream = StringIO() if ctx.out_error is not None: # All errors at this point must be Fault subclasses. inst = ctx.out_error cls = inst.__class__ name = cls.get_type_name() ctx.out_document = E.div() from lxml import etree with etree.xmlfile(ctx.out_stream) as xf: retval = HtmlBase.HtmlMicroFormat() \ .to_parent(ctx, cls, inst, xf, name) else: assert message is self.RESPONSE result_message_class = ctx.descriptor.out_message name = result_message_class.get_type_name() if ctx.descriptor.body_style == BODY_STYLE_WRAPPED: if self.ignore_wrappers: ctx.out_object = ctx.out_object[0] result_message = ctx.out_object while result_message_class.Attributes._wrapper: result_message_class = next(iter( result_message_class._type_info.values())) else: result_message = result_message_class() for i, attr_name in enumerate( result_message_class._type_info.keys()): setattr(result_message, attr_name, ctx.out_object[i]) else: result_message = ctx.out_object retval = self.incgen(ctx, result_message_class, result_message, name) self.event_manager.fire_event('after_serialize', ctx) return retval
def _build_pixfield(self, pixfield_element): pixfield_element.append( E.rect(width="100%", height="100%", style="fill: black;")) attributes = [make_attributes(key, count) for key, count in self._messages_dict.items()] for attribute in attributes: pixfield_element.append( E.circle( cx="{0}%".format(attribute.x), cy="{0}%".format(attribute.y), r="{0}px".format(attribute.size), style="fill:rgb({0}, {1}, {2})".format( int(attribute.red * 255), int(attribute.green * 255), int(attribute.blue * 255) ), ) )
def _build_html_head(self): '''Add title, metadata, and styles''' self.elements.head.append(E.meta(charset='UTF-8')) self._build_html_title() for key, value in self._default_meta_values: self.meta[key] = value self._build_html_head_meta() self._build_html_head_links() self._build_html_stylesheets()
def build_content(self): pixfield_element = E.svg(id='textshow-pixfield', width="100%", height="100%") self.elements.content.append(pixfield_element) html_form = HTMLForm(self._form, self.handler, submit_label=self.T('Submit')) form_element = html_form.to_html() form_element.set('id', 'textshow-form') self.elements.content.append(form_element) self._build_pixfield(pixfield_element) self.add_footer()
def imageuri_to_parent(self, ctx, cls, inst, parent, name, **kwargs): # with ImageUri, content is ignored. href = getattr(inst, 'href', None) if href is None: # this is not a AnyUri.Value instance. href = inst text = getattr(cls.Attributes, 'text', None) else: text = getattr(inst, 'text', None) if text is None: text = getattr(cls.Attributes, 'text', None) retval = E.img(src=href) if text is not None: retval.attrib['alt'] = text parent.write(retval)