<?xml version="1.0" encoding="UTF-8"?>
<feed
  xmlns="http://www.w3.org/2005/Atom"
  xmlns:thr="http://purl.org/syndication/thread/1.0"
  xml:lang="en"
   >
  <title type="text">zzzeek</title>
  <subtitle type="text">mostly computer stuff</subtitle>

  <updated>2012-02-07T16:16:27Z</updated>
  <generator uri="http://blogofile.com/">Blogofile</generator>

  <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org" />
  <id>http://techspot.zzzeek.org/feed/atom/</id>
  <link rel="self" type="application/atom+xml" href="http://techspot.zzzeek.org/feed/atom/" />
  <entry>
    <author>
      <name></name>
      <uri>http://techspot.zzzeek.org</uri>
    </author>
    <title type="html"><![CDATA[Thoughts on Beaker]]></title>
    <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org/2011/10/01/thoughts-on-beaker" />
    <id>http://techspot.zzzeek.org/2011/10/01/thoughts-on-beaker</id>
    <updated>2011-10-01T16:01:00Z</updated>
    <published>2011-10-01T16:01:00Z</published>
    <category scheme="http://techspot.zzzeek.org" term="Code" />
    <category scheme="http://techspot.zzzeek.org" term="Mako/Pylons" />
    <summary type="html"><![CDATA[Thoughts on Beaker]]></summary>
    <content type="html" xml:base="http://techspot.zzzeek.org/2011/10/01/thoughts-on-beaker"><![CDATA[<div class="document">
<p><a class="reference external" href="http://pypi.python.org/pypi/Beaker">Beaker</a> is a
widely used caching and HTTP session library published by Ben Bangert.
It dates back to the
early days of Pylons, when Pylons moved off of the Myghty
base to the Python Paste infrastructure.  Beaker's guts in fact were originally the internals
to the caching and session system of Myghty itself, which in turn was loosely based on the caching
code from HTML::Mason (which if those two colons don't look familiar means we've made the jump
across the ages to Perl).</p>
<p>The key neato thing nestled deep inside of Beaker is what
I later was told is called a &quot;dogpile lock&quot;. This is a
simple, but slightly less simple than <tt class="docutils literal">dict.get()</tt> type
of system whereby the cache can put one thread to work on
generating a new value for a certain cache key, while all
the other threads and even other processes can all
continue to return the expired value, until the new value
is ready. I spent weeks
getting this aspect to do what it was supposed to. It
does things in a slightly more complex but comprehensive
way than Mason did; it coordinates workers using a mutex
and/or lockfiles, instead of a simple counter that
estimates the creation time for a new value.</p>
<p>The storage backends are implemented in terms of a &quot;container&quot;, which deals with
an individual key, including checking if it's expired, regenerating it, and so forth,
and a &quot;namespace&quot;, which is the entryway to storing the data.   It deals with keys and
values like everything else does, and has backends for pickled files, DBM files, relational
databases, memcached, and GAE.   The general idea here came from Myghty but has been
highly modified since then.</p>
<p>Beaker then adds something of a coarse-grained facade over this model, including something
of a generic get/put API as well as a system of function decorators that cache the return
value of a function.  In recent releases it also supports the notion of a &quot;region&quot;, which
is just a way to package up a particular cache configuration under a single name that can later
be referenced by high level caching operations.</p>
<p>Beaker also implements an HTTP session object on top of the same storage backends, taking this from
Myghty as well.   Implementing HTTP sessions on top of the cache backends was a completely off-the-cuff
idea in Myghty, and over the years in Beaker it's had to be wrangled and re-wrangled over basic issues resulting
from this mismatch.</p>
<p>As far as the backends themselves, at this point all of
them have accumulated a fair degree of woe. The file- and
DBM- backends basically perform pretty poorly (DBM maybe
not as much). The memcached backend has always been
problematic - we slowly learned that the <tt class="docutils literal">cmemcache</tt>
library is basically a non starter, and that <tt class="docutils literal">pylibmc</tt>
is dramatically faster than the usual <tt class="docutils literal">memcache</tt>
library. The memcached backend slowly sprouted an awkward
way to select among these backends and more awkwardness to
attempt to accommodate pylibmc's special concurrency API.
Then when users started combining the memcached backend
with HTTP sessions, all kinds of new issues occurred,
namely that any particular key might be removed from
memcached at any time, that caused us to rework the
session implementation even more awkwardly to store the
whole session under one &quot;key&quot;, defeating the purpose of
how the session object works with other backends.  As for the SQLAlchemy backends, there are two, and I've
no idea why.</p>
<p>The HTTP session as a &quot;bag of random keys&quot;, to paraphrase
a term I think PJE originally used, is not something I
really do these days, as I'm pretty skeptical of the approach of
storing a bag of key/value pairs inside of a big
serialized BLOB as a solution to anything, really. A few keys in a cookie-based
session of very limited size is fine. But a
backend-oriented system where you're loading up a giant
bag of dozens of keys referencing full object structures
inside of a good sized serialized blob inside of a file,
database, or memcached-type of system, is both horribly
inefficient and a sign of sloppy, ad-hoc coding.</p>
<p>Beaker eventually provided a purely client side encrypted
cookie session as an alternative to the server-based
sessions. This session implementation stores all the data
in an encrypted string (Ben spent a <em>lot</em> of time and got
a lot of advice getting the encryption right here) which
is stored completely on the client. All of the
performance, scalability and failover issues introduced
by typical memory or file based HTTP session
implementations is solved immediately.   So this session implementation,
I use lots.    I only put a few critical keys in it to track the user, but
anything that is more significant is part of the object model which is persisted
in the database as a first class object.</p>
<p>The only downside to the cookie-only session is that, unless you coordinate the state
of the session with server-side state (which IMHO you should), you can't &quot;force&quot; it
to expire sooner than it normally would, or otherwise prevent the replay of previous
state, within an attack scenario.   While an attacker can't craft a
session, (s)he can re-use the same cookie over and over again, and that can only
be guarded against by comparing its state to that of a memo on the server; a single
&quot;generation&quot; counter can achieve this.  I.e. session comes in, generation is &quot;5&quot;,
the server says it should be &quot;7&quot;, reject it.   So it may be considered that
this turns the encrypted cookie session into a
fancy session cookie for a server-side session.  But I am actually OK with that.
I put very, very little into unstructured sessions.</p>
<p>What I'm getting at here is that I'm not super-interested in most of what Beaker has - a lot of the
APIs are awkward, all of the storage backends are either mostly useless or
slow and crufty, and I don't care much for the server-side
session thing especially using backends that were designed for caching.     Overall Beaker
creates a coarse opacity on top of a collection of things that I think good application developers should be
much more aware of.   I really think developers should know how their tools work.</p>
<p>Beaker has some isolated features which I think are
great. These are the dogpile lock, the encrypted
client-side cookie session, the concept of &quot;cache
regions&quot; whereby a set of cache configuration is
referencable by a single name, and some nice function
decorators - these allow you to apply caching to a
function, similarly to:</p>


<div class="pygments_manni"><pre>@cached(region=&quot;file_based&quot;, namespace=&quot;somenamespace&quot;)
def return_some_data(x, y, z):
    # ...
</pre></div>



<p>I'm not sure what's in store for Beaker.   But what I'm doing is:</p>
<ul class="simple">
<li>Created <a class="reference external" href="http://pypi.python.org/pypi/Dogpile">Dogpile</a>, which is just the &quot;dogpile lock&quot; portion of Beaker, cleaned up and
turned into a very clear, succinct system which you can use to build your own caching implementation.   The README
includes a full example using Pylibmc.</li>
<li>In Mako, for either 0.5.1 or 0.6.0 (not sure yet, though I just put out 0.5.0 the other day for unrelated reasons)
the built-in Beaker support is genericized into a plugin system.  You
can write your own plugins very easily for Mako using Dogpile or similar, if you want caching inside your templates that
isn't based off of Beaker.  The system supports entrypoints so if a Beaker2 comes out, it would publish a cache backend
that Mako could then use.</li>
</ul>
<p>So we have that.  Then, for the community I would like to see:</p>
<ul class="simple">
<li>The solution for the key/value backend (or not).  Today, high-performance, sophisticated
key/value stores are ubiquitous. We of course have
<a class="reference external" href="http://memcached.org/">memcached</a>. We also have
<a class="reference external" href="http://wiki.basho.com/">Riak</a> and <a class="reference external" href="http://redis.io/">Redis</a> which appear very feasible for
temporary storage, I'm not sure if <a class="reference external" href="http://fallabs.com/tokyotyrant/">Tokyo Tyrant</a> is still popular.
And of course there's the more permanent-oriented systems like Mongo
and Cassandra. I am <em>sure</em> that someone has built some
kind of generic facade over these, and there are
probably many. These are the key/value systems you
should be using, either via a modern facade or one of
the libraries directly; Beaker's system, which was
originally built to store keys inside of dictionaries
or pickled files, is absolutely nothing more than a
quaint, historical novelty in comparison.</li>
<li>A new library that is just the encrpyted cookie session.  I'd use this.  It would be very nice
for this portion of Beaker to be its own thing.   Until then I may just rip out that part
of Beaker and stick it in a lib/ folder somewhere in my work projects for internal use.</li>
<li>For server-side HTTP sessions, I really think people should be rolling solutions for this as needed,
probably using the encrypted cookie session for client side state linked to first class model objects
in the datastore (relational or non-relational, doesn't matter).   If accessing the datastore is a performance
issue, you'd be using caching for those data structures, the same way you'd cache data structures
that are not specific to a user (probably based on primary key or on their originating query).
In the end this is similar to HTTP sessions stored directly in the cache backend, except there's a
well defined model layer in between.</li>
<li>People that really insist on the pattern of server-side HTTP sessions as bags of keys inside
of serialized blobs on a server should be served by some new library that someone
else can maintain.  I think I am done with supporting this pattern and I think Ben may
be as well.</li>
</ul>
<p>The theme I've been pushing in my recent talk on
SQLAlchemy and I think I'm pushing here, is that if
you're writing a big application, one which you'll be
spending months or years with, it is very much worth it
to spend some time spending a day or so building up
foundational patterns. I really have never understood the
point of, &quot;I just got the whole app up and running
from start to finish on the plane!&quot; Well great, you got
the app up in three hours, now you can spend the next six
months reworking the whole thing to actually scale (or if it
was only a proof-of-concept, then why does it need a cache or even
a database?).  Did
three hours for a quick and dirty implementation versus three days to do it right
really improve your life within the scope of the total time spent?
Breaking up Beaker into components and encouraging people to use patterns
instead of relying upon opaque, pushbutton libraries is part of that idea.</p>
</div>
]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://techspot.zzzeek.org</uri>
    </author>
    <title type="html"><![CDATA[My Blogofile Hacks]]></title>
    <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org/2010/12/06/my-blogofile-hacks" />
    <id>http://techspot.zzzeek.org/2010/12/06/my-blogofile-hacks</id>
    <updated>2010-12-07T00:26:00Z</updated>
    <published>2010-12-07T00:26:00Z</published>
    <category scheme="http://techspot.zzzeek.org" term="Code" />
    <category scheme="http://techspot.zzzeek.org" term="Mako/Pylons" />
    <summary type="html"><![CDATA[My Blogofile Hacks]]></summary>
    <content type="html" xml:base="http://techspot.zzzeek.org/2010/12/06/my-blogofile-hacks"><![CDATA[<div class="document">
<p><strong>Update:</strong> - Spurred on by
<a class="reference external" href="http://danielnouri.org/notes/2010/01/24/bye-bye-zine,-hello-blogofile!/">Daniel Nouri</a>,
configuration examples have been upgraded to 0.7.</p>
<p>I'm having a completely great time with <a class="reference external" href="http://www.blogofile.com">Blogofile</a>. Publishing the whole site static and in one
step, letting <a class="reference external" href="http://www.disqus.com">Disqus</a> handle all the community is so
much better than worrying about <a class="reference external" href="/2010/11/21/how-coders-blog">upgrades and spam</a>. I've noticed some other folks using Blogofile
and I wanted to share the key changes I used to make it work the way I want.
Ideally, Blogofile itself could provide these features since they are pretty
basic; I'm being somewhat lazy by just posting them here rather than
requesting features via the BF mailing list, but the changes aren't generic to
a plain Blogofile install so they would need to be &quot;featurized&quot; in order to be
part of Blogofile's default setup. Until then, these adjustments work right
now for an 0.6 installation.</p>
<div class="section" id="getting-syntax-highlighting-to-work-with-rest">
<h1>Getting Syntax Highlighting to work with ReST</h1>
<p>We're all using <a class="reference external" href="http://sphinx.pocoo.org">Sphinx</a> for our docs now so we've
all become experts at <a class="reference external" href="http://docutils.sourceforge.net/">Restructured Text</a>.
I know this because I can actually type out <tt class="docutils literal">`[text] <span class="pre">&lt;[hyperlink]&gt;`_</span></tt> from
memory. Blogofile supports .rst but the syntax highlighting that's included
appears to be tailored towards Markdown. My approach here to allow .rst
highlighting is not as nice as that of Sphinx since I continue to be very
mystified by Docutils, but it gets the job done.</p>
<div class="section" id="step-1-put-the-rst-filter-first">
<h2>Step 1 - Put the RST Filter First</h2>
<p>We'll be using Docutils' built in system of <tt class="docutils literal">::</tt> followed by indentation to
establish a code block, so the syntax highlighter will detect the HTML
generated, instead of Blogofile's default approach of using a special tag
<tt class="docutils literal">$$code(lang=python)</tt> which doesn't make it through the rst parser in any
case (in fact it's the Pygments HTML the filter generates that doesn't).
Change the order in <tt class="docutils literal">_config.py</tt> as follows:</p>


<div class="pygments_manni"><pre><span class="n">blog</span><span class="o">.</span><span class="n">post_default_filters</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s">&quot;rst&quot;</span><span class="p">:</span> <span class="s">&quot;rst, syntax_highlight&quot;</span>
<span class="p">}</span>
</pre></div>



</div>
<div class="section" id="step-2-new-syntax-filter">
<h2>Step 2 - New Syntax Filter</h2>
<p>I don't need a lot of options in my code blocks other than what language is in
use. Below is a simplified <tt class="docutils literal">syntax_highlight.py</tt> that looks for a language
name using a comment of the form <tt class="docutils literal"><span class="pre">#!&lt;language</span> name&gt;</tt>:</p>


<div class="pygments_manni"><pre><span class="kn">import</span> <span class="nn">re</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="kn">from</span> <span class="nn">pygments</span> <span class="kn">import</span> <span class="n">util</span><span class="p">,</span> <span class="n">formatters</span><span class="p">,</span> <span class="n">lexers</span><span class="p">,</span> <span class="n">highlight</span>
<span class="kn">import</span> <span class="nn">blogofile_bf</span> <span class="kn">as</span> <span class="nn">bf</span>

<span class="n">css_files_written</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>

<span class="n">code_block_re</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span>
    <span class="s">r&quot;&lt;pre class=</span><span class="se">\&quot;</span><span class="s">literal-block</span><span class="se">\&quot;</span><span class="s">&gt;\n&quot;</span>
    <span class="s">r&quot;(?:#\!(?P&lt;lang&gt;\w+)\n)?&quot;</span>
    <span class="s">r&quot;(?P&lt;code&gt;.*?)&quot;</span>
    <span class="s">r&quot;&lt;/pre&gt;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">DOTALL</span>
<span class="p">)</span>

<span class="k">def</span> <span class="nf">highlight_code</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">language</span><span class="p">,</span> <span class="n">formatter</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">lexer</span> <span class="o">=</span> <span class="n">lexers</span><span class="o">.</span><span class="n">get_lexer_by_name</span><span class="p">(</span><span class="n">language</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">util</span><span class="o">.</span><span class="n">ClassNotFound</span><span class="p">:</span>
        <span class="n">lexer</span> <span class="o">=</span> <span class="n">lexers</span><span class="o">.</span><span class="n">get_lexer_by_name</span><span class="p">(</span><span class="s">&quot;text&quot;</span><span class="p">)</span>
    <span class="n">highlighted</span> <span class="o">=</span> <span class="s">&quot;</span><span class="se">\n\n</span><span class="s">&quot;</span> <span class="o">+</span> \
                  <span class="n">highlight</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">lexer</span><span class="p">,</span> <span class="n">formatter</span><span class="p">)</span> <span class="o">+</span> \
                  <span class="s">&quot;</span><span class="se">\n\n</span><span class="s">&quot;</span>
    <span class="k">return</span> <span class="n">highlighted</span>

<span class="k">def</span> <span class="nf">write_pygments_css</span><span class="p">(</span><span class="n">style</span><span class="p">,</span> <span class="n">formatter</span><span class="p">,</span> <span class="n">location</span><span class="o">=</span><span class="s">&quot;/css&quot;</span><span class="p">):</span>
    <span class="n">path</span> <span class="o">=</span> <span class="n">bf</span><span class="o">.</span><span class="n">util</span><span class="o">.</span><span class="n">path_join</span><span class="p">(</span><span class="s">&quot;_site&quot;</span><span class="p">,</span><span class="n">bf</span><span class="o">.</span><span class="n">util</span><span class="o">.</span><span class="n">fs_site_path_helper</span><span class="p">(</span><span class="n">location</span><span class="p">))</span>
    <span class="n">bf</span><span class="o">.</span><span class="n">util</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
    <span class="n">css_path</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">path</span><span class="p">,</span><span class="s">&quot;pygments_&quot;</span><span class="o">+</span><span class="n">style</span><span class="o">+</span><span class="s">&quot;.css&quot;</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">css_path</span> <span class="ow">in</span> <span class="n">css_files_written</span><span class="p">:</span>
        <span class="k">return</span> <span class="c">#already written, no need to overwrite it.</span>
    <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">css_path</span><span class="p">,</span><span class="s">&quot;w&quot;</span><span class="p">)</span>
    <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">formatter</span><span class="o">.</span><span class="n">get_style_defs</span><span class="p">(</span><span class="s">&quot;.pygments_&quot;</span><span class="o">+</span><span class="n">style</span><span class="p">))</span>
    <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="n">css_files_written</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">css_path</span><span class="p">)</span>

<span class="kn">from</span> <span class="nn">mako.filters</span> <span class="kn">import</span> <span class="n">html_entities_unescape</span>

<span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="n">src</span><span class="p">):</span>

    <span class="n">style</span> <span class="o">=</span> <span class="n">bf</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">filters</span><span class="o">.</span><span class="n">syntax_highlight</span><span class="o">.</span><span class="n">style</span>
    <span class="n">css_class</span> <span class="o">=</span> <span class="s">&quot;pygments_&quot;</span><span class="o">+</span><span class="n">style</span>
    <span class="n">formatter</span> <span class="o">=</span> <span class="n">formatters</span><span class="o">.</span><span class="n">HtmlFormatter</span><span class="p">(</span>
            <span class="n">linenos</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="n">cssclass</span><span class="o">=</span><span class="n">css_class</span><span class="p">,</span> <span class="n">style</span><span class="o">=</span><span class="n">style</span><span class="p">)</span>
    <span class="n">write_pygments_css</span><span class="p">(</span><span class="n">style</span><span class="p">,</span><span class="n">formatter</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">repl</span><span class="p">(</span><span class="n">m</span><span class="p">):</span>
        <span class="n">lang</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s">&#39;lang&#39;</span><span class="p">)</span>
        <span class="n">code</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s">&#39;code&#39;</span><span class="p">)</span>

        <span class="n">code</span> <span class="o">=</span> <span class="n">html_entities_unescape</span><span class="p">(</span><span class="n">code</span><span class="p">)</span>

        <span class="k">return</span> <span class="n">highlight_code</span><span class="p">(</span><span class="n">code</span><span class="p">,</span><span class="n">lang</span><span class="p">,</span><span class="n">formatter</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">code_block_re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">repl</span><span class="p">,</span> <span class="n">src</span><span class="p">)</span>
</pre></div>



<p>That's it.  All you do now when writing a code example:</p>


<div class="pygments_manni"><pre>This is some blog text.  Some code<span class="se">::</span>

<span class="s">    #!python</span>
<span class="s">    print &quot;hello world&quot;</span>
</pre></div>



</div>
</div>
<div class="section" id="permalinks">
<h1>Permalinks</h1>
<p>Blogofile's auto-permalink regular expression needs some serious help. Any
kind of punctuation characters or whatever just get dumped into the URL, and
there's no hook to change how the auto-permalink generation works. We
definitely don't want to have to type permalinks into all our posts that look
just like the titles.</p>
<p>With Blogofile 0.6, I had a post-processor in the <tt class="docutils literal">0.initial.py</tt> controller file
that rewrote the permalink on each <tt class="docutils literal">Post</tt> object.  As of Blogofile 0.7, the
<tt class="docutils literal">0.initial.py</tt> controller seems to be gone, but the <tt class="docutils literal">Post</tt> class is now part
of the blog buildout in the file <tt class="docutils literal">_controllers/blog/post.py</tt>, allowing you to
change how things are done.  So inside the <tt class="docutils literal">__post_process()</tt> method of
<tt class="docutils literal">Post</tt>, I replace the &quot;slug&quot; generation code with the following:</p>


<div class="pygments_manni"><pre><span class="gd">--- _controllers/blog/post.py</span>
<span class="gi">+++ _controllers/blog/post.py</span>
<span class="gu">@@ -166,7 +168,24 @@</span>
                datetime.datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;))

         if not self.slug:
<span class="gd">-            self.slug = re.sub(&quot;[ ?]&quot;, &quot;-&quot;, self.title).lower()</span>
<span class="gi">+</span>
<span class="gi">+            ########## THIS CODE ADDED FOR TECHSPOT #############</span>
<span class="gi">+            slug = self.title.lower()</span>
<span class="gi">+</span>
<span class="gi">+            # convert ellipses to spaces</span>
<span class="gi">+            slug = re.sub(r&#39;\.{2,}&#39;, &#39; &#39;, slug)</span>
<span class="gi">+</span>
<span class="gi">+            # flatten everything non alpha or . into a single -</span>
<span class="gi">+            slug = re.sub(r&#39;[^0-9a-zA-Z\.]+&#39;, &#39;-&#39;, slug)</span>
<span class="gi">+</span>
<span class="gi">+            # trim off leading/trailing -</span>
<span class="gi">+            slug = re.sub(r&#39;^-+|-+$&#39;, &#39;&#39;, slug)</span>
<span class="gi">+            self.slug = slug</span>
<span class="gi">+</span>
<span class="gi">+            #######################################################</span>
<span class="gi">+</span>
<span class="gi">+            # original</span>
<span class="gi">+            #self.slug = re.sub(&quot;[ ?]&quot;, &quot;-&quot;, self.title).lower()</span>
</pre></div>



<p>This allows the <tt class="docutils literal">blog.auto_permalink.path</tt> configuration
in <tt class="docutils literal">_config.py</tt> to remain at <tt class="docutils literal"><span class="pre">&quot;/:year/:month/:day/:title&quot;</span></tt>,
and special characters will be nicely treated in permalinks.</p>
<p>You need to have permalink generation turned on for the above to work - if
your posts don't have permalinks inside them, they don't appear to be
generated otherwise.</p>
<p>Hope these are helpful and happy static file blogging !</p>
</div>
</div>
]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://techspot.zzzeek.org</uri>
    </author>
    <title type="html"><![CDATA[In Response to "Stupid Template Languages"]]></title>
    <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org/2010/12/04/in-response-to-stupid-template-languages" />
    <id>http://techspot.zzzeek.org/2010/12/04/in-response-to-stupid-template-languages</id>
    <updated>2010-12-04T15:15:00Z</updated>
    <published>2010-12-04T15:15:00Z</published>
    <category scheme="http://techspot.zzzeek.org" term="Code" />
    <category scheme="http://techspot.zzzeek.org" term="Mako/Pylons" />
    <summary type="html"><![CDATA[In Response to "Stupid Template Languages"]]></summary>
    <content type="html" xml:base="http://techspot.zzzeek.org/2010/12/04/in-response-to-stupid-template-languages"><![CDATA[<div class="document">
<p>Responding to Daniel Greenfield's critique of &quot;smart&quot; template languages (<a class="reference external" href="http://pydanny.blogspot.com/2010/12/stupid-template-languages.html">&quot;Stupid Template Languages&quot;</a>).  In this post we see a typical critique of Mako, that it's allowance of Python code in templates equates to an encouragement of the placement of large amounts of business logic in templates:</p>
<blockquote>
<p>I often work on projects crafted by others, some who decided for arcane/brilliant/idiotic reasons to mix the kernel of their applications in template function/macros. This is only possible in Smart Template Languages! If they were using a Stupid Template Language they would have been forced put their kernel code in a Python file where it applies, not in a template that was supposed to just render HTML or XML or plain text.</p>
<p>What it comes down to is that Smart Template Languages designers assume that developers are smart enough to avoid making this mistake. Stupid Template Languages designers assume that developers generally lack the discipline to avoid creating horrific atrocities that because of unnecessary complexity have a bus factor of 1.</p>
</blockquote>
<p>Though I'm the author of Mako, I have lots of experience with restricted templating systems, being the original creator of several, including one that became known as <a class="reference external" href="http://freemarker.org/whoWeAre.html">FreeMarker</a>.  It's my experience that non-trivial projects using such systems virtually always bring forth situations where HTML needs to be stuffed into concatenated strings inside view logic - areas where some intricate interaction of tags and data are needed, or even not so intricate interactions.</p>
<p>Then you have HTML tags, including the choice of tag and its CSS attributes, shoved inside your code, where no HTML person will ever see it.  You only need to look as far as <a class="reference external" href="http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/">Django's own template documentation</a> to see them actually <em>encouraging</em> it !  This to me is infinitely worse than a little bit of code in templates, and I am always struck by the Django communities' critiques of Mako's allowance of small amounts of Python in template code,  as they continue to stuff HTML in their Python code as they see fit, seeing no issue at all.  Mako's philosophy is that no HTML should ever be in your code anywhere, and to that end it allows your custom tag libraries to be <a class="reference external" href="http://techspot.zzzeek.org/2008/07/01/better-form-generation-with-mako-and-pylons/">built as templates</a> as well.</p>
<p>I commonly hear the critique of Mako, as we see here, &quot;you could write your whole application in your template ! I've seen people do it!&quot;  That argument is entirely a straw man.   In contrast, my nightmare experiences with applications are those where entire HTML pages have been shoved into collections of hundreds of Perl modules or Java classes, each broken up into dozens of functions and entirely unreadable and unmaintainable.  I would bet that there are some Django apps out there which do some of the same thing.   Is that the way Django intended ?  Absolutely not.  But they can't save the world from bad code.</p>
<p>There's an infinite number of ways to write an application incorrectly, just because a particular library doesn't physically prevent you from doing so doesn't mean it's encouraging this behavior.  Mako has no responsiblity to &quot;assume&quot; that developers &quot;won't be stupid&quot;.  I can assure you that no library or framework has ever achieved the feat of eliminating developer stupidity.  If that is to be Django's main selling point, they can run with it.</p>
<p>The PHP mindset is one of the greatest evils in web development but Mako's existence is not an endorsement.  We don't encourage the placement of business logic in HTML templates, nor the placement of HTML tags into business logic - something that others do.</p>
</div>
]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://techspot.zzzeek.org</uri>
    </author>
    <title type="html"><![CDATA[How Coders Blog]]></title>
    <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org/2010/11/21/how-coders-blog" />
    <id>http://techspot.zzzeek.org/2010/11/21/how-coders-blog</id>
    <updated>2010-11-22T01:18:49Z</updated>
    <published>2010-11-22T01:18:49Z</published>
    <category scheme="http://techspot.zzzeek.org" term="Code" />
    <category scheme="http://techspot.zzzeek.org" term="Mako/Pylons" />
    <summary type="html"><![CDATA[How Coders Blog]]></summary>
    <content type="html" xml:base="http://techspot.zzzeek.org/2010/11/21/how-coders-blog"><![CDATA[<div class="document">
<p>It all started just a few days ago, as I had a really rare
desire to blog something, and had to go back to my klunky old
Wordpress blog and re-figure out how to use it.</p>
<p>I've had Wordpress running for maybe three years, after trying
out some other not so spectacular platforms like Serendipity.
Years ago Movable Type was the bomb because all it did was
generate files for you, but then they got on the PHP bandwagon
and became a huge beast just like all the rest. Wordpress at
least had marketshare and a lot of plugins.</p>
<p>Running WP is mostly a miserable affair for a coder.  We generally
don't go for WYSIWYG editors, and we certainly don't want to sit
there typing HTML tags, and we need to display lots of code samples
which we'd like highlighted.  I managed to hack up my WP to use a
Markdown plugin for content entry and <tt class="docutils literal">wp_syntax</tt> for syntax
highlighting, where getting them to work together was a herculean effort
involving direct modification of the plugins.  This herculean effort
needed to be repeated every few years when it became necessary to
upgrade Wordpress, as I had to re-figure-out and re-write all my
PHP hacks to make my system work again.  Just shoveling around
all those PHP files, each one a huge mess of spaghetti, hardcoded
SQL, and who knows what future vulnerabilities
that you're now going to <em>run on your server</em>, is a distasteful affair.</p>
<p>Which comes down to the worst thing about WP, is that <em>you have
to upgrade all the fricking time</em>, as it is simultaneously the
most security-hole ridden piece of crap as well as the most
highly targeted application by various worms and other web
nasties. As paranoid as I was about enabling the PHP interpreter
on my server, a pretty harmful nasty managed to stick some
backdoor-related files in my /tmp/ directory around 2008 or so, prompting
me to literally delete various .php files from the wp-admin/
directory and add additional passwords on the whole thing, as
these were php files meant to provide &quot;file upload&quot; features
which might as well been designed exclusively for worms and
hackers. Searching WP's trac finds hundreds of issues tagged
&quot;security&quot;, many of them just closed as &quot;can't reproduce&quot; even
though the unfortunate reporter of the bug clearly
got hacked several times, long after my
most recent version of 2.5. Here's an <a class="reference external" href="http://core.trac.wordpress.org/ticket/7710">admin exploit</a> in 2.6.1, an
<a class="reference external" href="http://core.trac.wordpress.org/ticket/10733">improperly escaped eval()</a> (they were using
<strong>eval!</strong>) in 2.8.4.</p>
<p>So the other day, when as is always the case when I go back to my WP admin page,
a giant &quot;YOU NEED TO UPGRADE RIGHT NOW!&quot; warning has been sitting there for eighteen months,
I got fed up and <a class="reference external" href="https://twitter.com/zzzeek/status/5809771005345792">tweeted</a>:</p>
<blockquote>
what do I use to blog where I write posts as ReST files,
generate-&gt;static site + Disqus, keep the whole thing in VC
and use rsync to pub ?</blockquote>
<p>Turns out that field has gone really well since the bad old days when I had to decide
between one PHP piece of junk or the other, and a whole bunch of people have
already been thinking the same thing.  Here's what I got back:</p>
<ul class="simple">
<li>Blogofile: <a class="reference external" href="http://www.blogofile.com/">http://www.blogofile.com/</a></li>
<li>CodeRanger: <a class="reference external" href="https://github.com/coderanger/coderanger.github.com">https://github.com/coderanger/coderanger.github.com</a></li>
<li>Jekyll: <a class="reference external" href="https://github.com/mojombo/jekyll">https://github.com/mojombo/jekyll</a></li>
<li>Hyde: <a class="reference external" href="https://github.com/lakshmivyas/hyde">https://github.com/lakshmivyas/hyde</a></li>
<li>Pelican: <a class="reference external" href="http://alexis.notmyidea.org/pelican/">http://alexis.notmyidea.org/pelican/</a></li>
<li>Rest2Web: <a class="reference external" href="http://www.voidspace.org.uk/python/rest2web/">http://www.voidspace.org.uk/python/rest2web/</a></li>
</ul>
<p>All look extremely promising - but what was even better was how
obvious the decision was for me personally - the one that uses my
own stuff (i.e. Mako, plus some SQLA utilities for WP import)
which is <a class="reference external" href="http://www.blogofile.com/">Blogofile</a>. In
just two days I got everything the crap out of Wordpress and got
ReST-powered, static, Pygments-syntax highlighting,
entirely-invisible-to-PHP-worms blog that looks better and I'll
never need to upgrade anything.   The comments go to Disqus, which
is both good and bad.  Good because the data-receiving, spam catching
dynamic side of the equation is on someone else's damn server.  Bad
because, there you go they've got my data, as well as my general distaste
of smarmy highly designed social media dashboards.  But it does
look nice.</p>
<p>Blogofile worked terrifically, was designed
exactly with my needs in mind by someone who sees things similarly to me,
and was super easy to customize and tweak.   It did need a
little bit of tweaking to work with RST and Pygments, but
this is all laid out for you (the coding blogger) in an obvious way that's
easy to customize.  Publishing is the easiest part, just push to a local
Mercurial via ssh, and a two line hg hook to up, rebuild and copy the
files - rsync isn't needed at all.</p>
<p>What's hard to ignore about all these platforms is that, your dad will never
blog like this.   You simply have to be a programmer to get excited about
writing posts as plain markup, checking them into a VC and configuring
shell scripts to publish, not to mention building the whole blog out
using Python scripts and templates.   So this is no threat to the world of hosted
blog services and dynamically-oriented systems.   But in the Python and
Ruby worlds this is how we should be doing it.</p>
</div>
]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://techspot.zzzeek.org</uri>
    </author>
    <title type="html"><![CDATA[Quick Mako vs. Jinja Speed Test]]></title>
    <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org/2010/11/19/quick-mako-vs.-jinja-speed-test" />
    <id>http://techspot.zzzeek.org/2010/11/19/quick-mako-vs.-jinja-speed-test</id>
    <updated>2010-11-20T01:18:49Z</updated>
    <published>2010-11-20T01:18:49Z</published>
    <category scheme="http://techspot.zzzeek.org" term="Code" />
    <category scheme="http://techspot.zzzeek.org" term="Mako/Pylons" />
    <summary type="html"><![CDATA[Quick Mako vs. Jinja Speed Test]]></summary>
    <content type="html" xml:base="http://techspot.zzzeek.org/2010/11/19/quick-mako-vs.-jinja-speed-test"><![CDATA[<div class="document">
<p><strong>Updated March 6, 2011</strong> - Mako 0.4 has ironed out some of the bumps and is within 10% of Jinja2's speed for this test.</p>
<p>I'm really glad about <a class="reference external" href="http://docs.pylonshq.com/">Pyramid</a> and all the great
work Pylons + BFG is going to accomplish. Also glad that someone
did a <a class="reference external" href="http://blog.curiasolutions.com/2010/11/the-great-web-technology-shootout-%E2%80%93-round-4-pyramid-vs-django-vs-tg-vs-rails-2-3/">matchup</a>
against other frameworks, including Rails, and its looking
great!</p>
<p>Here we address this statement made by Seth (nice to meet you,
Seth!):</p>
<blockquote>
Jinja2 was consistently around 25-50r/s
faster than Mako for me</blockquote>
<p>and when I read that, I said to myself, &quot;yeah, probably, Armin
wrote Jinja2 well after Mako, and probably did the same thing I
did with Cheetah when I wrote Mako, ensured it was just a teeny
bit faster&quot;.</p>
<p>As is my pessimistic nature, I made the same assumptions with <a class="reference external" href="/2007/12/26/revisiting-storm-sqlalchemy-and-geniusql">ORMs</a> a long time
ago, I said &quot;yeah OK, they focused more on speed than I did,
they're probably right !&quot; Until I went and tried it out, and saw
that wasn't the case at all.</p>
<p>So I whipped up a quick <a class="reference external" href="http://bitbucket.org/zzzeek/mako_v_jinja/">test</a> for
this one, running the templates directly without any web
frameworks involved in a <tt class="docutils literal">timeit</tt> run of 10000
render() calls. <span class="strikeout">Shrugs</span> Oh well, <span class="strikeout">I'm
getting 18%-21% faster performance from Mako</span>, the
latest Jinja2 is 24% faster using Seth's exact Jinja2 templates,
compared against two versions of the Mako template which
duplicate the Jinja2 templates down to the newline:</p>


<div class="pygments_manni"><pre>classics-MacBook-Pro:mako_v_jinja classic$ python run.py
jinja2 2.5: 7.5499420166
mako 0.3.6: 6.17144298553
mako 0.3.6 using def: 5.95005702972
</pre></div>



<p><strong>Edit:</strong> ah crap, forgot to upgrade Jinja2 - Armin wins !:</p>


<div class="pygments_manni"><pre>jinja2 2.5.5: 4.56899094582
mako 0.3.6: 6.26432800293
mako 0.3.6 using def: 6.06626796722
</pre></div>



<p><strong>Update March 2011</strong> - some of the issues have been addressed in Mako 0.4.0, Mako now nearly the same:</p>


<div class="pygments_manni"><pre>jinja2 2.5.5: 4.35861802101
mako 0.4.0: 4.83493804932
mako 0.4.0 using def: 4.82003712654
</pre></div>



<p>All three versions use a basic template inheritance setup. The
first Mako test uses the traditional <tt class="docutils literal">next.body()</tt>
approach to render the &quot;body&quot;, the second does more exactly the
method used by the Jinja2 template, declaring a &quot;block&quot; (in
Mako's case a <tt class="docutils literal">&lt;%def&gt;</tt>) and then calling it as
a method, i.e. <tt class="docutils literal">self.content()</tt>.</p>
<p><span class="strikeout">I was surprised myself</span> This is hardly
surprising ! I've hardly done anything at all with Mako
speedwise in years (with one exception below) and assumed newer
module-compiled systems were smoking me by now (as I've been
told <a class="reference external" href="http://chameleon.repoze.org/">these guys</a> did).</p>
<p>The ironic thing is that Mako got a pretty big speed boost in
version 0.3.4, when we started using Armin's own <a class="reference external" href="http://pypi.python.org/pypi/MarkupSafe">MarkupSafe</a>,
the library that was written originally for Jinja specifically,
to do escaping. It's written in C and is a huge improvement over
the very slow cgi routine we were using. Jinja2 and Mako are
almost like cousins at this point - we also use some AST utility
code written by Armin.</p>
</div>
]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://techspot.zzzeek.org</uri>
    </author>
    <title type="html"><![CDATA[Ajax the Mako Way]]></title>
    <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org/2008/09/01/ajax-the-mako-way" />
    <id>http://techspot.zzzeek.org/2008/09/01/ajax-the-mako-way</id>
    <updated>2008-09-01T22:15:38Z</updated>
    <published>2008-09-01T22:15:38Z</published>
    <category scheme="http://techspot.zzzeek.org" term="Code" />
    <category scheme="http://techspot.zzzeek.org" term="Mako/Pylons" />
    <summary type="html"><![CDATA[Ajax the Mako Way]]></summary>
    <content type="html" xml:base="http://techspot.zzzeek.org/2008/09/01/ajax-the-mako-way"><![CDATA[<div class="document">
<p>My previous post demonstrated how Mako's
&quot;defs with embedded content&quot; feature was used to build a library
of form tags, keeping all HTML and layout within templates, as
well as a succinct method of linking them to form validation and
data state. The &quot;def with embedded content&quot;, a feature derived
from HTML::Mason, is one feature that makes Mako highly unique
in the Python world. The form demo also illustrated another
unique feature, which is the ability to &quot;export&quot; the
functionality of a def (essentially a subcomponent of a page) to
other templates, without any dependency on inheritance or other
structural relationship. Defs with embeddable content and
exportable defs are two features I would never want to do
without, which is why I ported HTML::Mason to Myghty, and later
created Mako for Python.</p>
<p>A lesser known capability of the def is that they can be called
not just by other templates but by any arbitrary caller, such as
a controller. As it turns out, this capability is ideal in
conjunction with asynchronous requests as well, a use case that
didn't even exist when HTML::Mason was first created. Here I'll
demonstrate my favorite way to do Ajax with Pylons and the
unbelievably excellent <a class="reference external" href="http://jquery.com/">jQuery</a>. We'll
introduce a new <tt class="docutils literal">render()</tt> function that IMO should be part of
Pylons, the same way as <tt class="docutils literal">render_mako()</tt>.</p>
<p>An asynchronous HTTP request is often used to render part of the
page while leaving the rest unchanged, typically by taking the
output of the HTTP request and rendering it into a DOM element.
Jquery code such as the following can achieve this:</p>


<div class="pygments_manni"><pre><span class="nx">$</span><span class="p">(</span><span class="s2">&quot;#some_element&quot;</span><span class="p">).</span><span class="nx">load</span><span class="p">(</span><span class="s2">&quot;/datafeed&quot;</span><span class="p">);</span>
</pre></div>



<p>The above statement will render the output of the URI
<tt class="docutils literal">/datafeed</tt> into the DOM element with the id <tt class="docutils literal">some_element</tt>. In
Pylons, a controller and associated template would provide the
output for the <tt class="docutils literal">/datafeed</tt> URI, which would be HTML content
forming a portion of the larger webpage.</p>
<p>In our example, we'll build a &quot;pager&quot; display which displays
multiple pages of a document, one at a time, using the <tt class="docutils literal">load()</tt>
method to load new pages. One way we might do this looks like
this:</p>


<div class="pygments_manni"><pre><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;display&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
<span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;javascript:showpage(1)&quot;</span><span class="nt">&gt;</span>1<span class="nt">&lt;/a&gt;</span>
<span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;javascript:showpage(2)&quot;</span><span class="nt">&gt;</span>2<span class="nt">&lt;/a&gt;</span>
<span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;javascript:showpage(3)&quot;</span><span class="nt">&gt;</span>3<span class="nt">&lt;/a&gt;</span>

<span class="nt">&lt;script&gt;</span>
    <span class="kd">function</span> <span class="nx">showpage</span><span class="p">(</span><span class="nx">num</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">$</span><span class="p">(</span><span class="s2">&quot;#display&quot;</span><span class="p">).</span><span class="nx">load</span><span class="p">(</span><span class="s2">&quot;/page/read/&quot;</span> <span class="o">+</span> <span class="nx">num</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="nx">showpage</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
<span class="nt">&lt;/script&gt;</span>
</pre></div>



<p>Above, we define <tt class="docutils literal">display</tt>, which is a div where the pages
render. Some javascript code defines the <tt class="docutils literal">showpage()</tt> function,
which given a page number calls the jQuery <tt class="docutils literal">load()</tt> function to
load the content from the page-appropriate URI into the div.
Three links to three different pages each link to <tt class="docutils literal">showpage()</tt>,
given different page numbers.</p>
<p>In this version, the <tt class="docutils literal">/page/read</tt> controller would probably
define a separate template of some kind in order to format a the
data, so the layout of what goes inside of <tt class="docutils literal">display</tt> is
elsewhere. Additionally, the initial display of the full layout
requires two HTTP requests, one to deliver the enclosing layout
and another to load the formatted content within <tt class="docutils literal">display</tt>.</p>
<p>When using Mako, we often want to group together related
components of display within a single file. The <tt class="docutils literal">&lt;%def&gt;</tt> tag
makes this possible - a compound layout of small, highly
interrelated components need not be spread across many files
with small amounts of HTML in each; they can all be defined
together, which can cut down on clutter and speed up
development.</p>
<p>Such as, if we built the above display entirely without any
asynchronous functionality, we might say:</p>


<div class="pygments_manni"><pre><span class="x">&lt;div id=&quot;display&quot;&gt;</span>
<span class="x">    </span><span class="cp">${</span><span class="n">showpage</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">page</span><span class="p">)</span><span class="cp">}</span><span class="x"></span>
<span class="x">&lt;/div&gt;</span>
<span class="x">&lt;a href=&quot;/page/read/1&quot;&gt;1&lt;/a&gt;</span>
<span class="x">&lt;a href=&quot;/page/read/2&quot;&gt;2&lt;/a&gt;</span>
<span class="x">&lt;a href=&quot;/page/read/3&quot;&gt;3&lt;/a&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;showpage(page)&quot;</span><span class="cp">&gt;</span><span class="x"></span>
<span class="x">&lt;div class=&quot;page&quot;&gt;</span>
<span class="x">    &lt;div class=&quot;pagenum&quot;&gt;Page: </span><span class="cp">${</span><span class="n">page</span><span class="o">.</span><span class="n">number</span><span class="cp">}</span><span class="x">&lt;/div&gt;</span>
<span class="x">    &lt;h3&gt;</span><span class="cp">${</span><span class="n">page</span><span class="o">.</span><span class="n">title</span><span class="cp">}</span><span class="x">&lt;/h3&gt;</span>

<span class="x">    &lt;pre&gt;</span><span class="cp">${</span><span class="n">page</span><span class="o">.</span><span class="n">content</span><span class="cp">}</span><span class="x">&lt;/pre&gt;</span>
<span class="x">&lt;/div&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span><span class="x"></span>
</pre></div>



<p>The above approach again defines <tt class="docutils literal">showpage()</tt>, but it's now a
server-side Mako def, which receives a single <tt class="docutils literal">Page</tt> object as
the thing to be rendered. The output is first displayed using
the <tt class="docutils literal">Page</tt> object placed at <tt class="docutils literal">c.page</tt> by the controller, and
subsequent controller requests re-render the full layout with
the appropriate <tt class="docutils literal">Page</tt> represented.</p>
<p>The missing link here is to use both of the above approaches at
the same time - render the first <tt class="docutils literal">Page</tt> object into the div
without using an asynchronous request, allow subsequent <tt class="docutils literal">Page</tt>
requests to be rendered via Ajax, and finally to have the whole
layout defined in a single file. For that, we need a new Pylons
render function, which looks like this:</p>


<div class="pygments_manni"><pre><span class="k">def</span> <span class="nf">render_def</span><span class="p">(</span><span class="n">template_name</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="n">globs</span> <span class="o">=</span> <span class="n">pylons_globals</span><span class="p">()</span>

    <span class="k">if</span> <span class="n">kwargs</span><span class="p">:</span>
        <span class="n">globs</span> <span class="o">=</span> <span class="n">globs</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
        <span class="n">globs</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="n">template</span> <span class="o">=</span> <span class="n">globs</span><span class="p">[</span><span class="s">&#39;app_globals&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">mako_lookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="n">template_name</span><span class="p">)</span><span class="o">.</span><span class="n">get_def</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">template</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="o">**</span><span class="n">globs</span><span class="p">)</span>
</pre></div>



<p>The above <tt class="docutils literal">render_def()</tt> function is adapted from the standard
Pylons boilerplate for building render functions. It's virtually
the same as <tt class="docutils literal">render_mako()</tt> except we're calling the extra
<tt class="docutils literal">get_def()</tt> method from the Mako <tt class="docutils literal">Template</tt> object, and we're
also passing some <tt class="docutils literal">**kwargs</tt> straight to the def in addition to
the standard Pylons template globals. A refined approach might
involve building a <tt class="docutils literal">render_mako()</tt> function that has the
functionality to render both full <tt class="docutils literal">Template</tt> objects as well as
individual <tt class="docutils literal">&lt;%def&gt;</tt> objects based on arguments; but we'll keep
them separate for now.</p>
<p>With <tt class="docutils literal">render_def()</tt>, the Ajax version of our page now looks
like:</p>


<div class="pygments_manni"><pre><span class="x">&lt;div id=&quot;display&quot;&gt;</span>
<span class="x">     </span><span class="cp">${</span><span class="n">showpage</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">page</span><span class="p">)</span><span class="cp">}</span><span class="x"></span>
<span class="x">&lt;/div&gt;</span>
<span class="x">&lt;a href=&quot;javascript:showpage(1)&quot;&gt;1&lt;/a&gt;</span>
<span class="x">&lt;a href=&quot;javascript:showpage(2)&quot;&gt;2&lt;/a&gt;</span>
<span class="x">&lt;a href=&quot;javascript:showpage(3)&quot;&gt;3&lt;/a&gt;</span>

<span class="x">&lt;script&gt;</span>
<span class="x">    function showpage(num) {</span>
<span class="x">        $(&quot;#display&quot;).load(&quot;/page/read/&quot; + num);</span>
<span class="x">    }</span>
<span class="x">&lt;/script&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;showpage(page)&quot;</span><span class="cp">&gt;</span><span class="x"></span>
<span class="x">&lt;div class=&quot;page&quot;&gt;</span>
<span class="x">    &lt;div class=&quot;pagenum&quot;&gt;Page: </span><span class="cp">${</span><span class="n">page</span><span class="o">.</span><span class="n">number</span><span class="cp">}</span><span class="x">&lt;/div&gt;</span>
<span class="x">    &lt;h3&gt;</span><span class="cp">${</span><span class="n">page</span><span class="o">.</span><span class="n">title</span><span class="cp">}</span><span class="x">&lt;/h3&gt;</span>

<span class="x">    &lt;pre&gt;</span><span class="cp">${</span><span class="n">page</span><span class="o">.</span><span class="n">content</span><span class="cp">}</span><span class="x">&lt;/pre&gt;</span>
<span class="x">&lt;/div&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span><span class="x"></span>
</pre></div>



<p>Note above that there are <em>two</em> showpage functions; one is a
Mako def, callable during the server's rendering of the
template, the other a Javascript function which uses jQuery to
issue a new request to load new content. The <tt class="docutils literal">/page/read</tt>
controller calls the <tt class="docutils literal">showpage()</tt> def directly as its returned
template. The net effect is that the server-side version of
<tt class="docutils literal">showpage()</tt> dual purposes itself in two different contexts; as
a server-side component which participates in the composition of
an enclosing template render, and as a &quot;standalone&quot; template
which delivers new versions of its layout into the same overall
display within its own HTTP request.</p>
<p>The controller, which locates <tt class="docutils literal">Page</tt> objects using a simple
SQLAlchemy model, in its entirety:</p>


<div class="pygments_manni"><pre><span class="k">class</span> <span class="nc">PageController</span><span class="p">(</span><span class="n">BaseController</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">c</span><span class="o">.</span><span class="n">number_of_pages</span> <span class="o">=</span> <span class="n">Session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Page</span><span class="p">)</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
        <span class="n">c</span><span class="o">.</span><span class="n">page</span> <span class="o">=</span> <span class="n">Session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Page</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">Page</span><span class="o">.</span><span class="n">number</span><span class="o">==</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">one</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="s">&quot;/page.mako&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">read</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">id</span><span class="p">):</span>
        <span class="n">pagenum</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">id</span><span class="p">)</span>

        <span class="n">page</span> <span class="o">=</span> <span class="n">Session</span><span class="o">.</span><span class="n">query</span><span class="p">(</span><span class="n">Page</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">Page</span><span class="o">.</span><span class="n">number</span><span class="o">==</span><span class="n">pagenum</span><span class="p">)</span><span class="o">.</span><span class="n">one</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">render_def</span><span class="p">(</span><span class="s">&quot;/page.mako&quot;</span><span class="p">,</span> <span class="s">&quot;showpage&quot;</span><span class="p">,</span> <span class="n">page</span><span class="o">=</span><span class="n">page</span><span class="p">)</span>
</pre></div>



<p>I've packaged the whole thing as a demo
application (using Pylons 0.9.7 and SQLAlchemy 0.5), which pages
through a document we all should be well familiar with.</p>
<p>Download the ajax demo: <a class="reference external" href="/files/2008/ajax.tar.gz">ajax.tar.gz</a></p>
</div>
]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://techspot.zzzeek.org</uri>
    </author>
    <title type="html"><![CDATA[Better Form Generation with Mako and Pylons]]></title>
    <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org/2008/07/01/better-form-generation-with-mako-and-pylons" />
    <id>http://techspot.zzzeek.org/2008/07/01/better-form-generation-with-mako-and-pylons</id>
    <updated>2008-07-01T18:05:55Z</updated>
    <published>2008-07-01T18:05:55Z</published>
    <category scheme="http://techspot.zzzeek.org" term="Code" />
    <category scheme="http://techspot.zzzeek.org" term="Mako/Pylons" />
    <summary type="html"><![CDATA[Better Form Generation with Mako and Pylons]]></summary>
    <content type="html" xml:base="http://techspot.zzzeek.org/2008/07/01/better-form-generation-with-mako-and-pylons"><![CDATA[<div class="document">
<!--  -->
<blockquote>
<strong>11/21/2010 Newly revised for recent Pylons 1.0, Mako 0.3.6</strong></blockquote>
<p>In developing <a class="reference external" href="http://www.makotemplates.org">Mako</a>, a primary
goal was to make a super-nice version of a particular
&quot;component&quot; pattern which I had used for years primarily with
<a class="reference external" href="http://www.masonhq.com/">HTML::Mason</a> which for me provides a
&quot;sweet spot&quot; of obviousness, agility, and succinctness. The
focus is around the ability to create &quot;tag libraries&quot; which
interact easily with a server-parsed templating language, and
which can be implemented within templates themselves. In JSP
development, taglibs are now the standard way to indicate
dynamic areas of templates, but while they look pretty clean,
they are painful to implement (requiring HTML embedded in
hand-crafted classes, a few dozen XML pushups for every tag you
add, and the obligatory application restart whenever they
change), and the
<a class="reference external" href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html">EL</a>
and <a class="reference external" href="http://struts.apache.org/2.0.11.1/docs/ognl.html">OGNL</a>
expressions which are standard within taglibs interact terribly
with straight Java code.</p>
<p>Mako allows the creation of tags which can be arbitrarily nested
and interactive with one another via the <tt class="docutils literal">&lt;%def&gt;</tt> construct, in
combination with the <tt class="docutils literal">&lt;%call&gt;</tt> tag, or as is more common
with modern versions of Mako, the <tt class="docutils literal">&lt;%namespace:def&gt;</tt> tag.
It's been my observation
that the <tt class="docutils literal">&lt;%call&gt;</tt> tag as well as the usage of nesting-aware
<tt class="docutils literal">&lt;%defs&gt;</tt> hasn't caught on yet, as the examples in the docs are
a little dense, so here I will seek to demystify it a bit.</p>
<p>Pylons currently recommends a decent approach to rendering
forms, using Webhelpers,
which are essentially little functions you can embed in your
template to render standard form elements. The handling of the
form at the controller level uses FormEncode and routes validation errors
through htmlfill. My
approach modifies this to use Mako tags to build a site-specific
taglib around the webhelpers tags and adds an explicit
interaction between those tags and the controller, in a manner
similar to a Struts form handler, which replaces <tt class="docutils literal">htmlfill</tt> and
allows all layout, including the layout of validation error
messages, using the same template system. It also adds a
preprocessor that illustrates how to build custom tags in Mako
which look as nice as the built-in ones.</p>
<p>A tar.gz of the approach can be downloaded
<a class="reference external" href="/files/2008/formhelpers.tar.gz">here</a>
(works against Pylons 1.0), which contains two templates
each illustrating a different approach to laying out the form -
one using htmfill, the second using the Mako-defined tags.
The final result, present in the file
<tt class="docutils literal">templates/comment_form.html</tt>, looks like this:</p>


<div class="pygments_manni"><pre><span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">name=</span><span class="s">&quot;form&quot;</span> <span class="na">file=</span><span class="s">&quot;/form_tags.mako&quot;</span><span class="cp">/&gt;</span><span class="x"></span>

<span class="x">&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;</span>
<span class="x">   &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;</span>
<span class="x">&lt;html&gt;</span>
<span class="x">&lt;head&gt;</span>
<span class="x">  &lt;title&gt;Mako Form Helpers&lt;/title&gt;</span>
<span class="x">  &lt;link rel=&quot;stylesheet&quot; href=&quot;/style.css&quot; type=&quot;text/css&quot; /&gt;</span>
<span class="x">&lt;/head&gt;</span>
<span class="x">&lt;body&gt;</span>

<span class="x">&lt;h3&gt;Using Mako Helpers&lt;/h3&gt;</span>

<span class="cp">&lt;%</span><span class="nb">form:form</span> <span class="na">name=</span><span class="s">&quot;comment_form&quot;</span> <span class="na">controller=</span><span class="s">&quot;comment&quot;</span> <span class="na">action=</span><span class="s">&quot;post&quot;</span><span class="cp">&gt;</span><span class="x"></span>
<span class="x">&lt;table&gt;</span>
<span class="x">    &lt;tr&gt;</span>
<span class="x">        &lt;th colspan=&quot;2&quot;&gt;Submit your Comment&lt;/th&gt;</span>
<span class="x">    &lt;/tr&gt;</span>
<span class="x">    &lt;tr&gt;</span>
<span class="x">        &lt;td&gt;Your Name:&lt;/td&gt;</span>
<span class="x">        &lt;td&gt;</span><span class="cp">&lt;%</span><span class="nb">form:text</span> <span class="na">name=</span><span class="s">&quot;name&quot;</span><span class="cp">/&gt;</span><span class="x">&lt;/td&gt;</span>
<span class="x">    &lt;/tr&gt;</span>

<span class="x">    &lt;tr&gt;</span>
<span class="x">        &lt;td&gt;How did you hear about this site ?&lt;/td&gt;</span>
<span class="x">        &lt;td&gt;</span>
<span class="x">            </span><span class="cp">&lt;%</span><span class="nb">form:select</span> <span class="na">name=</span><span class="s">&quot;heard&quot;</span> <span class="na">options=</span><span class="s">&quot;${c.heard_choices}&quot;</span><span class="cp">&gt;</span><span class="x"></span>
<span class="x">                </span><span class="cp">&lt;%</span><span class="nb">form:option</span> <span class="na">value=</span><span class="s">&quot;&quot;</span><span class="cp">&gt;</span><span class="x">None</span><span class="cp">&lt;/%</span><span class="nb">form:option</span><span class="cp">&gt;</span><span class="x"></span>
<span class="x">            </span><span class="cp">&lt;/%</span><span class="nb">form:select</span><span class="cp">&gt;</span><span class="x"></span>
<span class="x">        &lt;/td&gt;</span>
<span class="x">    &lt;/tr&gt;</span>

<span class="x">    &lt;tr&gt;</span>
<span class="x">        &lt;td&gt;Comment:&lt;/td&gt;</span>
<span class="x">        &lt;td&gt;</span><span class="cp">&lt;%</span><span class="nb">form:textarea</span> <span class="na">name=</span><span class="s">&quot;comment&quot;</span><span class="cp">/&gt;</span><span class="x">&lt;/td&gt;</span>
<span class="x">    &lt;/tr&gt;</span>

<span class="x">    &lt;tr&gt;</span>
<span class="x">        &lt;td colspan=&quot;2&quot;&gt;</span><span class="cp">&lt;%</span><span class="nb">form:submit</span><span class="cp">/&gt;</span><span class="x">&lt;/td&gt;</span>
<span class="x">    &lt;/tr&gt;</span>
<span class="x">&lt;/table&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">form:form</span><span class="cp">&gt;</span><span class="x"></span>

<span class="x">&lt;/body&gt;</span>
<span class="x">&lt;/html&gt;</span>
</pre></div>



<p>The <tt class="docutils literal">%form:textarea</tt> tag invokes the <tt class="docutils literal">textarea</tt> def inside the
<tt class="docutils literal">form</tt> namespace, which is defined in the file
<tt class="docutils literal">form_tags.mako</tt>. The def for <tt class="docutils literal">textarea</tt> looks like:</p>


<div class="pygments_manni"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;textarea(name, default=None, **attrs)&quot;</span> <span class="na">decorator=</span><span class="s">&quot;render_error&quot;</span><span class="cp">&gt;</span><span class="x">\</span>
<span class="cp">&lt;%doc&gt;</span>
<span class="cp">    Render an HTML &lt;textarea&gt;&lt;/textarea&gt; tag pair with embedded content.</span>
<span class="cp">&lt;/%doc&gt;</span><span class="x"></span>
<span class="cp">${</span><span class="n">h</span><span class="o">.</span><span class="n">textarea</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">content</span><span class="o">=</span><span class="n">request</span><span class="o">.</span><span class="n">params</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">default</span><span class="p">),</span> <span class="o">**</span><span class="n">attrs</span><span class="p">)</span><span class="cp">}</span><span class="x">\</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span><span class="x"></span>
</pre></div>



<p>Above, the <tt class="docutils literal"><span class="pre">decorator=&quot;render_error&quot;</span></tt> is a Mako def decorator,
where the <tt class="docutils literal">render_error</tt> function inserts validation messages
into the content while also rendering the form control.</p>
<p>The point of <tt class="docutils literal">form_tags.mako</tt> is that all the form tags,
their layout and method of rendering is plainly visible and easily customized.</p>
<p>The demo also contains a modified version of Pylons'
<tt class="docutils literal">&#64;validate</tt> decorator. Usage is similar, except
it requires a name for the form and a <tt class="docutils literal">formencode</tt> schema
unconditionally.  It also features an optional
<tt class="docutils literal">input_controller</tt> parameter, a reference to the local controller
method used for input:</p>


<div class="pygments_manni"><pre><span class="kn">from</span> <span class="nn">formhelpers.lib.mako_forms</span> <span class="kn">import</span> <span class="n">validate</span>

<span class="k">class</span> <span class="nc">CommentController</span><span class="p">(</span><span class="n">BaseController</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">c</span><span class="o">.</span><span class="n">comment_form</span><span class="p">:</span>
            <span class="n">c</span><span class="o">.</span><span class="n">comment_form</span> <span class="o">=</span> <span class="n">CommentForm</span><span class="p">()</span><span class="o">.</span><span class="n">from_python</span><span class="p">({})</span>
        <span class="n">c</span><span class="o">.</span><span class="n">heard_choices</span> <span class="o">=</span> <span class="n">HEARD_CHOICES</span>
        <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="s">&#39;/comment_form.html&#39;</span><span class="p">)</span>

    <span class="nd">@validate</span><span class="p">(</span><span class="s">&quot;comment_form&quot;</span><span class="p">,</span> <span class="n">CommentForm</span><span class="p">,</span> <span class="n">input_controller</span><span class="o">=</span><span class="n">index</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">post</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">c</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">form_result</span><span class="p">[</span><span class="s">&#39;name&#39;</span><span class="p">]</span>
        <span class="k">return</span> <span class="n">render</span><span class="p">(</span><span class="s">&#39;/thanks.html&#39;</span><span class="p">)</span>
</pre></div>



<p>Where above, <tt class="docutils literal">post</tt> hits the validator, and on an invalid
exception the <tt class="docutils literal">index</tt> controller method is called instead.
Validation errors are placed in <tt class="docutils literal">self.form_errors</tt> as well as
<tt class="docutils literal">c.form_errors</tt> for template access. The validator as well as
the preprocessor are defined in <tt class="docutils literal">lib/mako_forms.py</tt>.
The controller also places a <tt class="docutils literal">comment_form</tt> dictionary on <tt class="docutils literal">c</tt>,
which the <tt class="docutils literal">&#64;validate</tt> function takes care of on
the post side.</p>
<p>Download the formhelpers demo: <a class="reference external" href="/files/2008/formhelpers.tar.gz">formhelpers.tar.gz</a></p>
</div>
]]></content>
  </entry>
  <entry>
    <author>
      <name></name>
      <uri>http://techspot.zzzeek.org</uri>
    </author>
    <title type="html"><![CDATA[Reddit.com Goes Open Source]]></title>
    <link rel="alternate" type="text/html" href="http://techspot.zzzeek.org/2008/06/18/reddit.com-goes-open-source" />
    <id>http://techspot.zzzeek.org/2008/06/18/reddit.com-goes-open-source</id>
    <updated>2008-06-18T14:07:03Z</updated>
    <published>2008-06-18T14:07:03Z</published>
    <category scheme="http://techspot.zzzeek.org" term="Code" />
    <category scheme="http://techspot.zzzeek.org" term="SQLAlchemy" />
    <category scheme="http://techspot.zzzeek.org" term="Mako/Pylons" />
    <summary type="html"><![CDATA[Reddit.com Goes Open Source]]></summary>
    <content type="html" xml:base="http://techspot.zzzeek.org/2008/06/18/reddit.com-goes-open-source"><![CDATA[<div class="document">
<p><a class="reference external" href="http://reddit.com">Reddit</a> has <a class="reference external" href="http://blog.reddit.com/2008/06/reddit-goes-open-source.html">opened their source
up</a>
and we can now see just what they've been up to. It's been known
for some time that Reddit was (re)built using
<a class="reference external" href="http://pylonshq.com">Pylons</a> and
<a class="reference external" href="http://www.makotemplates.org">Mako</a> templates, contrary to
their <a class="reference external" href="http://www.reddit.com/help/faq">FAQ</a> which still states
that they use web.py. As it turns out, they've also built
something of their own database layer, which seems to include a
homegrown caching layer and ultimately is built on top of
<a class="reference external" href="http://code.reddit.com/browser/r2/r2/lib/db/tdb_sql.py">SQLAlchemy</a>,
using the SQLA expression language to generate queries.
Connections are served with the
<a class="reference external" href="http://code.reddit.com/browser/r2/r2/lib/manager/db_manager.py">QueuePool</a>,
and they use the <cite>threadlocal</cite> setting, so that they can get
implicit access to transactions in progress. They <a class="reference external" href="http://code.reddit.com/browser/r2/r2/config/databases.py">vertically partition</a>
their database access among four separate engines across four
distinct areas of functionality on the site.</p>
<p>This is currently the highest volume website I'm aware of using
SQLAlchemy and Pylons, and is a testament to the stability of
our core components (I hope). Python in general is not too
prominent in New York City where I work; Java, PHP and .NET are
still the default &quot;goto&quot; platforms, and most developers here
look at you kind of funny when you mention Python. Look how
well-known Java advocate Ted Neward says <a class="reference external" href="http://www.ibm.com/developerworks/java/library/j-cobol.html">even
Python!</a>,
as though we're the most fringe Java alternative imaginable. I
hope examples like Reddit continue to illustrate that Python
presents the best mix of performance, stability, and rapid
development for web development today, not to mention one of the
broadest software ecosystems in the field (which I've always
maintained is a <em>good</em> thing).</p>
</div>
]]></content>
  </entry>
</feed>

