Un/bound methods in Cheetah - python

Is there a way to declare static methods in cheetah? IE
snippets.tmpl
#def address($address, $title)
<div class="address">
<b>$title</h1></b>
#if $address.title
$address.title <br/>
#end if
$address.line1 <br/>
#if $address.line2
$address.line2 <br/>
#end if
$address.town, $address.state $address.zipcode
</div>
#end def
....
other snippets
other.tmpl
#from snippets import *
$snippets.address($home_address, "home address")
This code reports this error: NotFound: cannot find 'address'. Cheetah is compiling it as a bound method, natch:
snippets.py
class snippets(Template):
...
def address(self, address, title, **KWS):
Is there a way to declare static methods? If not, what are some alternative ways to implement something like this (a snippets library)?

This page seems to have some relevant information, but I'm not in a position to try it out myself right now, sorry.
Specifically, you should just be able to do:
##staticmethod
#def address($address, $title)
...and have it work.
(If you didn't know, staticmethod is a built-in function that creates a... static method :) It's most commonly used as a decorator. So I found that page by Googling "cheetah staticmethod".)

Related

Realtime(ish) updates on Web Page using AppEngine

I'm using AppEngine to create a page that I would like to update from the program. Specifically, I am getting some market data and would like to have a table (or something else appropriate) that shows current prices. Let me be clear: I am new to this and think my problem is that I'm not asking the question well enough to find a good (best) answer. I'm not even sure AppEngine is necessarily the way to go. I'll also caveat that I've been learning via Udacity so if code looks familiar -- kudos to Steve Huffman.
I've created the page via jinja2 and I've managed to wrangle the appropriate libraries and sandbox parameters to get market updates. I've created an html table and passed in a dictionary with values for exchanges and bid/ask pairs. The table creates fine -- but when I render again, I get tables repeating down the page rather than one table with updating market prices.
Here is the html/jinja2 (I ditched all the styling to make it shorter):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Table template</title>
</head>
<body>
<h1>Table template</h1>
<table>
{% for exch in mkt_data %}
<tr>
<td> <div>{{exch}}</div></td>
<td> <div>{{mkt_data[exch][0]}}</div></td>
<td><div>{{mkt_data[exch][1]}}</div></td>
</tr>
{% endfor %}
</table>
</body>
</html>
Here is the code:
import os
import jinja2
import webapp2
import ccxt
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape=True)
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
class MainPage(Handler):
def get(self):
self.render("table.html", mkt_data=btc)
for x in range(3):
for exch in exchanges:
orderbook=exch.fetch_order_book('BTC/USD')
bid = orderbook['bids'][0][0] if len(orderbook['bids'])>0 else None
ask = orderbook['asks'][0][0] if len(orderbook['asks'])>0 else None
btc[exch.id]=[bid,ask]
self.render("table.html", mkt_data=btc)
gdax = ccxt.gdax()
gemini = ccxt.gemini()
exchanges = [gdax, gemini]
btc = {"gemini":[0,1], "gdax":[1,2]}
for exch in exchanges:
exch.load_markets()
app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
I have 2 questions:
First, why am I getting the table repeating? I think I know why, but I want to hear a formal reason.
Second, what should I be doing? I originally started learning javascript/node but then it seemed very hard to wrap all the appropriate libraries (was looking into browserify but then thought appengine may be better so I could more easily host something for others to see). I tried integrating some javascript but that did not get me anywhere. Now I've run into Firebase but before I go learn yet another "thing" I wanted to ask how other people do this. I'm certain there are multiple ways but I'm new to web programming; I'm viewing a web page as a nice UI & delivery mechanism.
Some add'l notes: using Ubuntu, virtualenv, ccxt library (for cryptocurrency).
edit: I checked Dan's answer because it offered a solution. I'd love to hear about whether Firebase is "a" more correct solution rather than auto-refreshing.
The repeated table is the result of the multiple self.render() calls inside your MainPage.get() - both above and repetead ones inside the for loop(s).
Update your code to make a single such call, after the for loops building the template values (at the end of MainPage.get())

Getting specific part of <div> from webpage

I am currently using aiohttp and lxml to scrape webpages and return values. So far, I have
def get_sr(page, tree):
sr = tree.xpath(".//div[#class='competitive-rank']/div/text()")[0]
return sr
def get_icon_url(page, tree):
url = tree.xpath('.//img[#class="player-portrait"]/#src')[0]
return url
def get_sr_icon_url(page, tree):
url = tree.xpath('.//div[#class="competitive-rank"]/img/#src')[0]
return url
def get_level(page, tree):
level = tree.xpath('.//div[#class="header-avatar"]/text()')[0]
return level
The first 3 functions work perfectly, and yet the final function will not correctly get the text I am looking for. This:
<div class="header-avatar">
<img src="https://blzgdapipro-a.akamaihd.net/game/unlocks/0x0250000000001150.png" width="80" height="80">
<span>369</span>
</div>
Is the code block I am trying to get the number from. Currently, the number is 369 but it constantly changes. I have confirmed that the page and tree are correct through print statements, so instead it's an issue w/ the actual get_level method itself.
Help? Other pieces of code needed to determine issue?
Thank you for the help.
Try this:
level = tree.xpath('.//div[#class="header-avatar"]/span/text()')[0]

Extending Jinja's {% trans %} to use JavaScript variables

I'd like to extend the behaviour of trans by rendering variables not as as values from the context, but instead as html (without using the context). My aim is to be able to populate those variables on the client through JavaScript.
Jinja as it seems doesn't allow for a great deal of customisation of this kind or I'm just unable to find the right hooks.
Here's what I'd like to achieve:
{% etrans name=username %}
My name is {{ name }}
{% endetrans %}
This should render to:
My name is <span id='#username'></span>
Of course, I could just use the normal {% trans %} directive and pass my html code to template.render(html_code_params), but that would require to have them defined in the template and the rendering code which I'd like to avoid.
Here's what I got so far (not much) which allows for a new etrans tag and the ability to use whatever goodies InternationalizationExtension has to offer.
from jinja2.ext import InternationalizationExtension
from jinja2.runtime import concat
class JavaScriptVariableExtension(InternationalizationExtension):
tagname = 'etrans'
tags = set([tagname])
def _parse_block(self, parser, allow_pluralize):
"""Parse until the next block tag with a given name.
Copy from InternationalizationExtension, as this uses hardcoded
`name:endtrans` instead of relying on tag name
"""
referenced = []
buf = []
while 1:
if parser.stream.current.type == 'data':
buf.append(parser.stream.current.value.replace('%', '%%'))
next(parser.stream)
elif parser.stream.current.type == 'variable_begin':
next(parser.stream)
name = parser.stream.expect('name').value
referenced.append(name)
buf.append('%%(%s)s' % name)
parser.stream.expect('variable_end')
elif parser.stream.current.type == 'block_begin':
next(parser.stream)
# can't use hardcoded "endtrans"
# if parser.stream.current.test('name:endtrans'):
if parser.stream.current.test('name:end%s' % self.tagname):
break
elif parser.stream.current.test('name:pluralize'):
if allow_pluralize:
break
parser.fail('a translatable section can have only one '
'pluralize section')
parser.fail('control structures in translatable sections are '
'not allowed')
elif parser.stream.eos:
parser.fail('unclosed translation block')
else:
assert False, 'internal parser error'
return referenced, concat(buf)
i18n_extended = JavaScriptVariableExtension
I don't mind overloading more methods (although the reason for above one should perhaps fixed upstream).
Stepping through the code is quite an interesting adventure. However, I hit a snag and am interested if anyone can give some advice.
The problem I see is that during the compilation, the function context.resolve() gets baked into the compiled code. jinja2.jinja2.compiler.CodeGenerator doesn't really allow any different handling here (correct me if I'm wrong). Ideally, I would define another node (for the variable) and this node would handle the way it's dealt with during compilation, but I don't see how this is possible. I might be too focussed on this as a solution, so perhaps someone can provide alternatives.
As suggested by #Garrett's comment, a much easier solution is to pass in a function to the template renderer that interpolates the variables. In my case, my target client-side framework is Angular, but this also works for any JS variables that you want to use within a {% trans %} environment. Here are the building blocks:
def text_to_javascript(string):
# modify as needed...
return "<span>{{ %s }}</span>" % string
def render():
tmpl = jinja_env.get_template(template_filename)
return tmpl.render({'js': text_to_javascript})
And this how I make use of it in the template file:
{% trans username=js('user.name') %}
My name is {{ username }}
{% endtrans %}
In the Angular controller, the variable user is bound to the $scope like so:
$scope.user = {'name': 'Bugs Bunny'}

Generating HTML documents in python

In python, what is the most elegant way to generate HTML documents. I currently manually append all of the tags to a giant string, and write that to a file. Is there a more elegant way of doing this?
You can use yattag to do this in an elegant way. FYI I'm the author of the library.
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('html'):
with tag('body'):
with tag('p', id = 'main'):
text('some text')
with tag('a', href='/my-url'):
text('some link')
result = doc.getvalue()
It reads like html, with the added benefit that you don't have to close tags.
I would suggest using one of the many template languages available for python, for example the one built into Django (you don't have to use the rest of Django to use its templating engine) - a google query should give you plenty of other alternative template implementations.
I find that learning a template library helps in so many ways - whenever you need to generate an e-mail, HTML page, text file or similar, you just write a template, load it with your template library, then let the template code create the finished product.
Here's some simple code to get you started:
#!/usr/bin/env python
from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django
# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""
t = Template(template)
c = Context({"title": "title from code",
"mystring":"string from code"})
print t.render(c)
It's even simpler if you have templates on disk - check out the render_to_string function for django 1.7 that can load templates from disk from a predefined list of search paths, fill with data from a dictory and render to a string - all in one function call. (removed from django 1.8 on, see Engine.from_string for comparable action)
If you're building HTML documents than I highly suggest using a template system (like jinja2) as others have suggested. If you're in need of some low level generation of html bits (perhaps as an input to one of your templates), then the xml.etree package is a standard python package and might fit the bill nicely.
import sys
from xml.etree import ElementTree as ET
html = ET.Element('html')
body = ET.Element('body')
html.append(body)
div = ET.Element('div', attrib={'class': 'foo'})
body.append(div)
span = ET.Element('span', attrib={'class': 'bar'})
div.append(span)
span.text = "Hello World"
if sys.version_info < (3, 0, 0):
# python 2
ET.ElementTree(html).write(sys.stdout, encoding='utf-8',
method='html')
else:
# python 3
ET.ElementTree(html).write(sys.stdout, encoding='unicode',
method='html')
Prints the following:
<html><body><div class="foo"><span class="bar">Hello World</span></div></body></html>
There is also a nice, modern alternative: airium: https://pypi.org/project/airium/
from airium import Airium
a = Airium()
a('<!DOCTYPE html>')
with a.html(lang="pl"):
with a.head():
a.meta(charset="utf-8")
a.title(_t="Airium example")
with a.body():
with a.h3(id="id23409231", klass='main_header'):
a("Hello World.")
html = str(a) # casting to string extracts the value
print(html)
Prints such a string:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8" />
<title>Airium example</title>
</head>
<body>
<h3 id="id23409231" class="main_header">
Hello World.
</h3>
</body>
</html>
The greatest advantage of airium is - it has also a reverse translator, that builds python code out of html string. If you wonder how to implement a given html snippet - the translator gives you the answer right away.
Its repository contains tests with example pages translated automatically with airium in: tests/documents. A good starting point (any existing tutorial) - is this one: tests/documents/w3_architects_example_original.html.py
I would recommend using xml.dom to do this.
http://docs.python.org/library/xml.dom.html
Read this manual page, it has methods for building up XML (and therefore XHTML). It makes all XML tasks far easier, including adding child nodes, document types, adding attributes, creating texts nodes. This should be able to assist you in the vast majority of things you will do to create HTML.
It is also very useful for analysing and processing existing xml documents.
Here is a tutorial that should help you with applying the syntax:
http://www.postneo.com/projects/pyxml/
I am using the code snippet known as throw_out_your_templates for some of my own projects:
https://github.com/tavisrudd/throw_out_your_templates
https://bitbucket.org/tavisrudd/throw-out-your-templates/src
Unfortunately, there is no pypi package for it and it's not part of any distribution as this is only meant as a proof-of-concept. I was also not able to find somebody who took the code and started maintaining it as an actual project. Nevertheless, I think it is worth a try even if it means that you have to ship your own copy of throw_out_your_templates.py with your code.
Similar to the suggestion to use yattag by John Smith Optional, this module does not require you to learn any templating language and also makes sure that you never forget to close tags or quote special characters. Everything stays written in Python. Here is an example of how to use it:
html(lang='en')[
head[title['An example'], meta(charset='UTF-8')],
body(onload='func_with_esc_args(1, "bar")')[
div['Escaped chars: ', '< ', u'>', '&'],
script(type='text/javascript')[
'var lt_not_escaped = (1 < 2);',
'\nvar escaped_cdata_close = "]]>";',
'\nvar unescaped_ampersand = "&";'
],
Comment('''
not escaped "< & >"
escaped: "-->"
'''),
div['some encoded bytes and the equivalent unicode:',
'你好', unicode('你好', 'utf-8')],
safe_unicode('<b>My surrounding b tags are not escaped</b>'),
]
]
I am attempting to make an easier solution called
PyperText
In Which you can do stuff like this:
from PyperText.html import Script
from PyperText.htmlButton import Button
#from PyperText.html{WIDGET} import WIDGET; ex from PyperText.htmlEntry import Entry; variations shared in file
myScript=Script("myfile.html")
myButton=Button()
myButton.setText("This is a button")
myScript.addWidget(myButton)
myScript.createAndWrite()
I wrote a simple wrapper for the lxml module (should work fine with xml as well) that makes tags for HTML/XML -esq documents.
Really, I liked the format of the answer by John Smith but I didn't want to install yet another module to accomplishing something that seemed so simple.
Example first, then the wrapper.
Example
from Tag import Tag
with Tag('html') as html:
with Tag('body'):
with Tag('div'):
with Tag('span', attrib={'id': 'foo'}) as span:
span.text = 'Hello, world!'
with Tag('span', attrib={'id': 'bar'}) as span:
span.text = 'This was an example!'
html.write('test_html.html')
Output:
<html><body><div><span id="foo">Hello, world!</span><span id="bar">This was an example!</span></div></body></html>
Output after some manual formatting:
<html>
<body>
<div>
<span id="foo">Hello, world!</span>
<span id="bar">This was an example!</span>
</div>
</body>
</html>
Wrapper
from dataclasses import dataclass, field
from lxml import etree
PARENT_TAG = None
#dataclass
class Tag:
tag: str
attrib: dict = field(default_factory=dict)
parent: object = None
_text: str = None
#property
def text(self):
return self._text
#text.setter
def text(self, value):
self._text = value
self.element.text = value
def __post_init__(self):
self._make_element()
self._append_to_parent()
def write(self, filename):
etree.ElementTree(self.element).write(filename)
def _make_element(self):
self.element = etree.Element(self.tag, attrib=self.attrib)
def _append_to_parent(self):
if self.parent is not None:
self.parent.element.append(self.element)
def __enter__(self):
global PARENT_TAG
if PARENT_TAG is not None:
self.parent = PARENT_TAG
self._append_to_parent()
PARENT_TAG = self
return self
def __exit__(self, typ, value, traceback):
global PARENT_TAG
if PARENT_TAG is self:
PARENT_TAG = self.parent

cheetah template importing functions

So I am having some trouble trying to import functions and run them inside my cheetah templates.
So I have one file that lives at /docroot/tmpl/base.html
and then another file that is /docroot/tmpl/comments.html
inside of comments I have something that looks like this
#def generateComments($commentObj):
code for generating comments
#end def
then inside of base.html I want to have a syntax like this
#import docroot.tmpl.comments as comments
<div class="commentlist">
$comments.generateComments($commentObj)
</div>
However when I run that output I just get the contents of comments.html printed out including the #def generateComments in raw txt.'
What am I missing?
Cheetah compiles templates to Python classes. When you import comments module the module consists of a single class also named comments. You need to explicitly instantiate the class and call its generateComments method. So your code should be
#from docroot.tmpl import comments
<div class="commentlist">
$comments.comments().generateComments($commentObj)
</div>
The first comments is a module, comments.comments is a template class in the module, comments.comments() is an instance of the class, comments.comments().generateComments($commentObj) is a call to its method. To simplify the code a bit import the class:
#from docroot.tmpl.comments import comments
<div class="commentlist">
$comments().generateComments($commentObj)
</div>

Categories