<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
     xmlns:content="http://purl.org/rss/1.0/modules/content/"
     xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
     xmlns:atom="http://www.w3.org/2005/Atom"
     xmlns:dc="http://purl.org/dc/elements/1.1/"
     xmlns:wfw="http://wellformedweb.org/CommentAPI/"
     >
  <channel>
    <title>zzzeek</title>
    <link>http://techspot.zzzeek.org</link>
    <description>mostly computer stuff</description>
    <pubDate>Wed, 08 Oct 2025 12:31:29 GMT</pubDate>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Gerrit is Awesome</title>
      <link>http://techspot.zzzeek.org/2016/04/21/gerrit-is-awesome</link>
      <pubDate>Thu, 21 Apr 2016 12:10:00 EDT</pubDate>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2016/04/21/gerrit-is-awesome</guid>
      <description>Gerrit is Awesome</description>
      <content:encoded><![CDATA[<div class="document">
<p>In the past week I've started using <a class="reference external" href="https://www.gerritcodereview.com/">Gerrit</a>
for all development on SQLAlchemy, including for pull requests, feature
branch development, and bug fixes across maintenance branches.  I was first introduced
to Gerrit through my involvement in the Openstack project, where initially
I was completely bewildered by it.   Eventually, I figured out roughly enough
what was going on to be productive with it and to ultimately prefer it for
adding code changes to a project.  But making the big leap of actually moving
SQLAlchemy and my other key projects over to it required the extra effort
of learning Gerrit a little more fundamentally as well as installing and
integrating it with SQLAlchemy's existing workflows.</p>
<div class="section" id="what-is-gerrit">
<h1>What is Gerrit?</h1>
<p>I don't consider myself to be any authority on Gerrit, so my description here
is based on my working impression of what it does; the details may not be
entirely accurate.   Gerrit is a &quot;code review&quot; tool, intended to  allow
collaboration around code changes targeted at a project.   At that level, what
Gerrit is doing can be compared to a pull request - allows proposal of a
change, shows you how it's different from what's there already, allows comments
on the change including against specific code, and then provides workflow to
allow the change to be merged into the code repository.   For those familiar
with pull requests, this seems exactly the same, yet while I've always been
very unsatisifed with pull requests for a long time, I am completely satisifed
with Gerrit's model.  So to understand that requires more understanding of
Gerrit.</p>
<p>At its core, Gerrit is maintaining a set of git repositories that are basically
mirrors of your projects' actual git repositories.  Then, it adds some
additional, non-mirrored (e.g. only to its local copy) reference  paths to
these git repositories such that you can push commits to them which represent
<strong>Code Reviews</strong>.   These commits resemble feature branches in that they are
branched off of &quot;master&quot; or another maintenance branch, but the way we work
with them is different.    The most immediate difference is that unlike a
traditional feature branch, the individual &quot;code review&quot; is always a <em>single
commit</em> containing the entire new feature all at once, whereas a feature branch
may consist of any number of commits. In order to allow additional changes and
refinements to the &quot;Code Review&quot; as it proceeds, you create a brand new
changeset that encompasses the previous changeset completely, plus your new
changes.   Since there is no longer a linear history in Git between these
refinements, Gerrit adds an additional &quot;Change-Id&quot; identifier to the commit
message which is how Gerrit keeps track of each change in a code review.   So
instead of a long-lived feature branch that changes by adding new revisions to
the end of it, you have a series of discrete all-at-once commits, each one
containing the whole feature at once.</p>
<p>In ASCII art parlance, the traditional Git branching model, also used
by pull requests, can be seen like this:</p>


<div class="pygments_manni"><pre><span></span>rev 1 -&gt; rev 2 -&gt; rev 3 -&gt; rev 4 -&gt; rev 5          -&gt; master
                    |
                    +-&gt; rev 3a -&gt; rev 3b -&gt; rev 3c -&gt; feature branch
</pre></div>



<p>Above, the feature branch is forked off from the code at some point, and
as development continues, a new revision is added to the feature branch.
The multiple commits of the feature branch will eventually be merged into master,
either using a traditional merge, or by &quot;rebasing&quot; the feature branch onto the
top of master.</p>
<p>In Gerrit, the open-ended nature of Git is taken advantage of in an entirely
different way, and the mapping of Gerrit to Git might look more like this:</p>


<div class="pygments_manni"><pre><span></span>rev 1 -&gt; rev 2 -&gt; rev 3 -&gt; rev 4 -&gt; rev 5 -&gt; master
                    |
                    +-&gt; rev 3a
                    |     |
                    +-&gt; rev 3a/3b
                    |     |
                    +-&gt; rev 3a/3b/3c
                          |
                          v
                       Change Id: Iabcdef
</pre></div>



<p>The above model would be difficult to work with using Git alone;  Gerrit
maintains the list of changesets conforming to a Change Id in its own
database, and provides a full blown GUI and command line API on top so
that the history of development of the &quot;Feature&quot; is very clear and easy to
work with.</p>
</div>
<div class="section" id="getting-used-to-it">
<h1>Getting Used to It</h1>
<p>The major caveat with this whole approach is that there's a non-trivial
conceptual hill to climb in order to use it, particularly if you're not
accustomed to &quot;git rebase&quot; (as I wasn't).  When we are in our code change that
we've pushed as a code review, and we want to revise it and push it up as a new
version of that code review, we need to <strong>replace</strong> the old commit with the new
one, not add it on as additional history.  The most fundamental thing this
means is that instead of saying <tt class="docutils literal">git commit</tt>, we have to say, <tt class="docutils literal">git commit
<span class="pre">--amend</span></tt>, meaning, squash our current changes into the most recent commit.
The hash of the recent commit is replaced with a brand new one, and the old
commit is essentially floating, except for the fact that Gerrit will track it.</p>
<p>When we amend a single commit, we get the same commit message and we basically
leave it alone; the commit message represents what the change will be a whole,
not the little adjustment we're making here.   The commentary about adjustments
to our feature occurs in the comment stream on the review itself.   With Gerrit's
approach, you no longer have commits like, &quot;fix whitespace&quot;, &quot;add test&quot;, &quot;add documentation&quot; - at
the end of the day there will be just one commit message with, &quot;Add Feature
XYZ; XYZ does QPR ...&quot;.   I consider that an advantage, because intermediary
commits within a feature branch like &quot;fix whitespace&quot; are really just noise; I
don't miss them.</p>
<p>The other thing that has to be dealt with is that Gerrit won't allow you to
push up a code review that can't be cleanly merged into the working branch
it will be a part of.  Again, this is a conceptually odd thing to adjust
to but when you start doing it you realize what a great idea it is; when
we work with tradtional feature branches and pull requests, there's always that
time when we realize we've fallen <em>so</em> far behind master, and oh now we have
to merge master into our branch, and fix all the conflicts, so that we can merge back
up later without making a huge mess.</p>
<p>With Gerrit's approach, nothing ever gets pushed up
that can't be immediately merged, which means if you're targeting a project that has
a lot of activity, you'll find yourself having to rebase your code reviews
every time - but the key word here is &quot;rebase&quot;.  Instead of merging master
back into our feature branch, we are doing a straight up rebase of our single
commit against the state of master; and because there's only one commit to deal
with, this is usually a very simple process - we aren't burdened with trying to
knit the changesets together in just the right way, or worrying about awkward
merge artifacts cluttering up our feature branch forever; we <em>flatten everything
into our single changeset</em>, and all the clutter of how we merged things
together is discarded.  As long as you're comfortable with
&quot;git rebase&quot;, it's a predictable and consistent process.   If you are using Gerrit for any amount of time, you will be <em>very</em> comfortable with rebasing :).</p>
</div>
<div class="section" id="advantages">
<h1>Advantages</h1>
<p>The advantages to the above Gerrit model are in my opinion huge wins,
including:</p>
<ol class="arabic simple">
<li>You always have a feature packaged up as a single, clean commit, so that
even with &quot;git show&quot;, you can see the change represented by the feature
all at once in its entirety, with no stream of trivial &quot;work in progress&quot;
commits cluttering it up.  Because Gerrit maintains its own database
of past versions and commentary, the history of how this change was developed
is persisted permanently, but outside of your Git repository.</li>
<li>You don't clutter up your Git repository with tons of old feature branches.
Git of course allows you to delete feature branches, but then you lose
all the change history.  With Gerrit you get to hold on to a permanent
record of how a new feature or change was produced and none of it clutters
up your main repository.</li>
<li>Any number of developers can collaborate on a single change with no bumps
in the process.  This is something that is just not practical at all
with pull requests; if a user submits a pull request to me, and I'd like
to add some changes to it myself, the usual answer is that I need to
pull that pull request into my <em>own</em> feature branch somewhere, and change
it there - totally separated from where the original pull request is.
Or, the developer of that pull request can opt to give my account write
access to their repository; however in practice, I've never seen anyone
do this, and it also means I'm awkwardly working on my own project via
someone else's account.  This is the most continuously frustrating thing
about pull requests and is a key reason I'm so much happier with Gerrit.
With pull requests I often found myself having to painstakingly describe
exactly how some part of code should look in order to get the submitter
to do it in their branch, so that I wouldn't have to &quot;take it over&quot; and
chase them away forever.  With a Gerrit code review
I can just push up a modification to their change, and the contributor
can jump right back on with no bump in continuity.  When
I've made a lot of changes to someone's change I add &quot;Co-Authored By: &quot; with
my name to the commit message so that a viewer can see it was a two-person
job.</li>
<li>The &quot;change as a single commit&quot; model means we no longer have to deal with
pull requests that consist of two dozen changesets, re-merges of master,
weird merge artifacts like where you see zillions of merged commits
interspersed with the ones you care about, and so on.  When I go to &quot;git merge&quot;
someone's pull request, I usually need to go through the effort to manually
squash it and add my own changelog notes, which means that the Github or
Bitbucket UX has no record at all of me &quot;merging&quot; their pull request,
and most horribly on Bitbucket I have to explicitly mark the PR as
&quot;DECLINED&quot;, when meanwhile I just wanted to squash it.  Gerrit on the other
hand is built for rebasing and squashing from the ground up, and represents
an accurate record of <strong>exactly</strong> what was merged, with no chance that I went
off and modified someone's pull request locally after the fact in a short-lived
feature branch.  <strong>Everything</strong> on a code contribution from start to final
merge to master is visible exactly within the Gerrit UX, with complete
accuracy and permanence.</li>
<li>The workflow model of Gerrit is far richer than that of a pull request and
is also fully customizable.  Different roles, such as that of developers,
contributors, and automated CI systems, can each get their own workflow
flags each with different meanings.  Typically, a core developer of
the project needs to assign a &quot;+2 Approved&quot; flag, the CI systems in play
need to assign &quot;+1 Verified&quot; and in Openstack and on my own system there's
additionally a &quot;+1 Ready to Merge&quot; flag; when all those are up, you press
&quot;submit&quot; and the code review is pushed to the target branch, and its done.
With Bitbucket and Gerrit pull requests, I <em>never</em> pushed the button,
as I was always having to add changelog notes, make fixes, squash it,
fixing merge conflicts, all of which I can now push straight into that
same code review under one consistent interface.</li>
<li>Integration with Jenkins is way better for Gerrit than it is with Github,
and for Bitbucket I've not even been able to find any Jenkins integration.
Once I pull a code change into Gerrit I can easily grant the contributor
access to continue working on it, or disallow changes, so that I can
on a per-user basis decide who gets to push new changes that automatically
kick off builds and not have to worry that someone will submit a malicious
pull request when I'm not looking.  With the Jenkins Github pull request
plugin, it was simply not an option to enable automatic CI unless I were
using something like Travis, which currently I'm not.</li>
</ol>
<p>Overall, with Gerrit I now have a single, consistent way to do <em>all</em> new code;
all of my feature branches, all of my random .patch files sitting in my home
directory, pull requests from github or bitbucket; all of it goes straight into
Gerrit where I have them all under one interface and where
changes, history, code review, workflow, and comments on them are permanent,
without creating any branch junk in my main git repo!</p>
<p>Gerrit has a ton more features as well, including an extremely detailed
permissioning model which you can map to specific paths in each git repo;
a Lucene-powered search feature, a replication engine so that changes to
the local git repo can be pushed anywhere else; it is itself a full blown
http and ssh server for the git repositories as well as for its
command-line and GUI interfaces, and generally has all-around industrial
style features.</p>
<p>Where Gerrit is falling short is that on the &quot;self-install&quot; side, it  is
definitely a little obtuse and unforgiving about things.   It was not  that
easy to set up, and you'll likely have to spend a lot of time reading stack
traces in the logs to figure out various issues - documentation, links to
packages, and other online help is a little scattered and sometimes
incomplete, especially for the plugins.  It's not very user friendly on the
adminstration side yet.   But hosting it yourself is still the way to go, so
that when  you hit a view like &quot;all&quot;, you see just your projects and not a huge
list of other people's projects.</p>
</div>
<div class="section" id="implementation">
<h1>Implementation</h1>
<p>The move to self-hosting services again is kind of a pendulum swing for me;
a couple of years ago I was entirely gleeful to move my issue tracking
off of Trac and onto Bitbucket, but i think the reason for that was mostly
due to Trac's inability to limit spam accounts as well as a burdensome
performance model and very little upstream development.  With Gerrit, I'm
self-hosting again, however all authorization is pushed up to Github
with OAuth, so that I'm not dealing with fake user accounts and so far not
any spammers either.</p>
<p>I'm using the Gerrit Oauth plugin to provide Github logins, and this plugin
also includes support for Google Oauth which I haven't turned on yet,
and Bitbucket OAuth which I couldn't get working.</p>
<p>For integration with community-supplied code submissions, I am still
using pull requests as the primary entrypoint into the system.  Github
and Bitbucket require that you leave the &quot;pull request&quot; button on
in any case, so people are naturally going to send you code on both
of them no matter what you say, so we might as well use them.   The pull
request allows me to have a quick preview of what we're dealing with,
and I then import it into Gerrit using a semi-manual process.  To achieve
this consistently, I've created the
<a class="reference external" href="https://bitbucket.org/zzzeek/prtogerrit">prtogerrit</a> script which
communicates with both the Github and Bitbucket APIs to pull in any target
pull request, squash it, push it into Gerrit as a new review, and add comments
to the pull request referring the contributor to our Gerrit registration page.
Pull requests submitted through Bitbucket still necessarily get that
big ugly &quot;DECLINED&quot; status, however it is now consistent for all BB pull requests
and the messaging is clear that the work is continued on Gerrit.</p>
</div>
<div class="section" id="sum-up">
<h1>Sum Up</h1>
<p>Since I've been using Gerrit, I've been surprised at how much more productive
I became; being able to see every code change being worked on by anyone
all under one interface is very freeing, and the workflow that lets me have
the entire change from implementation to tests to changelog and migration notes
in one clean, mergable commit, fully run through multiple Jenkins CI jobs
before it gets merged has made me totally comfortable pushing a big red
&quot;merge&quot; button at the end, which was
never the case with pull requests and other ad-hoc patchfiles and feature
branches.</p>
</div>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Asynchronous Python and Databases</title>
      <link>http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases</link>
      <pubDate>Sun, 15 Feb 2015 12:10:00 EST</pubDate>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases</guid>
      <description>Asynchronous Python and Databases</description>
      <content:encoded><![CDATA[<div class="document">
<div class="admonition admonition-note-on-sqlalchemy-november-2020">
<p class="first admonition-title">Note on SQLAlchemy, November, 2020</p>
<p>To quote the last part of this blog post, &quot;I think it's [asyncio] really
well done, it's fun to use, and I still am interested in having more of a
SQLAlchemy story for it, because I'm sure folks will still want this no
matter what anyone says.&quot;.   To that end, SQLAlchemy 1.4 now includes
<a class="reference external" href="https://docs.sqlalchemy.org/latest/orm/extensions/asyncio.html">complete support for asyncio</a>, thanks
to an approach that internally uses the &quot;greenlet&quot; library to bridge the
gap between asyncio's syntactical requirements and SQLAlchemy's internals,
so that we didn't have to rewrite everything.   The greenlet approach is
also made available as an <strong>optional</strong> public-facing API feature so that an
asyncio-centric application may opt in to making use of traditional
ORM patterns such as lazy loading within specific segments of an
application.</p>
<p class="last">Read the migration notes for the new asyncio feature at
<a class="reference external" href="https://docs.sqlalchemy.org/latest/changelog/migration_14.html#asynchronous-io-support-for-core-and-orm">Asynchronous Support for Core and ORM</a>.</p>
</div>
<p>The asynchronous programming topic is difficult to cover.  These days,
it's not just about one thing, and I'm mostly
an outsider to it.  However, because I deal a lot with
relational databases and the Python stack's interaction with
them, I have to field a lot of questions and issues regarding
asynchronous IO and database programming, both specific to <a class="reference external" href="http://www.sqlalchemy.org">SQLAlchemy</a> as well as towards <a class="reference external" href="http://www.openstack.org/">Openstack</a>.</p>
<p>As I don't have a simple opinion on the matter, I'll try to give a spoiler
for the rest of the blog post here.  I think that the
Python <a class="reference external" href="https://docs.python.org/3/library/asyncio.html">asyncio</a> library
is very neat, promising, and fun to use, and organized well enough
that it's clear that some level of
SQLAlchemy compatibility is feasible, most likely including most
parts of the ORM.   As asyncio is now a standard part of Python, this compatiblity layer
is something I am interested in producing at some point.</p>
<p>All of that said, I still think that
asynchronous programming is just one potential approach to have on the shelf,
and is by no means the one we should be using all the time or even most of
the time, unless we are writing HTTP or chat servers or other applications
that specifically need to concurrently maintain large numbers of <em>arbitrarily</em> slow or
idle TCP connections (where by &quot;arbitrarily&quot; we mean, we don't care if individual
connections are slow, fast, or idle, throughput can be maintained regardless).
For standard business-style,
<a class="reference external" href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD-oriented</a>
database code, the approach given by asyncio is never
necessary, will almost certainly hinder performance,
and arguments as to its promotion of &quot;correctness&quot; are
very questionable in terms of relational database programming.   Applications
that need to do non-blocking IO on the front end should leave the business-level
CRUD code behind the thread pool.</p>
<p>With my assumedly entirely unsurprising viewpoint revealed, let's get underway!</p>
<div class="section" id="what-is-asynchronous-io">
<h1>What is Asynchronous IO?</h1>
<p>Asynchronous IO is an approach used to achieve concurrency by
allowing processing to continue while responses from IO operations
are still being waited upon.  To achieve this, IO function calls are
made to be <a class="reference external" href="http://en.wikipedia.org/wiki/Asynchronous_I/O">non blocking</a>, so that they
return immediately, before the actual IO operation is complete
or has even begun.   A typically OS-dependent polling system
(such as <a class="reference external" href="http://linux.die.net/man/4/epoll">epoll</a>)
is used within a loop in order to query a set of file descriptors
in search of the next one which has data available; when located, it
is acted upon, and when the operation is complete, control goes back
to the polling loop in order to act upon the next descriptor with
data available.</p>
<p>Non-blocking IO in its classical use case is for those cases where it's
not efficient to dedicate a thread of execution towards waiting for a
socket to have results. It's an essential technique for when you need
to listen to lots of TCP sockets that are arbitrarily &quot;sleepy&quot; or
slow - the best example is a chat server, or some similar kind of
messaging system, where you have lots of connections connected
persistently, only sending data very occasionally; e.g. when a
connection actually sends data, we consider it to be an &quot;event&quot; to
be responded to.</p>
<p>In recent years, the asynchronous IO approach has also been successfully
applied to HTTP related servers and applications.   The theory of operation
is that a very large number of HTTP connections can be efficiently serviced without
the need for the server to dedicate threads to wait on each
connection individually; in particular, slow HTTP clients need not get in the
way of the server being able to serve lots of other clients at the same
time.   Combine this with the renewed popularity of
so-called <a class="reference external" href="http://en.wikipedia.org/wiki/Comet_%28programming%29">long polling</a>
approaches, and non-blocking web servers like <a class="reference external" href="http://www.aosabook.org/en/nginx.html">nginx</a>
have proven to work very well.</p>
</div>
<div class="section" id="asynchronous-io-and-scripting">
<h1>Asynchronous IO and Scripting</h1>
<p>Asynchronous IO programming in scripting languages is
heavily centered on the notion of an <em>event loop</em>, which
in its most classic form uses <em>callback functions</em> that receive a call
once their corresponding IO request has data available.   A critical aspect
of this type of programming is that, since the event loop has the effect
of providing scheduling for a series of functions waiting for IO, a scripting
language in particular can replace the need for threads and OS-level
scheduling entirely, at least within a single CPU.
It can in fact be a little bit awkward to integrate multithreaded, blocking IO code
with code that uses non-blocking IO, as they necessarily use different
programming approaches when IO-oriented methods are invoked.</p>
<p>The relationship of asynchronous IO to event loops, combined with its
growing popularity for use in web-server oriented applications as well
as its ability to provide concurrency in an intuitive and obvious way, found
itself hitting a perfect storm of factors for it to become popular on
one platform in particular, Javascript.  Javascript was designed to be a
client side scripting language for browsers.
Browsers, like any other GUI app, are essentially event machines; all
they do is respond to user-initiated events of button pushes, key presses,
and mouse moves.  As a result, Javascript has a very strong concept
of an event loop with callbacks and,  until <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/basic_usage">recently</a>, no concept at all of multithreaded programming.</p>
<p>As an army of front-end developers from the
90's through the 2000's mastered the use of these client-side callbacks,
and began to use them not just for user-initiated events but for network-initiated
events via AJAX connections, the stage was set for a new player to come
along, which would transport the ever growing community of Javascript programmers
to a new place...</p>
</div>
<div class="section" id="the-server">
<h1>The Server</h1>
<p>Node.js is not the <a class="reference external" href="http://docs.oracle.com/cd/E19957-01/816-6411-10/getstart.htm#1015788">first</a>
attempt to make Javascript a server side language.   However,
a key reason for its success was that there were plenty of sophisticated
and experienced Javascript
programmers around by the time it was released, and that it also fully
embraces the event-driven programming paradigm that client-side Javascript
programmers are already well-versed in and comfortable with.</p>
<p>In order to sell this, it followed that the &quot;non-blocking IO&quot; approach
needed to be established as appropriate not just for the classic case of &quot;tending to lots of
usually asleep or arbitrarily slow connections&quot;, but as the <a class="reference external" href="https://www.youtube.com/watch?v=bzkRVzciAZg">de facto</a> style in which all
web-oriented software should be written.  This meant that <em>any</em>
network IO of any kind now had to be interacted with in a non-blocking
fashion, and this of course includes database connections - connections
which are normally relatively few per process, with numbers of 10-50
being common, are usually pooled so that the latency associated with TCP
startup is not much of an issue, and for which the response times for
a well-architected database, naturally served over the local network
behind the firewall and often clustered, are extremely fast and
predictable - in every way, the exact opposite of the use case for which
non-blocking IO was first intended.  The Postgresql database supports
an asynchronous command API in libpq, stating a primary rationale for it as - surprise!
<a class="reference external" href="http://www.postgresql.org/docs/8.3/static/libpq-async.html">using it in GUI applications</a>.</p>
<p>node.js already benefits from an <a class="reference external" href="https://code.google.com/p/v8/">extremely performant
JIT-enabled engine</a>, so it's likely
that despite this repurposing of non-blocking IO for a case in which
it was not intended, scheduling among database connections using non-blocking
IO works acceptably well.   (authors note: the comment here regarding
libuv's thread pool is removed, as this only regards file IO.)</p>
</div>
<div class="section" id="the-spectre-of-threads">
<h1>The Spectre of Threads</h1>
<p>Well before node.js was turning masses of client-side Javascript developers
into async-only server side programmers, the multithreaded programming model
had begun to make <a class="reference external" href="http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.html">academic theorists</a>
complain that they produce non-deterministic programs, and asynchronous
programming, having the side effect that the event-driven paradigm effectively
provides an alternative model of programming concurrency (at least for
any program with a sufficient proportion of IO to keep context switches
high enough), quickly became one of several hammers used to beat multithreaded programming
over the head, centered on the two critiques that threads are expensive to
create and maintain in an application, being inappropriate for applications
that wish to tend to hundreds or thousands of connections simultaneously,
and secondly that multithreaded programming is difficult and non-deterministic.
In the Python world,
continued confusion over what the GIL does and does not do provided for a natural
tilling of land fertile for the async model to take root more strongly than
might have occurred in other scenarios.</p>
</div>
<div class="section" id="how-do-you-like-your-spaghetti">
<h1>How do you like your Spaghetti?</h1>
<p>The callback style of node.js and other asynchronous paradigms was considered
to be problematic; callbacks organized for larger scale logic and operations
made for verbose and hard-to-follow code, commonly referred to as
<a class="reference external" href="https://www.google.com/search?q=node.js+spaghetti+code&amp;ie=utf-8&amp;oe=utf-8#q=node.js+spaghetti">callback spaghetti</a>.
Whether callbacks were in fact spaghetti or a thing of beauty was one of the
great arguments of the 2000's, however I fortunately don't have to get into it
because the async community has clearly acknowledged the former and taken
many great steps to improve upon the situation.</p>
<p>In the Python world, one approach offered in order to allow for asyncrhonous
IO while removing the need for callbacks is the &quot;implicit async IO&quot; approach offered by
<a class="reference external" href="http://eventlet.net/">eventlet</a> and <a class="reference external" href="http://www.gevent.org/">gevent</a>.
These take the approach of instrumenting IO functions to be implicitly
non-blocking, organized such that a system of
<a class="reference external" href="http://en.wikipedia.org/wiki/Green_threads">green threads</a> may each run
concurrently, using a native event library such as
<a class="reference external" href="http://libev.schmorp.de/">libev</a> to schedule work between green threads
based on the points at which non-blocking IO is invoked.  The effect of
implicit async IO systems is that the vast majority of code which performs IO
operations need not be changed at all; in most cases, the same code can
literally be used in both blocking and non-blocking IO contexts without
any changes (though in typical real-world use cases, certainly not
without occasional quirks).</p>
<p>In constrast to implicit async IO is the very promising approach offered by Python
itself in the form of the previously mentioned <a class="reference external" href="https://www.python.org/dev/peps/pep-3156/">asyncio</a>
library, now available in Python 3.  Asyncio brings
to Python fully standardized concepts of &quot;futures&quot;
and <a class="reference external" href="http://en.wikipedia.org/wiki/Coroutine">coroutines</a>, where we can
produce non-blocking IO code that flows in a very similar way to traditional
blocking code, while still maintaining the explicit nature of when non
blocking operations occur.</p>
</div>
<div class="section" id="sqlalchemy-asyncio-yes">
<h1>SQLAlchemy? Asyncio? Yes?</h1>
<p>Now that <tt class="docutils literal">asyncio</tt> is part of Python, it's a common integration point
for all things async.  Because it maintains the concepts
of meaningful return values and exception catching
semantics, getting an asyncio version of SQLAlchemy to work for real
is probably feasible; it will still require at least several external
modules that re-implement key methods of SQLAlchemy Core and ORM in terms of async results,
but it seems that the majority of code, even within execution-centric parts,
can stay much the same.  It no longer means a rewrite of all of SQLAlchemy,
and the async aspects should be able to remain entirely outside of the
central library itself.  I've started playing with this.  It will be a lot
of effort but should be doable, even for the ORM where some of the patterns
like &quot;lazy loading&quot; will just have to work in some more verbose way.</p>
<p>However.  I don't know that you really would generally want to <strong>use</strong>
an async-enabled form of SQLAlchemy.</p>
</div>
<div class="section" id="taking-async-web-scale">
<h1>Taking Async Web Scale</h1>
<p>As anticipated, let's get into where it's all going wrong, especially
for database-related code.</p>
<div class="section" id="issue-one-async-as-magic-performance-fairy-dust">
<h2>Issue One - Async as Magic Performance Fairy Dust</h2>
<p>Many (but certainly not all) within both the node.js community as well
as the Python community continue
to claim that asynchronous programming styles are innately superior
for concurrent performance in nearly all cases.   In particular, there's the
notion that the context switching approaches of explicit async systems
such as that of asyncio can be had virtually for free, and as the Python has a GIL,
that all adds up in some unspecified/non-illustrated/apples-to-oranges way to establish that asyncio will
totally, definitely be faster than using any kind of threaded approach, or at the
very least, not any slower.  Therefore any web application should as quickly
as possible be converted to use a front-to-back async approach for everything,
from HTTP request to database calls, and performance enhancements will come for free.</p>
<p>I will address this only in terms of database access.  For HTTP / &quot;chat&quot;
server styles of communication, either listening as a server or making client calls, asyncio may very well
be superior as it can allow lots more sleepy/arbitrarily slow connections to be tended
towards in a simple way.  But for local database access, this is just not the case.</p>
<div class="section" id="python-is-very-very-slow-compared-to-your-database">
<h3>1. Python is Very <span class="strikeout">, Very</span> Slow compared to your database</h3>
<p><strong>Update</strong> - redditor Riddlerforce found valid issues with this section,
in that I was not testing over a network connection.   Results here
are updated.  The conclusion is the same, but not as hyperbolically
amusing as it was before.</p>
<p>Let's first review asynchronous programming's
<a class="reference external" href="http://blog.kgriffs.com/2012/09/18/demystifying-async-io.html">sweet spot</a>,
the <a class="reference external" href="http://en.wikipedia.org/wiki/I/O_bound">I/O Bound</a> application:</p>
<blockquote>
I/O Bound refers to a
condition in which the time it takes to complete a computation is
determined principally by the period spent waiting for
input/output operations to be completed.  This circumstance
arises when the rate at which data is requested is slower than
the rate it is consumed or, in other words, <strong>more time is spent
requesting data than processing it.</strong></blockquote>
<p>A great misconception I seem to encounter often is the notion that communication
with the database takes up a majority of the time spent in a database-centric
Python application.   This perhaps is a common wisdom in compiled languages
such as C or maybe even Java, but generally not in Python.   Python is
<strong>very</strong> slow, compared to such systems; and while Pypy is certainly
a big help, the speed of Python is not nearly as fast as your database,
when dealing in terms of standard CRUD-style applications
(meaning: not running large OLAP-style queries, and of course assuming
relatively low network latencies).
As I worked up in my <a class="reference external" href="https://wiki.openstack.org/wiki/PyMySQL_evaluation">PyMySQL Evaluation</a>
for Openstack, whether a database driver (DBAPI) is written in pure Python
or in C will incur significant additional Python-level overhead.
For just the DBAPI alone, this can be as much as an order of magnitude
slower.   While network overhead will cause more balanced proportions
between CPU and IO, just the CPU time spent by Python driver itself still takes
up twice the time as the network IO, and that is without any additional database abstraction
libraries, business logic, or presentation logic in place.</p>
<p>This <a class="reference external" href="/files/2015/mysql_speed_test.py">script</a>, adapted from the
Openstack entry, illustrates a pretty straightforward set of INSERT and SELECT statements,
and virtually no Python code other than the barebones explicit calls into
the DBAPI.</p>
<p>MySQL-Python, a pure C DBAPI, runs it like the following over a network:</p>


<div class="pygments_manni"><pre><span></span>DBAPI (cProfile):  &lt;module &#39;MySQLdb&#39;&gt;
     47503 function calls in 14.863 seconds
DBAPI (straight time):  &lt;module &#39;MySQLdb&#39;&gt;, total seconds 12.962214
</pre></div>



<p>With PyMySQL, a pure-Python DBAPI,and a network connection we're about 30%
slower:</p>


<div class="pygments_manni"><pre><span></span>DBAPI (cProfile):  &lt;module &#39;pymysql&#39;&gt;
     23807673 function calls in 21.269 seconds
DBAPI (straight time):  &lt;module &#39;pymysql&#39;&gt;, total seconds 17.699732
</pre></div>



<p>Running against a local database, PyMySQL is an order of magnitude slower
than MySQLdb:</p>


<div class="pygments_manni"><pre><span></span>DBAPI:  &lt;module &#39;pymysql&#39;&gt;, total seconds 9.121727

DBAPI:  &lt;module &#39;MySQLdb&#39;&gt;, total seconds 1.025674
</pre></div>



<p>To highlight the actual proportion of these runs that's spent in IO,
the following two <a class="reference external" href="http://www.vrplumber.com/programming/runsnakerun/">RunSnakeRun</a>
displays illustrate how much time is actually for IO within the PyMySQL
run, both for local database as well as over a network connection.
The proportion is not as dramatic over a network connection, but in
that case network calls still only take 1/3rd of the total time; the other
2/3rds is spent in Python crunching the results.
Keep in mind this is <strong>just the DBAPI alone</strong>;
a real world application would have database abstraction layers, business
and presentation logic surrounding these calls as well:</p>
<div class="figure">
<img alt="PyMySQL profile result" src="/files/2015/pymysql_runsnake.png" />
<p class="caption">Local connection - clearly not IO bound.</p>
</div>
<div class="figure">
<img alt="PyMySQL profile result, over the network" src="/files/2015/pymysql_runsnake_network.png" />
<p class="caption">Network connection - not as dramatic, but still not IO bound
(8.7 sec of socket time vs. 24 sec for the overall execute)</p>
</div>
<p>Let's be clear here, that when using Python, calls to your database, unless
you're trying to make lots of complex analytical calls with enormous
result sets that you would normally not be doing in a high performing
application, or unless you have a very slow network, do not typically produce an
IO bound effect.  When we talk to databases, we are almost always using some form of connection
pooling, so the overhead of connecting is already mitigated to a large extent;
the database itself can select and insert small numbers of rows very fast
on a reasonable network.  The overhead of Python itself, just to marshal
messages over the wire and produce result sets, gives the CPU plenty
of work to do which removes any unique throughput advantages to be had
with non-blocking IO.  With real-world activities based around database
operations, the proportion spent in CPU only increases.</p>
</div>
<div class="section" id="asyncio-uses-appealing-but-relatively-inefficient-python-paradigms">
<h3>2. AsyncIO uses appealing, but relatively inefficient Python paradigms</h3>
<p>At the core of asyncio is that we are using the <tt class="docutils literal">&#64;asyncio.coroutine</tt>
decorator, which does some generator tricks in order to have your otherwise
synchronous looking function defer to other coroutines.  Central to this
is the <tt class="docutils literal">yield from</tt> technique, which causes the function to stop its
execution at that point, while other things go on until the event loop
comes back to that point.
This is a great idea, and it can also be done using the more common <tt class="docutils literal">yield</tt>
statement as well.   However, using <tt class="docutils literal">yield from</tt>, we are able to maintain
at least the appearance of the presence of return values:</p>


<div class="pygments_manni"><pre><span></span><span class="nd">@asyncio</span><span class="o">.</span><span class="n">coroutine</span>
<span class="k">def</span><span class="w"> </span><span class="nf">some_coroutine</span><span class="p">():</span>
    <span class="n">conn</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">db</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">conn</span>
</pre></div>



<p>That syntax is fantastic, I like it a lot, but unfortunately, the mechanism
of that <tt class="docutils literal">return conn</tt> statement is necessarily that it raises a <tt class="docutils literal">StopIteration</tt>
exception.   This, combined with the fact that each <tt class="docutils literal">yield from</tt> call
more or less adds up to the overhead of an individual function call separately.
I <a class="reference external" href="https://twitter.com/zzzeek/status/563865362996133889">tweeted</a> a simple
demonstration of this, which I include here in abbreviated form:</p>


<div class="pygments_manni"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">return_with_normal</span><span class="p">():</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;One function calls another normal function, which returns a value.&quot;&quot;&quot;</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">foo</span><span class="p">():</span>
        <span class="k">return</span> <span class="mi">5</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">bar</span><span class="p">():</span>
        <span class="n">f1</span> <span class="o">=</span> <span class="n">foo</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">f1</span>

    <span class="k">return</span> <span class="n">bar</span>

<span class="k">def</span><span class="w"> </span><span class="nf">return_with_generator</span><span class="p">():</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;One function calls another coroutine-like function,</span>
<span class="sd">    which returns a value.&quot;&quot;&quot;</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">decorate_to_return</span><span class="p">(</span><span class="n">fn</span><span class="p">):</span>
        <span class="k">def</span><span class="w"> </span><span class="nf">decorate</span><span class="p">():</span>
            <span class="n">it</span> <span class="o">=</span> <span class="n">fn</span><span class="p">()</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">x</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
            <span class="k">except</span> <span class="ne">StopIteration</span> <span class="k">as</span> <span class="n">y</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">y</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">return</span> <span class="n">decorate</span>

    <span class="nd">@decorate_to_return</span>
    <span class="k">def</span><span class="w"> </span><span class="nf">foo</span><span class="p">():</span>
        <span class="k">yield from</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="mi">5</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">bar</span><span class="p">():</span>
        <span class="n">f1</span> <span class="o">=</span> <span class="n">foo</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">f1</span>

    <span class="k">return</span> <span class="n">bar</span>

<span class="n">return_with_normal</span> <span class="o">=</span> <span class="n">return_with_normal</span><span class="p">()</span>
<span class="n">return_with_generator</span> <span class="o">=</span> <span class="n">return_with_generator</span><span class="p">()</span>

<span class="kn">import</span><span class="w"> </span><span class="nn">timeit</span>

<span class="nb">print</span><span class="p">(</span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="s2">&quot;return_with_generator()&quot;</span><span class="p">,</span>
    <span class="s2">&quot;from __main__ import return_with_generator&quot;</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">10000000</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="s2">&quot;return_with_normal()&quot;</span><span class="p">,</span>
    <span class="s2">&quot;from __main__ import return_with_normal&quot;</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">10000000</span><span class="p">))</span>
</pre></div>



<p>The results we get are that the do-nothing <tt class="docutils literal">yield from</tt> + <tt class="docutils literal">StopIteration</tt>
take about six times longer:</p>


<div class="pygments_manni"><pre><span></span>yield from: 12.52761328802444
normal: 2.110536064952612
</pre></div>



<p>To which many people said to me, &quot;so what?  Your database call is much
more of the time spent&quot;.  Never minding that we're not talking here about
an approach to <em>optimize</em> existing code, but to <em>prevent making perfectly
fine code more slow than it already is</em>.  The PyMySQL example
should illustrate that Python overhead adds up very fast, even just within
a pure Python driver, and in the overall profile dwarfs the time spent
within the database itself.  However, this argument still may not be
convincing enough.</p>
<p>So, I will here <a class="reference external" href="https://github.com/zzzeek/bigdata">present</a>
a comprehensive test suite which illustrates
traditional threads in Python against asyncio, as well as gevent style
nonblocking IO.  We will use <a class="reference external" href="http://initd.org/psycopg/">psycopg2</a> which
is currently the <strong>only production DBAPI that even supports async</strong>, in
conjunction with <a class="reference external" href="https://github.com/aio-libs/aiopg">aiopg</a> which adapts
psycopg2's async support to asyncio and <a class="reference external" href="https://github.com/psycopg/psycogreen/">psycogreen</a>
which adapts it to gevent.</p>
<p>The purpose of the test suite is to
load a few million rows into a Postgresql database as fast
as possible, while using the same general set of SQL instructions, such that
we can see if in fact the GIL slows us down so much that asyncio blows
right past us with ease.  The suite can use any number of connections simultaneously;
at the highest I boosted it up to using 350 concurrent connections, which trust me,
will not make your DBA happy <strong>at all</strong>.</p>
<p>The results of several runs on different machines under different conditions
are summarized at the bottom of the <a class="reference external" href="https://github.com/zzzeek/bigdata">README</a>.
The best performance I could get was running the Python code on one laptop
interfacing to the Postgresql database on another, but in virtually every test
I ran, whether I ran just 15 threads/coroutines on my Mac, or 350 (!) threads/coroutines
on my Linux laptop, threaded code got the job done much faster than asyncio
in every case (including the 350 threads case, to my surprise), and usually
faster than gevent as well.  Below are the results from running
120 threads/processes/connections on the Linux laptop networked to
the Postgresql database on a Mac laptop:</p>


<div class="pygments_manni"><pre><span></span>Python2.7.8 threads (22k r/sec, 22k r/sec)
Python3.4.1 threads (10k r/sec, 21k r/sec)
Python2.7.8 gevent (18k r/sec, 19k r/sec)
Python3.4.1 asyncio (8k r/sec, 10k r/sec)
</pre></div>



<p>Above, we see asyncio significantly slower for the first part of the
run (Python 3.4 seemed to have some issue here in both threaded and asyncio),
and for the second part, fully twice as slow compared to both Python2.7 and
Python3.4 interpreters using threads.   Even running 350 concurrent
connections, which is way more than you'd usually ever want a single process
to run, asyncio could hardly approach the efficiency of threads.  Even with
the very fast and pure C-code psycopg2 driver, just the overhead of the
aiopg library on top combined with the need for in-Python receipt of
polling results with psycopg2's asynchronous library added more than enough
Python overhead to slow the script right down.</p>
<p>Remember, I wasn't even trying to prove that asyncio is significantly slower
than threads; only that it <em>wasn't any faster</em>.  The results I got were more
dramatic than I expected.   We see also that an extremely low-latency async approach,
e.g. that of gevent, is also slower than threads, but not by much, which
confirms first that async IO is definitely not faster in this scenario,
but also because asyncio is so much slower than gevent,
that it is in fact the in-Python overhead of asyncio's coroutines
and other Python constructs that are likely adding up to very significant
additional latency on top of the latency of less efficient IO-based context
switching.</p>
</div>
</div>
<div class="section" id="issue-two-async-as-making-coding-easier">
<h2>Issue Two - Async as Making Coding Easier</h2>
<p>This is the flip side to the &quot;magic fairy dust&quot; coin.  This argument
expands upon the &quot;threads are bad&quot; rhetoric, and in its most
extreme form goes that if a program at some level happens to spawn a thread, such as
if you wrote a WSGI application and happen to run it under mod_wsgi using
a threadpool, you are now doing &quot;threaded programming&quot;, of the caliber that
is just as difficult as if you were doing <a class="reference external" href="http://www.cs.cmu.edu/afs/cs/academic/class/15492-f07/www/pthreads.html#PITFALLS">POSIX threading exercises</a> throughout your code.   Despite the fact
that a WSGI application should not have the slightest mention of anything
to do with in-process shared and mutable state within in it,
nope, you're doing threaded programming, threads are hard, and you should stop.</p>
<p>The &quot;threads are bad&quot; argument has an interesting twist (ha!), which
is that it is being used by explicit async advocates to argue against
implicit async techniques.  Glyph's <a class="reference external" href="https://glyph.twistedmatrix.com/2014/02/unyielding.html">Unyielding</a>
post makes exactly this point very well.  The premise goes
that if you've accepted that threaded concurrency
is a bad thing, then using the implicit style of async IO is just
as bad, because at the end of the day, the code looks the same as threaded
code, and because IO can happen anywhere, it's just as non-deterministic
as using traditional threads.   I would happen to agree with this,
that yes, the problems of concurrency in a gevent-like system are just
as bad, if not worse, than a threaded system.   One reason is that
concurrency problems in threaded Python are fairly &quot;soft&quot; because
already the GIL, as much as we hate it, makes all kinds of normally
disastrous operations, like appending to a list, safe.
But with green threads, you can easily have hundreds of them without
breaking a sweat and you can sometimes stumble across pretty
<a class="reference external" href="https://github.com/PyMySQL/PyMySQL/issues/275">weird issues</a> that are normally
not possible to encounter with traditional, GIL-protected threads.</p>
<p>As an aside, it should be noted that Glyph takes a direct swipe at the &quot;magic fairy dust&quot; crowd:</p>
<blockquote>
<p>Unfortunately, “asynchronous” systems have often been evangelized by emphasizing a somewhat dubious optimization which allows for a higher level of I/O-bound concurrency than with preemptive threads, rather than the problems with threading as a programming model that I’ve explained above. By characterizing “asynchronousness” in this way, it makes sense to lump all 4 choices together.</p>
<p>I’ve been guilty of this myself, especially in years past: saying that a system using Twisted is more efficient than one using an alternative approach using threads. In many cases that’s been true, but:</p>
<blockquote>
<ol class="arabic simple">
<li>the situation is almost always more complicated than that, when it
comes to performance,</li>
<li>“context switching” is rarely a bottleneck in real-world programs, and</li>
<li>it’s a bit of a distraction from the much bigger advantage of
event-driven programming, which is simply that it’s easier to
write programs at scale, in both senses (that is, programs
containing lots of code as well as programs which have many
concurrent users).</li>
</ol>
</blockquote>
</blockquote>
<p>People will quote Glyph's post when they want to
talk about how you'll have fewer bugs in your program when you switch to
asyncio, but continue to promise greater performance as well, for some
reason choosing to ignore this part of this very well written post.</p>
<p>Glyph makes a great, and very clear, argument for the twin points
that both non-blocking IO should be used, and that it should be explicit.
But the reasoning has nothing to do with non-blocking IO's original beginnings
as a reasonable way to process data from a large number of sleepy and slow
connections.   It instead has to do with the nature of the event loop and
how an entirely new concurrency model, removing the need to expose OS-level
context switching, is emergent.</p>
<p>While we've come a long way from writing callbacks and can now again
write code that looks very linear with approaches like asyncio, the approach
should still require that the programmer explicitly specify all those
function calls where IO is known to occur.  It begins with the following
example:</p>


<div class="pygments_manni"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">transfer</span><span class="p">(</span><span class="n">amount</span><span class="p">,</span> <span class="n">payer</span><span class="p">,</span> <span class="n">payee</span><span class="p">,</span> <span class="n">server</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">payer</span><span class="o">.</span><span class="n">sufficient_funds_for_withdrawal</span><span class="p">(</span><span class="n">amount</span><span class="p">):</span>
        <span class="k">raise</span> <span class="n">InsufficientFunds</span><span class="p">()</span>
    <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payer}</span><span class="s2"> has sufficient funds.&quot;</span><span class="p">,</span> <span class="n">payer</span><span class="o">=</span><span class="n">payer</span><span class="p">)</span>
    <span class="n">payee</span><span class="o">.</span><span class="n">deposit</span><span class="p">(</span><span class="n">amount</span><span class="p">)</span>
    <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payee}</span><span class="s2"> received payment&quot;</span><span class="p">,</span> <span class="n">payee</span><span class="o">=</span><span class="n">payee</span><span class="p">)</span>
    <span class="n">payer</span><span class="o">.</span><span class="n">withdraw</span><span class="p">(</span><span class="n">amount</span><span class="p">)</span>
    <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payer}</span><span class="s2"> made payment&quot;</span><span class="p">,</span> <span class="n">payer</span><span class="o">=</span><span class="n">payer</span><span class="p">)</span>
    <span class="n">server</span><span class="o">.</span><span class="n">update_balances</span><span class="p">([</span><span class="n">payer</span><span class="p">,</span> <span class="n">payee</span><span class="p">])</span>
</pre></div>



<p>The concurrency mistake here in a threaded perspective is that if two
threads both run <tt class="docutils literal">transfer()</tt> they both may withdraw from <tt class="docutils literal">payer</tt>
such that <tt class="docutils literal">payer</tt> goes below <tt class="docutils literal">InsufficientFunds</tt>, without this condition
being raised.</p>
<p>The explcit async version is then:</p>


<div class="pygments_manni"><pre><span></span><span class="nd">@coroutine</span>
<span class="k">def</span><span class="w"> </span><span class="nf">transfer</span><span class="p">(</span><span class="n">amount</span><span class="p">,</span> <span class="n">payer</span><span class="p">,</span> <span class="n">payee</span><span class="p">,</span> <span class="n">server</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">payer</span><span class="o">.</span><span class="n">sufficient_funds_for_withdrawal</span><span class="p">(</span><span class="n">amount</span><span class="p">):</span>
        <span class="k">raise</span> <span class="n">InsufficientFunds</span><span class="p">()</span>
    <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payer}</span><span class="s2"> has sufficient funds.&quot;</span><span class="p">,</span> <span class="n">payer</span><span class="o">=</span><span class="n">payer</span><span class="p">)</span>
    <span class="n">payee</span><span class="o">.</span><span class="n">deposit</span><span class="p">(</span><span class="n">amount</span><span class="p">)</span>
    <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payee}</span><span class="s2"> received payment&quot;</span><span class="p">,</span> <span class="n">payee</span><span class="o">=</span><span class="n">payee</span><span class="p">)</span>
    <span class="n">payer</span><span class="o">.</span><span class="n">withdraw</span><span class="p">(</span><span class="n">amount</span><span class="p">)</span>
    <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payer}</span><span class="s2"> made payment&quot;</span><span class="p">,</span> <span class="n">payer</span><span class="o">=</span><span class="n">payer</span><span class="p">)</span>
    <span class="k">yield from</span> <span class="n">server</span><span class="o">.</span><span class="n">update_balances</span><span class="p">([</span><span class="n">payer</span><span class="p">,</span> <span class="n">payee</span><span class="p">])</span>
</pre></div>



<p>Where now, within the scope of the process we're in, we know that we are only
allowing anything else to happen at the bottom, when we call
<tt class="docutils literal">yield from server.update_balances()</tt>.  There is no chance that any
other concurrent calls to <tt class="docutils literal">payer.withdraw()</tt> can occur while we're in the
function's body and have not yet reached the <tt class="docutils literal">server.update_balances()</tt>
call.</p>
<p>He then makes a clear point as to why even the implicit gevent-style async isn't
sufficient.   Because with the above program, the fact that <tt class="docutils literal">payee.deposit()</tt>
and <tt class="docutils literal">payer.withdraw()</tt> do <strong>not</strong> do a <tt class="docutils literal">yield from</tt>, we are assured
that no IO might occur in future versions of these calls which would break
into our scheduling and potentially run another <tt class="docutils literal">transfer()</tt> before ours is
complete.</p>
<p>(As an aside, I'm not actually sure, in the realm of &quot;we had to type <tt class="docutils literal">yield from</tt> and
that's how we stay aware of what's going on&quot;, why the <tt class="docutils literal">yield from</tt>
needs to be a real, structural part of the program and not
just, for example, a magic comment consumed by a gevent/eventlet-integrated
linter that tests callstacks for IO and verifies that the corresponding
source code has been annotated with special
comments, as that would have the identical effect without impacting any
libraries outside of that system and without incurring all the Python
performance overhead of explicit async.  But that's a different topic.)</p>
<p>Regardless of style of explicit coroutine, there's two flaws with this approach.</p>
<p>One is that asyncio makes it so easy to type out <tt class="docutils literal">yield from</tt> that the
idea that it prevents us from making mistakes loses a lot of
its plausibility.  A commenter on Hacker News made this great
<a class="reference external" href="https://news.ycombinator.com/item?id=8990850">point</a>
about the notion of asynchronous code being easier to debug:</p>
<blockquote>
<p>It's basically, &quot;I want context switches syntactically explicit in
my code. If they aren't, reasoning about it is exponentially
harder.&quot;</p>
<p>And I think that's pretty clearly a strawman. Everything the
author claims about threaded code is true of any re-entrant code,
multi-threaded or not. If your function inadvertently calls a
function which calls the original function recursively, you have
the exact same problem.</p>
<p>But, guess what, that just doesn't happen that often. Most code
isn't re-entrant. Most state isn't shared.</p>
<p>For code that is concurrent and does interact in interesting ways,
you are going to have to reason about it carefully. Smearing
&quot;yield from&quot; all over your code doesn't solve.</p>
<p><strong>In practice, you'll end up with so many &quot;yield from&quot; lines in your
code that you're right back to &quot;well, I guess I could context
switch just about anywhere&quot;, which is the problem you were trying
to avoid in the first place.</strong></p>
</blockquote>
<p>In my benchmark code, one can see this last point is exactly true.  Here's a bit
of the threaded version:</p>


<div class="pygments_manni"><pre><span></span><span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
    <span class="s2">&quot;select id from geo_record where fileid=</span><span class="si">%s</span><span class="s2"> and logrecno=</span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span>
    <span class="p">(</span><span class="n">item</span><span class="p">[</span><span class="s1">&#39;fileid&#39;</span><span class="p">],</span> <span class="n">item</span><span class="p">[</span><span class="s1">&#39;logrecno&#39;</span><span class="p">])</span>
<span class="p">)</span>
<span class="n">row</span> <span class="o">=</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="n">geo_record_id</span> <span class="o">=</span> <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>

<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
    <span class="s2">&quot;select d.id, d.index from dictionary_item as d &quot;</span>
    <span class="s2">&quot;join matrix as m on d.matrix_id=m.id where m.segment_id=</span><span class="si">%s</span><span class="s2"> &quot;</span>
    <span class="s2">&quot;order by m.sortkey, d.index&quot;</span><span class="p">,</span>
    <span class="p">(</span><span class="n">item</span><span class="p">[</span><span class="s1">&#39;cifsn&#39;</span><span class="p">],)</span>
<span class="p">)</span>
<span class="n">dictionary_ids</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">cursor</span>
<span class="p">]</span>
<span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">dictionary_ids</span><span class="p">)</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">item</span><span class="p">[</span><span class="s1">&#39;items&#39;</span><span class="p">])</span>

<span class="k">for</span> <span class="n">dictionary_id</span><span class="p">,</span> <span class="n">element</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">dictionary_ids</span><span class="p">,</span> <span class="n">item</span><span class="p">[</span><span class="s1">&#39;items&#39;</span><span class="p">]):</span>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
        <span class="s2">&quot;insert into data_element &quot;</span>
        <span class="s2">&quot;(geo_record_id, dictionary_item_id, value) &quot;</span>
        <span class="s2">&quot;values (</span><span class="si">%s</span><span class="s2">, </span><span class="si">%s</span><span class="s2">, </span><span class="si">%s</span><span class="s2">)&quot;</span><span class="p">,</span>
        <span class="p">(</span><span class="n">geo_record_id</span><span class="p">,</span> <span class="n">dictionary_id</span><span class="p">,</span> <span class="n">element</span><span class="p">)</span>
    <span class="p">)</span>
</pre></div>



<p>Here's a bit of the asyncio version:</p>


<div class="pygments_manni"><pre><span></span><span class="k">yield from</span> <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
    <span class="s2">&quot;select id from geo_record where fileid=</span><span class="si">%s</span><span class="s2"> and logrecno=</span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span>
    <span class="p">(</span><span class="n">item</span><span class="p">[</span><span class="s1">&#39;fileid&#39;</span><span class="p">],</span> <span class="n">item</span><span class="p">[</span><span class="s1">&#39;logrecno&#39;</span><span class="p">])</span>
<span class="p">)</span>
<span class="n">row</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="n">geo_record_id</span> <span class="o">=</span> <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>

<span class="k">yield from</span> <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
    <span class="s2">&quot;select d.id, d.index from dictionary_item as d &quot;</span>
    <span class="s2">&quot;join matrix as m on d.matrix_id=m.id where m.segment_id=</span><span class="si">%s</span><span class="s2"> &quot;</span>
    <span class="s2">&quot;order by m.sortkey, d.index&quot;</span><span class="p">,</span>
    <span class="p">(</span><span class="n">item</span><span class="p">[</span><span class="s1">&#39;cifsn&#39;</span><span class="p">],)</span>
<span class="p">)</span>
<span class="n">rows</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
<span class="n">dictionary_ids</span> <span class="o">=</span> <span class="p">[</span><span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">rows</span><span class="p">]</span>

<span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">dictionary_ids</span><span class="p">)</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">item</span><span class="p">[</span><span class="s1">&#39;items&#39;</span><span class="p">])</span>

<span class="k">for</span> <span class="n">dictionary_id</span><span class="p">,</span> <span class="n">element</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">dictionary_ids</span><span class="p">,</span> <span class="n">item</span><span class="p">[</span><span class="s1">&#39;items&#39;</span><span class="p">]):</span>
    <span class="k">yield from</span> <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span>
        <span class="s2">&quot;insert into data_element &quot;</span>
        <span class="s2">&quot;(geo_record_id, dictionary_item_id, value) &quot;</span>
        <span class="s2">&quot;values (</span><span class="si">%s</span><span class="s2">, </span><span class="si">%s</span><span class="s2">, </span><span class="si">%s</span><span class="s2">)&quot;</span><span class="p">,</span>
        <span class="p">(</span><span class="n">geo_record_id</span><span class="p">,</span> <span class="n">dictionary_id</span><span class="p">,</span> <span class="n">element</span><span class="p">)</span>
    <span class="p">)</span>
</pre></div>



<p>Notice how they look <strong>exactly the same</strong>?   The fact that <tt class="docutils literal">yield from</tt>
is present is not in any way changing the code that I write, or the decisions
that I make - this is because <a class="reference external" href="https://twitter.com/zzzeek/status/559172684060557313">in boring database code</a>,
we basically need to do the queries that we need to do, in order.   I'm not going
to try to weave an intelligent, thoughtful system of in-process concurrency into how I call
into the database or not, or try to repurpose when I happen to need database
data as a means of also locking out other parts of my program;
if I need data I'm going to call for it.</p>
<p>Whether or not that's compelling, it doesn't actually matter - using
async or mutexes or whatever inside our program to control concurrency
is in fact completely insufficient in any case.   Instead, there is of course something
we <strong>absolutely must always do</strong> in real world boring database code in the name of concurrency,
and that is:</p>
<div class="section" id="database-code-handles-concurrency-through-acid-not-in-process-synchronization">
<h3>Database Code Handles Concurrency through ACID, Not In-Process Synchronization</h3>
<p>Whether or not we've managed to use threaded code or coroutines with implicit
or explicit IO and find all the race conditions that would occur in our
process, that matters not at all if the thing we're talking to is a relational
database, especially in today's world where everything runs in clustered / horizontal /
distributed ways - the handwringing of academic theorists regarding the
non-deterministic nature of threads is just the tip of the iceberg; we need
to deal with entirely distinct processes, and regardless of what's said,
non-determinism is here to stay.</p>
<p>For database code, you have exactly one technique
to use in order to assure correct concurrency, and that is <strong>by using ACID-oriented
constructs and techniques</strong>.  These unfortunately don't come magically
or via any known silver bullet, though there are <a class="reference external" href="http://www.sqlalchemy.org">great tools</a>
that are designed to help steer you in the right direction.</p>
<p>All of the example <tt class="docutils literal">transfer()</tt> functions above are incorrect from a
database perspective.  Here is the correct one:</p>


<div class="pygments_manni"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">transfer</span><span class="p">(</span><span class="n">amount</span><span class="p">,</span> <span class="n">payer</span><span class="p">,</span> <span class="n">payee</span><span class="p">,</span> <span class="n">server</span><span class="p">):</span>
    <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">begin</span><span class="p">():</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">payer</span><span class="o">.</span><span class="n">sufficient_funds_for_withdrawal</span><span class="p">(</span><span class="n">amount</span><span class="p">,</span> <span class="n">lock</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
            <span class="k">raise</span> <span class="n">InsufficientFunds</span><span class="p">()</span>
        <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payer}</span><span class="s2"> has sufficient funds.&quot;</span><span class="p">,</span> <span class="n">payer</span><span class="o">=</span><span class="n">payer</span><span class="p">)</span>
        <span class="n">payee</span><span class="o">.</span><span class="n">deposit</span><span class="p">(</span><span class="n">amount</span><span class="p">)</span>
        <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payee}</span><span class="s2"> received payment&quot;</span><span class="p">,</span> <span class="n">payee</span><span class="o">=</span><span class="n">payee</span><span class="p">)</span>
        <span class="n">payer</span><span class="o">.</span><span class="n">withdraw</span><span class="p">(</span><span class="n">amount</span><span class="p">)</span>
        <span class="n">log</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{payer}</span><span class="s2"> made payment&quot;</span><span class="p">,</span> <span class="n">payer</span><span class="o">=</span><span class="n">payer</span><span class="p">)</span>
        <span class="n">server</span><span class="o">.</span><span class="n">update_balances</span><span class="p">([</span><span class="n">payer</span><span class="p">,</span> <span class="n">payee</span><span class="p">])</span>
</pre></div>



<p>See the difference?  Above, we use a transaction.   To call upon the SELECT of the payer
funds and then modify them using autocommit would be totally wrong.
We then must ensure that we retrieve this value using some appropriate
system of locking, so that from the time that we read it, to the time that
we write it, it is <strong>not possible</strong> to change the value based on a stale
assumption.   We'd probably use a <tt class="docutils literal">SELECT .. FOR UPDATE</tt> to lock the row
we intend to update.  Or, we might use &quot;read committed&quot; isolation in conjunction with a
<a class="reference external" href="http://docs.sqlalchemy.org/en/rel_0_9/orm/versioning.html">version counter</a>
for an optimistic approach, so that our function fails if a race condition
occurs.    But in no way does the fact that we're using
threads, greenlets, or whatever concurrency mechanism in our single process
have any impact on what strategy we use here; our concurrency concerns involve
the interaction of entirely separate processes.</p>
</div>
</div>
</div>
<div class="section" id="sum-up">
<h1>Sum up!</h1>
<p>Please note I am <em>not</em> trying to make the point that you shouldn't use
asyncio.  I think it's really well done, it's fun to use,
and I still am interested in having
more of a SQLAlchemy story for it, because I'm sure folks will still want this
no matter what anyone says.</p>
<p>My point is that when it comes to stereotypical database
logic, there are no advantages to using it versus a traditional
threaded approach, and you can likely expect
a small to moderate <strong>decrease</strong> in performance, not an <strong>increase</strong>.
This is well known to many of <a class="reference external" href="https://twitter.com/laurencerowe/status/566130897473130496">my</a> <a class="reference external" href="https://twitter.com/aminusfu/status/566024241821126658">colleagues</a>, but recently I've had
to argue this point nonetheless.</p>
<p>An ideal integration situation if one wants to have the advantages of
non-blocking IO for receiving web requests without needing to turn
their business logic into explicit async is a simple combination
of nginx
with <a class="reference external" href="https://uwsgi-docs.readthedocs.org/en/latest/">uWsgi</a>, for example.</p>
</div>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Introduction to SQLAlchemy - Pycon 2013 - Wrapup</title>
      <link>http://techspot.zzzeek.org/2013/04/04/introduction-to-sqlalchemy-pycon-2013-wrapup</link>
      <pubDate>Thu, 04 Apr 2013 12:10:00 EDT</pubDate>
      <category><![CDATA[Talks]]></category>
      <category><![CDATA[SQLAlchemy]]></category>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2013/04/04/introduction-to-sqlalchemy-pycon-2013-wrapup</guid>
      <description>Introduction to SQLAlchemy - Pycon 2013 - Wrapup</description>
      <content:encoded><![CDATA[<div class="document">
<p>Video is up for my Pycon 2013 tutorial <a class="reference external" href="https://us.pycon.org/2013/schedule/presentation/16/">Introduction to SQLAlchemy</a>.</p>
<p>For those who want to follow along at home, the full code and prerequisite material is available here:</p>
<ul class="simple">
<li><a class="reference external" href="/files/2013/pycon2013_student_package.tar.gz">Prerequisite code</a></li>
<li><a class="reference external" href="https://speakerdeck.com/zzzeek/introduction-to-sqlalchemy-pycon-2013">Slides on Speakerdeck</a></li>
</ul>
<p><span class="raw-html"><iframe width="640" height="360" src="http://www.youtube.com/embed/woKYyhLCcnU?feature=player_detailpage" frameborder="0" allowfullscreen></iframe></span></p>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Introduction to SQLAlchemy - Pycon 2013</title>
      <link>http://techspot.zzzeek.org/2013/03/05/introduction-to-sqlalchemy-pycon-2013</link>
      <pubDate>Tue, 05 Mar 2013 12:10:00 EST</pubDate>
      <category><![CDATA[Talks]]></category>
      <category><![CDATA[SQLAlchemy]]></category>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2013/03/05/introduction-to-sqlalchemy-pycon-2013</guid>
      <description>Introduction to SQLAlchemy - Pycon 2013</description>
      <content:encoded><![CDATA[<div class="document">
<p>Preparations are just about complete for my upcoming tutorial
<a class="reference external" href="https://us.pycon.org/2013/schedule/presentation/16/">Introduction to SQLAlchemy</a>.
There's a good crowd of people already attending, and I <em>think</em> registration is still open in case
more people want to sign up.</p>
<p>But in any case, if you are coming, this year there is <a class="reference external" href="https://us.pycon.org/2013/community/tutorials/16/">prerequisite material</a>, including the software installs as well as
a &quot;Relational Overview&quot; section that covers the basics of SQL and relational databases.
Everyone coming to the tutorial should read through this document, so that we're all
on roughly the same page regarding upfront SQL knowledge, and try to get the software
installed.   If there's any issues with the software, please report <a class="reference external" href="https://bitbucket.org/zzzeek/pycon2013_student_package/issues?status=new&amp;status=open">bugs</a> to me and we'll try to get
them resolved by tutorial time.   We will also be available at the <a class="reference external" href="https://us.pycon.org/2013/community/welcome/">Wednesday 6:30pm tutorial setup session</a> to help with installs.</p>
<p>Historically, tutorials pack the whole three hours of material up pretty solidly, and I hope I can balance getting lots of coverage versus not talking too fast.  Thanks for signing up !</p>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Pycon Canada - the SQLAlchemy Session In Depth</title>
      <link>http://techspot.zzzeek.org/2012/11/14/pycon-canada-the-sqlalchemy-session-in-depth</link>
      <pubDate>Wed, 14 Nov 2012 08:31:00 EST</pubDate>
      <category><![CDATA[Talks]]></category>
      <category><![CDATA[SQLAlchemy]]></category>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2012/11/14/pycon-canada-the-sqlalchemy-session-in-depth</guid>
      <description>Pycon Canada - the SQLAlchemy Session In Depth</description>
      <content:encoded><![CDATA[<div class="document">
<p>Video is up for my <a class="reference external" href="http://pycon.ca/">Pycon.ca</a> talk, <em>The SQLAlchemy Session - In Depth</em>.
In this talk, I delve into the key philosophies behind the design of SQLAlchemy's Session system.
Starting with a brief review of the ACID model, I contrast the approach of the so-called &quot;active record&quot;
pattern to that of the more explicit Session pattern, and how the two approaches integrate with the
ACID model at work within a relational database.   Afterwards, I present an HTML animation of a Session
object at work.</p>
<ul class="simple">
<li><a class="reference external" href="http://pyvideo.org/video/1600/the-sqlalchemy-session-in-depth">Video</a> (setting the quality to 480p is recommended)</li>
<li><a class="reference external" href="/files/2012/session.key.pdf">Slides</a> (pdf format)</li>
<li><a class="reference external" href="/files/2012/session.html.tar.gz">HTML Demo</a> (tar.gz)</li>
</ul>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>The Absolutely Simplest Consistent Hashing Example</title>
      <link>http://techspot.zzzeek.org/2012/07/07/the-absolutely-simplest-consistent-hashing-example</link>
      <pubDate>Sat, 07 Jul 2012 12:01:00 EDT</pubDate>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2012/07/07/the-absolutely-simplest-consistent-hashing-example</guid>
      <description>The Absolutely Simplest Consistent Hashing Example</description>
      <content:encoded><![CDATA[<div class="document">
<p>Lately I've been studying <a class="reference external" href="http://redis.io">Redis</a> a lot.  When using key/value databases
like Redis, as well as caches like <a class="reference external" href="http://memcached.org/">Memcached</a>,
if you want to scale keys across multiple nodes, you need a consistent
hashing algorithm.   Consistent hashing is what we use when we want to distribute
a set of keys along a span of key/value servers in a...well consistent fashion.</p>
<p>If you Google around to learn what consistent hashing means,
the article that most directly tells you &quot;the answer&quot; without
a lot of handwringing is <a class="reference external" href="http://weblogs.java.net/blog/tomwhite/archive/2007/11/consistent_hash.html">Consistent Hashing</a> by Tom White.
Not only does it explain the concept very clearly, it even has a plain and
simple code example in Java.</p>
<p>The recipe in Tom's post is dependent on the capabilities of Java's <tt class="docutils literal">TreeMap</tt>
which we don't have in Python, but after some contemplation it became apparent
that the functionality of <tt class="docutils literal">circle.tailMap(hash)</tt> is something we already
have using <a class="reference external" href="http://docs.python.org/library/bisect.html">bisect</a>, that is, we have a
sorted array of integers, and a new number.  Where in the array does the
new number go?  <tt class="docutils literal">bisect.bisect()</tt> will give you that, with the same efficiency as
<tt class="docutils literal">TreeMap</tt>.</p>
<p>As a sanity check, I searched a bit more for Python implementations.  I found
a recipe by <a class="reference external" href="http://amix.dk/blog/viewEntry/19367">Amir Salihefendic</a>, which
seems to be based on the Java recipe and is pretty nice,
but in the post he's searching the circle for hash values using
a linear search, ouch!  Turns out
Amir is in fact using <tt class="docutils literal">bisect</tt> in his Python Cheese Shop package <a class="reference external" href="http://pypi.python.org/pypi/hash_ring/">hash_ring</a>, but by then it was too late, I had already written my own recipe
as well as tests (which <tt class="docutils literal">hash_ring</tt> doesn't appear to have, at least in the downloaded
distribution).
There's also <a class="reference external" href="http://pypi.python.org/pypi/python-continuum/">Continuum</a>,
taking a slightly more heavy-handed approach (three separate classes and an expensive
<tt class="docutils literal">IndexError</tt> being caught to detect keys beyond the circle).   Both systems, Continuum
more so, seem to encourage using hostnames directly as keys - as noted by
<a class="reference external" href="http://blog.zawodny.com/2011/02/26/redis-sharding-at-craigslist/">Jeremy Zawodny</a>,
with a persistent system like Redis this is a bad idea as it means you can't move
a particular key set to a new host.</p>
<p>So spending a bit of <a class="reference external" href="http://en.wikipedia.org/wiki/Not_invented_here">NIH</a> capital, here's
my recipe, which provides a dictionary interface so that you can store hostnames or even actual
client instances, keyed to symbolic names:</p>


<div class="pygments_manni"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">bisect</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">md5</span>

<span class="k">class</span><span class="w"> </span><span class="nc">ConsistentHashRing</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;Implement a consistent hashing ring.&quot;&quot;&quot;</span>

    <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">replicas</span><span class="o">=</span><span class="mi">100</span><span class="p">):</span>
<span class="w">        </span><span class="sd">&quot;&quot;&quot;Create a new ConsistentHashRing.</span>

<span class="sd">        :param replicas: number of replicas.</span>

<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">replicas</span> <span class="o">=</span> <span class="n">replicas</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_keys</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_nodes</span> <span class="o">=</span> <span class="p">{}</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">_hash</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
<span class="w">        </span><span class="sd">&quot;&quot;&quot;Given a string key, return a hash value.&quot;&quot;&quot;</span>

        <span class="k">return</span> <span class="n">long</span><span class="p">(</span><span class="n">md5</span><span class="o">.</span><span class="n">md5</span><span class="p">(</span><span class="n">key</span><span class="p">)</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">(),</span> <span class="mi">16</span><span class="p">)</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">_repl_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">nodename</span><span class="p">):</span>
<span class="w">        </span><span class="sd">&quot;&quot;&quot;Given a node name, return an iterable of replica hashes.&quot;&quot;&quot;</span>

        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_hash</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s</span><span class="s2">:</span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">nodename</span><span class="p">,</span> <span class="n">i</span><span class="p">))</span>
                <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">replicas</span><span class="p">))</span>

    <span class="k">def</span><span class="w"> </span><span class="fm">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">nodename</span><span class="p">,</span> <span class="n">node</span><span class="p">):</span>
<span class="w">        </span><span class="sd">&quot;&quot;&quot;Add a node, given its name.</span>

<span class="sd">        The given nodename is hashed</span>
<span class="sd">        among the number of replicas.</span>

<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">for</span> <span class="n">hash_</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_repl_iterator</span><span class="p">(</span><span class="n">nodename</span><span class="p">):</span>
            <span class="k">if</span> <span class="n">hash_</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_nodes</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Node name </span><span class="si">%r</span><span class="s2"> is &quot;</span>
                            <span class="s2">&quot;already present&quot;</span> <span class="o">%</span> <span class="n">nodename</span><span class="p">)</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">_nodes</span><span class="p">[</span><span class="n">hash_</span><span class="p">]</span> <span class="o">=</span> <span class="n">node</span>
            <span class="n">bisect</span><span class="o">.</span><span class="n">insort</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_keys</span><span class="p">,</span> <span class="n">hash_</span><span class="p">)</span>

    <span class="k">def</span><span class="w"> </span><span class="fm">__delitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">nodename</span><span class="p">):</span>
<span class="w">        </span><span class="sd">&quot;&quot;&quot;Remove a node, given its name.&quot;&quot;&quot;</span>

        <span class="k">for</span> <span class="n">hash_</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">_repl_iterator</span><span class="p">(</span><span class="n">nodename</span><span class="p">):</span>
            <span class="c1"># will raise KeyError for nonexistent node name</span>
            <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">_nodes</span><span class="p">[</span><span class="n">hash_</span><span class="p">]</span>
            <span class="n">index</span> <span class="o">=</span> <span class="n">bisect</span><span class="o">.</span><span class="n">bisect_left</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_keys</span><span class="p">,</span> <span class="n">hash_</span><span class="p">)</span>
            <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">_keys</span><span class="p">[</span><span class="n">index</span><span class="p">]</span>

    <span class="k">def</span><span class="w"> </span><span class="fm">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
<span class="w">        </span><span class="sd">&quot;&quot;&quot;Return a node, given a key.</span>

<span class="sd">        The node replica with a hash value nearest</span>
<span class="sd">        but not less than that of the given</span>
<span class="sd">        name is returned.   If the hash of the</span>
<span class="sd">        given name is greater than the greatest</span>
<span class="sd">        hash, returns the lowest hashed node.</span>

<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">hash_</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_hash</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
        <span class="n">start</span> <span class="o">=</span> <span class="n">bisect</span><span class="o">.</span><span class="n">bisect</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_keys</span><span class="p">,</span> <span class="n">hash_</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">start</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_keys</span><span class="p">):</span>
            <span class="n">start</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_nodes</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">_keys</span><span class="p">[</span><span class="n">start</span><span class="p">]]</span>
</pre></div>



<p>The map is used as a dictionary of node names to whatever you want, such as here we use Redis clients:</p>


<div class="pygments_manni"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">redis</span>
<span class="n">cr</span> <span class="o">=</span> <span class="o">=</span> <span class="n">ConsistentHashRing</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>

<span class="n">cr</span><span class="p">[</span><span class="s2">&quot;node1&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">redis</span><span class="o">.</span><span class="n">StrictRedis</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s2">&quot;host1&quot;</span><span class="p">)</span>
<span class="n">cr</span><span class="p">[</span><span class="s2">&quot;node2&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">redis</span><span class="o">.</span><span class="n">StrictRedis</span><span class="p">(</span><span class="n">host</span><span class="o">=</span><span class="s2">&quot;host2&quot;</span><span class="p">)</span>

<span class="n">client</span> <span class="o">=</span> <span class="n">cr</span><span class="p">[</span><span class="s2">&quot;some key&quot;</span><span class="p">]</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">client</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;some key&quot;</span><span class="p">)</span>
</pre></div>



<p>I wanted to validate that the ring is in fact producing standard deviations like
those mentioned in the Java article, so this is tested like the following:</p>


<div class="pygments_manni"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">unittest</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">collections</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">random</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">math</span>

<span class="k">class</span><span class="w"> </span><span class="nc">ConsistentHashRingTest</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span><span class="w"> </span><span class="nf">test_get_distribution</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">ring</span> <span class="o">=</span> <span class="n">ConsistentHashRing</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>

        <span class="n">numnodes</span> <span class="o">=</span> <span class="mi">10</span>
        <span class="n">numhits</span> <span class="o">=</span> <span class="mi">1000</span>
        <span class="n">numvalues</span> <span class="o">=</span> <span class="mi">10000</span>

        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span> <span class="o">+</span> <span class="n">numnodes</span><span class="p">):</span>
            <span class="n">ring</span><span class="p">[</span><span class="s2">&quot;node</span><span class="si">%d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;node_value</span><span class="si">%d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">i</span>

        <span class="n">distributions</span> <span class="o">=</span> <span class="n">collections</span><span class="o">.</span><span class="n">defaultdict</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="n">numhits</span><span class="p">):</span>
            <span class="n">key</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">numvalues</span><span class="p">))</span>
            <span class="n">node</span> <span class="o">=</span> <span class="n">ring</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
            <span class="n">distributions</span><span class="p">[</span><span class="n">node</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>

        <span class="c1"># count of hits matches what is observed</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="nb">sum</span><span class="p">(</span><span class="n">distributions</span><span class="o">.</span><span class="n">values</span><span class="p">()),</span> <span class="n">numhits</span><span class="p">)</span>

        <span class="c1"># I&#39;ve observed standard deviation for 10 nodes + 100</span>
        <span class="c1"># replicas to be between 10 and 15.   Play around with</span>
        <span class="c1"># the number of nodes / replicas to see how different</span>
        <span class="c1"># tunings work out.</span>
        <span class="n">standard_dev</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_pop_std_dev</span><span class="p">(</span><span class="n">distributions</span><span class="o">.</span><span class="n">values</span><span class="p">())</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertLessEqual</span><span class="p">(</span><span class="n">standard_dev</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span>

        <span class="c1"># if the stddev is good, it&#39;s safe to assume</span>
        <span class="c1"># all nodes were used</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">distributions</span><span class="p">),</span> <span class="n">numnodes</span><span class="p">)</span>

        <span class="c1"># just to test getting keys, see that we got the values</span>
        <span class="c1"># back and not keys or indexes or whatever.</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEquals</span><span class="p">(</span>
                <span class="nb">set</span><span class="p">(</span><span class="n">distributions</span><span class="o">.</span><span class="n">keys</span><span class="p">()),</span>
                <span class="nb">set</span><span class="p">(</span><span class="s2">&quot;node_value</span><span class="si">%d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span> <span class="o">+</span> <span class="n">numnodes</span><span class="p">))</span>
            <span class="p">)</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">_pop_std_dev</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">population</span><span class="p">):</span>
        <span class="n">mean</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">population</span><span class="p">)</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">population</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span>
                <span class="nb">sum</span><span class="p">(</span><span class="nb">pow</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="n">mean</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="n">population</span><span class="p">)</span>
                <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">population</span><span class="p">)</span>
            <span class="p">)</span>
</pre></div>



</div>
]]></content:encoded>
    </item>
    <item>
      <title>Server Side Templates and API Centric Development</title>
      <link>http://techspot.zzzeek.org/2012/06/18/server-side-templates-and-api-centric-development</link>
      <pubDate>Mon, 18 Jun 2012 12:01:00 EDT</pubDate>
      <category><![CDATA[Mako]]></category>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2012/06/18/server-side-templates-and-api-centric-development</guid>
      <description>Server Side Templates and API Centric Development</description>
      <content:encoded><![CDATA[<div class="document">
<p>We're here to talk about the rise of the API-focused application, and how it
interacts with templates for rendering HTML for web browsers.   The simple point I hope
to make is: you don't necessarily need to use all client side templates in order
to write an effective API-centric web application.</p>
<p>I'll do this by illustrating a simple web application, with a single
API-oriented method (that is, returns
JSON-oriented data), where the way it's rendered and the style of template
in use is entirely a matter of declarative configuration.  Rendering of
full pages as well as Ajax delivered &quot;fragments&quot; are covered using both
server- and client-side rendering approaches.</p>
<div class="section" id="api-centric-development">
<h1>API Centric Development</h1>
<p>Most dynamic web applications we write today have the requirement that they
provide APIs - that is, methods which return pure data for the consumption by
a wide variety of clients.   The trend here is towards organizing web applications
from the start to act like APIs.   In a nutshell, it means we are moving
away from mode of data models injected into templates:</p>


<div class="pygments_manni"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">get_balance</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">balance</span> <span class="o">=</span> <span class="n">BankBalance</span><span class="p">(</span>
        <span class="n">amount</span> <span class="o">=</span> <span class="n">Amount</span><span class="p">(</span><span class="mi">10000</span><span class="p">,</span> <span class="n">currency</span><span class="o">=</span><span class="s2">&quot;euro&quot;</span><span class="p">),</span>
        <span class="n">as_of_date</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mi">2012</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="p">)</span>
    <span class="k">return</span> <span class="n">render_template</span><span class="p">(</span><span class="s2">&quot;balance.html&quot;</span><span class="p">,</span> <span class="n">balance</span><span class="o">=</span><span class="n">balance</span><span class="p">)</span>
</pre></div>



<p>and instead towards returning JSON-compatible data structures, with
the &quot;view&quot; being decided somewhere else:</p>


<div class="pygments_manni"><pre><span></span><span class="nd">@view_config</span><span class="p">(</span><span class="s1">&#39;balance&#39;</span><span class="p">,</span> <span class="n">renderer</span><span class="o">=</span><span class="s1">&#39;json&#39;</span><span class="p">)</span>
<span class="k">def</span><span class="w"> </span><span class="nf">balance</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">{</span>
        <span class="s1">&#39;amount&#39;</span><span class="p">:</span><span class="mi">10000</span><span class="p">,</span>
        <span class="s1">&#39;currency&#39;</span><span class="p">:</span><span class="s1">&#39;euro&#39;</span><span class="p">,</span>
        <span class="s1">&#39;as_of_date&#39;</span><span class="p">:</span><span class="s1">&#39;2012-06-14 14:12:00&#39;</span>
    <span class="p">}</span>
</pre></div>



<p>This is a fine trend, allowing us to make a clearer line between server side concepts
and rendering concepts, and giving us an API-centric view of our data from day one.</p>
</div>
<div class="section" id="templates">
<h1>Templates</h1>
<p>There's a misunderstanding circulating about API-centric development which says that we have to
use client side templates:</p>
<blockquote>
API-centric development. If you take a client-side rendering approach, odds
are the server side of your web application is going to look more like an API
than it would if you were doing entirely server-side rendering. And if/when
you have plans to release an API, you'd probably already be 90% of the way
there. (<a class="reference external" href="http://openmymind.net/2012/5/30/Client-Side-vs-Server-Side-Rendering/#comment-544974348">http://openmymind.net/2012/5/30/Client-Side-vs-Server-Side-Rendering/#comment-544974348</a>)</blockquote>
<p>and:</p>
<blockquote>
Lastly, another issue i can see, assuming you develop using MVC. You need
to have the view, model and controller very tightly coupled to make his
way work. The controller needs to know how the view works to create html
that can slot right in. It's easier if the controller only has to pass
data, not layout information.
(<a class="reference external" href="http://www.reddit.com/r/programming/comments/ufyf3/clientside_vs_serverside_rendering/c4v5vjb">http://www.reddit.com/r/programming/comments/ufyf3/clientside_vs_serverside_rendering/c4v5vjb</a>)</blockquote>
<p>This second quote is specific to the approach of delivering rendered HTML
in an ajax response, to be directly rendered into a DOM element, which we will also demonstrate here.
How the &quot;model&quot; is more tightly coupled to anything when you have a
server side vs client side template, I have absolutely no idea.</p>
<p>Why might we want to stick with server side templates?   As a Python
developer, in my view the main
reason is that they are still a lot easier to develop with,
assuming we aren't developing our server in Javascript as well.
Consider if our bank account balance needed locale-specific
number, currency and date formatting, and also needed to convert the timestamp
from UTC into a preferred timezone.   A server side approach allows us to easily inject
more functionality into our template as part of its standard environment
for all render calls, such as something
like this:</p>


<div class="pygments_manni"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">render_template</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="n">template</span><span class="p">,</span> <span class="o">**</span><span class="n">template_ns</span><span class="p">):</span>
    <span class="n">number_formatter</span> <span class="o">=</span> <span class="n">number_formatter</span><span class="p">(</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">preferred_locale</span><span class="p">)</span>
    <span class="n">template_ns</span><span class="p">[</span><span class="s1">&#39;currency_format&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">currency_formatter</span><span class="p">(</span><span class="n">number_formatter</span><span class="p">)</span>
    <span class="n">template_ns</span><span class="p">[</span><span class="s1">&#39;date_format&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">date_formatter</span><span class="p">(</span>
                                <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">preferred_timezone</span><span class="p">,</span>
                                <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">preferred_date_format</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="n">template</span><span class="p">)</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="o">**</span><span class="n">template_ns</span><span class="p">)</span>
</pre></div>



<p>The template can, if it needs to, call upon these methods like this:</p>


<div class="pygments_manni"><pre><span></span><span class="x">&lt;ul&gt;</span>
<span class="x">    &lt;li&gt;Balance: </span><span class="cp">${</span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;amount&#39;</span><span class="p">]</span> <span class="o">|</span> <span class="n">currency_format</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;currency&#39;</span><span class="p">])</span><span class="cp">}</span><span class="x">&lt;/li&gt;</span>
<span class="x">    &lt;li&gt;As of: </span><span class="cp">${</span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;as_of_date&#39;</span><span class="p">]</span> <span class="o">|</span> <span class="n">date_format</span><span class="cp">}</span><span class="x">&lt;/li&gt;</span>
<span class="x">&lt;/ul&gt;</span>
</pre></div>



<p>With a client side template, we have to implement all of <tt class="docutils literal">currency_formatter</tt>,
<tt class="docutils literal">number_formatter</tt>, <tt class="docutils literal">date_formatter</tt> in Javascript.   These methods
may need to respond to business-specific inputs, such as specific user preferences
or other rules, that also need to be pushed up to the client.   All the additional Javascript
logic we're pushing out to the client brings forth the need for it to be unit
tested, which so far means we need to add significant complexity to the testing
environment by running
a Javascript engine like node.js or something else in order to test all this
functionality.   Remember, we're not already using node.js
to do the whole thing.  If we were, then yes everything is different, but I wasn't planning on abandoning
Python for web development just yet.</p>
<p>Some folks might argue that elements like date conversion and number formatting should
still remain on the server, but just be applied by the API to the data
being returned directly.  To me, this is specifically the worst thing you can
do - it basically means that the client side approach is forcing you to
move presentation-level concepts directly into your API's data format.
Almost immediately, you'll find yourself having to inject HTML entities for
currency symbols and other browser-specific markup into this data, at the very
least complicating your API with presentational concerns and in the worst case
pretty much ruining the purity of your API data.   While the examples here may
be a little contrived, you can be sure that more intricate cases come up
in practice that present an ongoing stream of hard decisions between complicating/polluting
server-generated API data with presentation concepts versus building a much heavier client
than initially seemed necessary.</p>
<p>Also, what about performance?  Don't client side/server side templates perform/scale/respond
worse/better?   My position here is &quot;if we're just starting out, then who knows, who cares&quot;.
If I've built an application
and I've observed that its responsiveness or scalability would benefit from some areas switching
to client side rendering, then that's an optimization that can be made later.
We've seen big sites like <a class="reference external" href="http://engineering.linkedin.com/frontend/leaving-jsps-dust-moving-linkedin-dustjs-client-side-templates">LinkedIn switch from server to client side rendering</a>,
and <a class="reference external" href="http://engineering.twitter.com/2012/05/improving-performance-on-twittercom.html">Twitter switch from client to server side rendering</a>,
both in the name of &quot;performance&quot;!
Who knows!  Overall, I don't think the difference between pushing out json strings versus HTML fragments
is something that warrants concern up front, until the application is more fully
formed and specific issues can addressed as needed.</p>
</div>
<div class="section" id="the-alternative">
<h1>The Alternative</h1>
<p>Implementing a larger client-side application than we might have originally
preferred is all doable of course, but given the additional steps of building
a bootstrap system for a pure client-side approach, reimplementing lots of
Python functionality, in some cases significant tasks such as timezone conversion,
into Javascript, and figuring out how to unit test it all, is a lot
of trouble for something that is pretty much effortless in a server side system -
must we go all client-side in order to be API centric?</p>
<p>Of course not!</p>
<p>The example I've produced illustrates a single, fake API method that produces a grid
of random integers:</p>


<div class="pygments_manni"><pre><span></span><span class="nd">@view_config</span><span class="p">(</span><span class="n">route_name</span><span class="o">=</span><span class="s1">&#39;api_ajax&#39;</span><span class="p">,</span> <span class="n">renderer</span><span class="o">=</span><span class="s1">&#39;json&#39;</span><span class="p">)</span>
<span class="k">def</span><span class="w"> </span><span class="nf">api</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">[</span>
        <span class="p">[</span><span class="s2">&quot;</span><span class="si">%0.2d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">99</span><span class="p">)</span>  <span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span>
        <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
    <span class="p">]</span>
</pre></div>



<p>and delivers it in four ways - two use server side rendering, two use client
side rendering.   Only <strong>one</strong> client template and <strong>one</strong> server side template
is used, and there is only <strong>one</strong> API call, which internally knows nothing
whatsoever about how it is displayed.  Basically, the design of our server component is un-impacted
by what style of rendering we use, save for different routing declarations
which we'll see later.</p>
<p>For client side rendering of this data, we'll use a <a class="reference external" href="http://handlebarsjs.com/">handlebars.js</a>
template:</p>


<div class="pygments_manni"><pre><span></span><span class="p">&lt;</span><span class="nt">p</span><span class="p">&gt;</span>
    API data -
    {{#if is_page}}
        Displayed via server-initiated, client-rendered page
    {{/if}}
    {{#unless is_page}}
        Displayed via client-initiated, client-rendered page
    {{/unless}}
<span class="p">&lt;/</span><span class="nt">p</span><span class="p">&gt;</span>

<span class="p">&lt;</span><span class="nt">table</span><span class="p">&gt;</span>
    {{#each data}}
        <span class="p">&lt;</span><span class="nt">tr</span><span class="p">&gt;</span>
            {{#each this}}
                <span class="p">&lt;</span><span class="nt">td</span><span class="p">&gt;</span>{{this}}<span class="p">&lt;/</span><span class="nt">td</span><span class="p">&gt;</span>
            {{/each}}
        <span class="p">&lt;/</span><span class="nt">tr</span><span class="p">&gt;</span>
    {{/each}}
<span class="p">&lt;/</span><span class="nt">table</span><span class="p">&gt;</span>
</pre></div>



<p>and for server side rendering, we'll use a <a class="reference external" href="http://www.makotemplates.org">Mako</a> template:</p>


<div class="pygments_manni"><pre><span></span><span class="cp">&lt;%</span><span class="nb">inherit</span> <span class="na">file=</span><span class="s">&quot;layout.mako&quot;</span><span class="cp">/&gt;</span>

<span class="cp">${</span><span class="n">display_api</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span><span class="cp">}</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;display_api(inline=False)&quot;</span><span class="cp">&gt;</span>
<span class="x">    &lt;p&gt;</span>
<span class="x">        API data -</span>
<span class="w">        </span><span class="cp">%</span> <span class="k">if</span> <span class="n">inline</span><span class="p">:</span>
<span class="x">            Displayed inline within a server-rendered page</span>
<span class="w">        </span><span class="cp">%</span> <span class="k">else</span><span class="p">:</span>
<span class="x">            Displayed via server-rendered ajax call</span>
<span class="w">        </span><span class="cp">%</span><span class="k"> endif</span>
<span class="x">    &lt;/p&gt;</span>
<span class="x">    &lt;table&gt;</span>
<span class="w">        </span><span class="cp">%</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">data</span><span class="p">:</span>
<span class="x">            &lt;tr&gt;</span>
<span class="w">                </span><span class="cp">%</span> <span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="n">row</span><span class="p">:</span>
<span class="x">                    &lt;td&gt;</span><span class="cp">${</span><span class="n">col</span><span class="cp">}</span><span class="x">&lt;/td&gt;</span>
<span class="w">                </span><span class="cp">%</span><span class="k"> endfor</span>
<span class="x">            &lt;/tr&gt;</span>
<span class="w">        </span><span class="cp">%</span><span class="k"> endfor</span>
<span class="x">    &lt;/table&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>



<p>The Mako template is using a <tt class="docutils literal">&lt;%def&gt;</tt> to provide indirection between the rendering
of the full page, and the rendering of the API data.  This is not a requirement,
but is here because we'll be illustrating also
how to dual purpose a single Mako template such that part of it can be used for a traditional
full page render as well as for an ajax-delivered HTML fragment, with no duplication.  It's
essentially a Pyramid port of the same technique I illustrated with Pylons four years ago
in my post <a class="reference external" href="/2008/09/01/ajax-the-mako-way/">Ajax the Mako Way</a>, which appears to
be somewhat forgotten.  Among other things, Pyramid's Mako renderer does not appear integrate
the capability to call upon page defs directly, even though
I had successfully lobbied to get the critical <tt class="docutils literal">render_def()</tt> into its predecessor
Pylons.  Here, I've implemented my own Mako renderer for Pyramid.</p>
<p>Key here is that we are separating the concept
of how the API interface is constructed, versus what the server actually produces.
Above, note we're using the Pyramid &quot;json&quot; renderer for our API data.
Note the term &quot;renderer&quot;.   Interpreting our API method as a JSON API,
as a call to a specific client-side template plus JSON API, or as a server
side render or ajax call is just a matter of declaration.   The way we
organize our application in an API-centric fashion has <em>nothing to do</em>
with where the rendering takes place.   To illustrate four different ways
of interpreting the same API method, we just need to add four different
<tt class="docutils literal">&#64;view_config</tt> directives:</p>


<div class="pygments_manni"><pre><span></span><span class="nd">@view_config</span><span class="p">(</span><span class="n">route_name</span><span class="o">=</span><span class="s1">&#39;server_navigate&#39;</span><span class="p">,</span> <span class="n">renderer</span><span class="o">=</span><span class="s1">&#39;home.mako&#39;</span><span class="p">)</span>
<span class="nd">@view_config</span><span class="p">(</span><span class="n">route_name</span><span class="o">=</span><span class="s1">&#39;server_ajax&#39;</span><span class="p">,</span> <span class="n">renderer</span><span class="o">=</span><span class="s1">&#39;home|display_api.mako&#39;</span><span class="p">)</span>
<span class="nd">@view_config</span><span class="p">(</span><span class="n">route_name</span><span class="o">=</span><span class="s1">&#39;client_navigate&#39;</span><span class="p">,</span> <span class="n">renderer</span><span class="o">=</span><span class="s1">&#39;display_api.handlebars&#39;</span><span class="p">)</span>
<span class="nd">@view_config</span><span class="p">(</span><span class="n">route_name</span><span class="o">=</span><span class="s1">&#39;api_ajax&#39;</span><span class="p">,</span> <span class="n">renderer</span><span class="o">=</span><span class="s1">&#39;json&#39;</span><span class="p">)</span>
<span class="k">def</span><span class="w"> </span><span class="nf">api</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">[</span>
        <span class="p">[</span><span class="s2">&quot;</span><span class="si">%0.2d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">99</span><span class="p">)</span>  <span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span>
        <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
    <span class="p">]</span>
</pre></div>



<p>The rendering methods here are as follows:</p>
<ul class="simple">
<li><strong>Method One, Server Via Server</strong> - The <tt class="docutils literal">api()</tt> view method returns the data, which
is received by the <tt class="docutils literal">home.mako</tt> template, which renders the full page,
and passes the data to the <tt class="docutils literal">display_api()</tt> def within the same
phase for all-at-once server side rendering.</li>
<li><strong>Method Two, Server Via Client</strong> - A hyperlink on the page initiates
an ajax call to the server's <tt class="docutils literal">server_ajax</tt> route, which invokes the
<tt class="docutils literal">api()</tt> view method, and returns the data directly to the <tt class="docutils literal">display_api</tt>
def present in the <tt class="docutils literal">home.mako</tt> template.   For this case, I had to
create my own Pyramid Mako renderer that receives a custom syntax,
where the page name and def name are separated by a pipe character.</li>
<li><strong>Method Three, Client Via Server</strong> - Intrinsic to any client side rendered
approach is that the server needs to first deliver some kind of HTML layout,
as nothing more than a launching point for all the requisite javascript
needed to start rendering the page for real.  This method illustrates that,
by delivering the <tt class="docutils literal">handlebars_base.mako</tt> template which serves as the
bootstrap point for any server-initiated page call that renders with
a client side template.   In this mode, it also embeds the data
returned by <tt class="docutils literal">api()</tt> within the &lt;script&gt; tags at the top of the page,
and then invokes the Javascript application to render the
<tt class="docutils literal">display_api.handlebars</tt> template, providing it with the embedded data.
Another approach here might be to deliver the template in one call, and
to have the client invoke the <tt class="docutils literal">api()</tt> method as a separate ajax call,
though this takes two requests instead of one and also implies adding
another server-side view method.</li>
<li><strong>Method Four, Client Via Client</strong> - A hyperlink on the page illustrates
how a client-rendered application can navigate to a certain view,
calling upon the server only for raw data (and possibly the client
side template itself, until its cached in a client-side collection).
The link includes
additional attributes which allow the javascript application to call
upon the <tt class="docutils literal">display_api.handlebars</tt> template directly, and renders it
along with the data returned by calling the <tt class="docutils literal">api()</tt> view method
with the <tt class="docutils literal">json</tt> renderer.</li>
</ul>
<p>Credit goes to Chris Rossi for coming up with the original client-side
rendering techniques that I've adapted here.</p>
<p>A screen shot of what we're looking at is as follows:</p>
<div class="figure">
<img alt="Template Demo Screenshot" src="/files/2012/template_demo_screenshot.png" />
</div>
<p>The demonstration here is hopefully useful not just to illustrate the server
techniques I'm talking about, but also as a way to play around with client
side rendering as well, including mixing and matching both server and client
side rendering together.   The hybrid approach is where I predict most
applications will be headed.</p>
<p>You can pull out the demo using git at <a class="reference external" href="https://bitbucket.org/zzzeek/client_template_demo">https://bitbucket.org/zzzeek/client_template_demo</a>.
Enjoy !</p>
</div>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Using Beaker for Caching?  Why You'll Want to Switch to dogpile.cache</title>
      <link>http://techspot.zzzeek.org/2012/04/19/using-beaker-for-caching-why-you-ll-want-to-switch-to-dogpile.cache</link>
      <pubDate>Thu, 19 Apr 2012 12:01:00 EDT</pubDate>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2012/04/19/using-beaker-for-caching-why-you-ll-want-to-switch-to-dogpile.cache</guid>
      <description>Using Beaker for Caching?  Why You'll Want to Switch to dogpile.cache</description>
      <content:encoded><![CDATA[<div class="document">
<p>Continuing on where I left off regarding Beaker in October (see <a class="reference external" href="/2011/10/01/thoughts-on-beaker/">Thoughts on Beaker</a>),
my new replacement for Beaker caching, <a class="reference external" href="https://bitbucket.org/zzzeek/dogpile.cache">dogpile.cache</a>, has had a bunch of
early releases.   While I'm still considering it &quot;alpha&quot; until I know a few people have taken it around the block,
it should be pretty much set for early testing and hopefully can be tagged as production quality in the near future.</p>
<p>The core of Beaker's caching mechanism is based on code I first wrote in 2005.   It was adapted from what was
basically my first Python program ever, a web template engine called Myghty, which in turn was based on
a Perl system called HTML::Mason.   The caching scenarios Beaker was designed for were primarily that of storing
data in files, such as DBM files.   A key assumption made at that time was that the backends would all provide
some system of returning a flag whether or not a key was present, which would precede the actual fetch of
the value from the cache.  Another assumption made was that the actual lock applied to these backends
to deal with the dogpile situation would be at its most &quot;distributed&quot; scope a file-based lock, using <tt class="docutils literal">flock()</tt>.</p>
<p>When memcached support was added to Beaker, these assumptions proved to be architectural shortcomings.
There is no &quot;check for a key&quot; function in memcached; there's only <tt class="docutils literal">get()</tt>.  Beaker's dogpile lock
calls &quot;check for a key&quot; twice.  As a result, Beaker
will in general pull a value out of memcached <strong>three times</strong>, each time resulting in an &quot;unpickle&quot; of a pickled
object.   The upshot of this is that <strong>Beaker pulls over the network and unpickles your object
three times times on every cache hit</strong>.
Users of Beaker are also well familiar with the awkward lock files Beaker insists on
generating, even though there are more appropriate ways to lock for distributed caches.</p>
<p>So for no other reason than these, dogpile.cache's entirely new and extremely simplified architecture
is an improvement of vast proportions.    The test program below illustrates the improvement in
unpickling behavior, as well as dogpile.cache's simplified API:</p>


<div class="pygments_manni"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">Widget</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;Sample object to be cached.</span>

<span class="sd">    Counts pickles and unpickles.</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">pickles</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">unpickles</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="k">def</span><span class="w"> </span><span class="fm">__init__</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="bp">self</span><span class="o">.</span><span class="n">id</span> <span class="o">=</span> <span class="nb">id</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">__getstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">Widget</span><span class="o">.</span><span class="n">pickles</span> <span class="o">+=</span><span class="mi">1</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span>

    <span class="k">def</span><span class="w"> </span><span class="nf">__setstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">state</span><span class="p">):</span>
        <span class="n">Widget</span><span class="o">.</span><span class="n">unpickles</span> <span class="o">+=</span><span class="mi">1</span>
        <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">state</span><span class="p">)</span>

<span class="k">def</span><span class="w"> </span><span class="nf">test_beaker</span><span class="p">():</span>
    <span class="kn">from</span><span class="w"> </span><span class="nn">beaker</span><span class="w"> </span><span class="kn">import</span> <span class="n">cache</span>

    <span class="n">cache_manager</span> <span class="o">=</span> <span class="n">cache</span><span class="o">.</span><span class="n">CacheManager</span><span class="p">(</span><span class="n">cache_regions</span><span class="o">=</span><span class="p">{</span>
    <span class="s1">&#39;default&#39;</span> <span class="p">:{</span>
            <span class="s1">&#39;type&#39;</span><span class="p">:</span><span class="s1">&#39;memcached&#39;</span><span class="p">,</span>
            <span class="s1">&#39;url&#39;</span><span class="p">:</span><span class="s1">&#39;127.0.0.1:11211&#39;</span><span class="p">,</span>
            <span class="s1">&#39;expiretime&#39;</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span>
            <span class="s1">&#39;lock_dir&#39;</span><span class="p">:</span><span class="s1">&#39;.&#39;</span><span class="p">,</span>
            <span class="s1">&#39;key_length&#39;</span><span class="p">:</span><span class="mi">250</span>
        <span class="p">}</span>
    <span class="p">})</span>

    <span class="nd">@cache_manager</span><span class="o">.</span><span class="n">region</span><span class="p">(</span><span class="s2">&quot;default&quot;</span><span class="p">,</span> <span class="s2">&quot;some_key&quot;</span><span class="p">)</span>
    <span class="k">def</span><span class="w"> </span><span class="nf">get_widget_beaker</span><span class="p">(</span><span class="nb">id</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">Widget</span><span class="p">(</span><span class="nb">id</span><span class="p">)</span>

    <span class="n">_run_test</span><span class="p">(</span><span class="n">get_widget_beaker</span><span class="p">)</span>

<span class="k">def</span><span class="w"> </span><span class="nf">test_dogpile</span><span class="p">():</span>
    <span class="kn">from</span><span class="w"> </span><span class="nn">dogpile.cache</span><span class="w"> </span><span class="kn">import</span> <span class="n">make_region</span>
    <span class="kn">from</span><span class="w"> </span><span class="nn">dogpile.cache.util</span><span class="w"> </span><span class="kn">import</span> <span class="n">sha1_mangle_key</span>

    <span class="n">region</span> <span class="o">=</span> <span class="n">make_region</span><span class="p">(</span><span class="n">key_mangler</span><span class="o">=</span><span class="n">sha1_mangle_key</span><span class="p">)</span><span class="o">.</span><span class="n">configure</span><span class="p">(</span>
        <span class="s1">&#39;dogpile.cache.memcached&#39;</span><span class="p">,</span>
        <span class="n">expiration_time</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
        <span class="n">arguments</span> <span class="o">=</span> <span class="p">{</span>
            <span class="s1">&#39;url&#39;</span><span class="p">:[</span><span class="s2">&quot;127.0.0.1:11211&quot;</span><span class="p">],</span>
        <span class="p">},</span>
    <span class="p">)</span>

    <span class="nd">@region</span><span class="o">.</span><span class="n">cache_on_arguments</span><span class="p">()</span>
    <span class="k">def</span><span class="w"> </span><span class="nf">get_widget_dogpile</span><span class="p">(</span><span class="nb">id</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">Widget</span><span class="p">(</span><span class="nb">id</span><span class="p">)</span>

    <span class="n">_run_test</span><span class="p">(</span><span class="n">get_widget_dogpile</span><span class="p">)</span>

<span class="k">def</span><span class="w"> </span><span class="nf">_run_test</span><span class="p">(</span><span class="n">get_widget</span><span class="p">):</span>
<span class="w">    </span><span class="sd">&quot;&quot;&quot;Store an object, retrieve from the cache.</span>

<span class="sd">    Wait two seconds, then exercise a regeneration.</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="kn">import</span><span class="w"> </span><span class="nn">time</span>

    <span class="n">Widget</span><span class="o">.</span><span class="n">pickles</span> <span class="o">=</span> <span class="n">Widget</span><span class="o">.</span><span class="n">unpickles</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="c1"># create and cache a widget.</span>
    <span class="c1"># no unpickle necessary.</span>
    <span class="n">w1</span> <span class="o">=</span> <span class="n">get_widget</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

    <span class="c1"># get it again.  one pull from cache</span>
    <span class="c1"># equals one unpickle needed.</span>
    <span class="n">w1</span> <span class="o">=</span> <span class="n">get_widget</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

    <span class="c1"># get from cache, will pull out the</span>
    <span class="c1"># object but also the fact that it&#39;s</span>
    <span class="c1"># expired (costs one unpickle).</span>
    <span class="c1"># newly generated object</span>
    <span class="c1"># cached and returned.</span>
    <span class="n">w1</span> <span class="o">=</span> <span class="n">get_widget</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

    <span class="nb">print</span> <span class="s2">&quot;Total pickles:&quot;</span><span class="p">,</span> <span class="n">Widget</span><span class="o">.</span><span class="n">pickles</span>
    <span class="nb">print</span> <span class="s2">&quot;Total unpickles:&quot;</span><span class="p">,</span> <span class="n">Widget</span><span class="o">.</span><span class="n">unpickles</span>

<span class="nb">print</span> <span class="s2">&quot;beaker&quot;</span>
<span class="n">test_beaker</span><span class="p">()</span>

<span class="nb">print</span> <span class="s2">&quot;dogpile&quot;</span>
<span class="n">test_dogpile</span><span class="p">()</span>
</pre></div>



<p>Running this with a clean memcached you get:</p>


<div class="pygments_manni"><pre><span></span>beaker
Total pickles: 2
Total unpickles: 6
dogpile
Total pickles: 2
Total unpickles: 2
</pre></div>



<p>Run it a second time, so that the <tt class="docutils literal">Widget</tt> is already in the cache.  Now you get <strong>ten</strong> unpickles with Beaker compared to dogpile.cache's three:</p>


<div class="pygments_manni"><pre><span></span>beaker
Total pickles: 2
Total unpickles: 10
dogpile
Total pickles: 2
Total unpickles: 3
</pre></div>



<p>The advantages of dogpile.cache go way beyond that:</p>
<ul class="simple">
<li>dogpile.cache includes distinct memcached backends for <tt class="docutils literal">pylibmc</tt>,
<tt class="docutils literal">memcache</tt> and <tt class="docutils literal">bmemcached</tt>.  These are all explicitly available
via different backend names, in contrast to Beaker's approach of deciding
for you which memcached backend it wants to use.</li>
<li>A dedicated API-space for backend-specific arguments, such as all the special
arguments <tt class="docutils literal">pylibmc</tt> offers.</li>
<li>A Redis backend is provided.</li>
<li>The system of &quot;dogpile locking&quot; is completely modular, and in the case
of memcached and Redis, a &quot;distributed lock&quot; option is provided which will
use the &quot;set key if not exists&quot; feature of those backends to provide
the dogpile lock.   A plain threaded mutex can be specified also.</li>
<li>Cache regions and function decorators are open ended.  You can
plug in your own system of generating cache keys from decorated functions,
as well as what kind of &quot;key mangling&quot; you'd like to apply to keys
going into the cache (such as encoding, hashing, etc.)</li>
<li>No lockfiles whatsoever unless you use the provided DBM backend; and
there, you tell it exactly where to put the lockfile, or tell it
to use a regular mutex instead.</li>
<li>New backends are ridiculously simple to write, and can be popped in
using regular setuptools entry points or in-application using
the <a class="reference external" href="http://dogpilecache.readthedocs.org/en/latest/usage.html#creating-backends">register_backend()</a>
function.</li>
<li>Vastly simplified scope - there's no dilution of the task at hand
with session, cookie, or encryption features.</li>
<li>Python 3 compatible in-place with no 2to3 step needed.</li>
</ul>
<p>So I'm hoping we can all soon get modernized onto dogpile.cache.</p>
<p><a class="reference external" href="http://dogpilecache.readthedocs.org/">dogpile.cache documentation</a>.</p>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Pycon 2012 : Hand Coded Applications with SQLAlchemy</title>
      <link>http://techspot.zzzeek.org/2012/03/12/pycon-2012-hand-coded-applications-with-sqlalchemy</link>
      <pubDate>Mon, 12 Mar 2012 12:01:00 EDT</pubDate>
      <category><![CDATA[Talks]]></category>
      <category><![CDATA[SQLAlchemy]]></category>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2012/03/12/pycon-2012-hand-coded-applications-with-sqlalchemy</guid>
      <description>Pycon 2012 : Hand Coded Applications with SQLAlchemy</description>
      <content:encoded><![CDATA[<div class="document">
<p>Here's the <a class="reference external" href="/files/2012/hand_coded_with_sqla.key.pdf">slides</a> from my Pycon
2012 talk, &quot;Hand Coded Applications with SQLAlchemy&quot;. I had a great time with
this talk and thanks all for coming !</p>
<p><strong>Update:</strong>  Here's <a class="reference external" href="http://www.youtube.com/watch?v=E09qigk_hnY">the video!</a></p>
</div>
]]></content:encoded>
    </item>
    <item>
      <title>Patterns Implemented by SQLAlchemy</title>
      <link>http://techspot.zzzeek.org/2012/02/07/patterns-implemented-by-sqlalchemy</link>
      <pubDate>Tue, 07 Feb 2012 12:01:00 EST</pubDate>
      <category><![CDATA[SQLAlchemy]]></category>
      <category><![CDATA[Code]]></category>
      <guid isPermaLink="true">http://techspot.zzzeek.org/2012/02/07/patterns-implemented-by-sqlalchemy</guid>
      <description>Patterns Implemented by SQLAlchemy</description>
      <content:encoded><![CDATA[<div class="document">
<p>When I first created SQLAlchemy, I knew I wanted to create something
significant. It was by no means the first ORM or database abstraction layer
I'd written; by 2005, I'd probably written about a dozen abstraction layers in
several languages, including in Java, Perl, C and C++ (really bad C and even
worse C++, one that talked to ODBC and another that communicated with
Microsoft's ancient <a class="reference external" href="http://msdn.microsoft.com/en-us/library/aa936939">DB-LIB</a> directly). All of these
abstraction layers were in the range of awful to mediocre, and certainly none
were anywhere near release-quality; even by late-90's to early-2000's standards.
They were all created for closed-source applications written on the job, but
each one did its job very well.</p>
<p>It was the repetitive creation of the same patterns over and over again that
made apparent the kinds of things a real toolkit should have, as well as
increased the urge to actually go through with it, so that I wouldn't have to
invent new database interaction layers for every new project, or worse, be
compelled by management to use whatever mediocre product they had read about
the week before (keeping in mind I was made to use such disasters as
<a class="reference external" href="http://en.wikipedia.org/wiki/Enterprise_JavaBeans#EJB_1.0_.281998-03-24.29">EJB 1.0</a>).
But at the same time it was apparent to me that I was going
to need to do some research up front as well. The primary book I used for this
research was <a class="reference external" href="http://www.martinfowler.com/books.html#eaa">Patterns of Enterprise Archictecture</a> by Martin Fowler. When reading
this book, about half the patterns were ones that I'd already used implicitly,
and the other half were ones that I was previously not entirely aware of.</p>
<p>Sometimes I read comments from new users expressing confusion or frustration
with SQLAlchemy's concepts. Maybe some of these users
are not only new to SQLAlchemy but are new to database abstraction layers in
general, and some maybe even to relational databases themselves. What I'd like to
lay out here is just how many of POEAA's patterns SQLAlchemy is built upon. If
you're new to SQLAlchemy, my hope is that this list might help to de-mystify
where these patterns come from.</p>
<p>These links are from <a class="reference external" href="http://martinfowler.com/eaaCatalog/">Catalog of Patterns of Enterprise Architecture</a>.</p>
<ul class="simple">
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/dataMapper.html">Data Mapper</a> - The
key to this pattern is that object-relational mapping is applied to a
user-defined class in a transparent way, keeping the details of persistence
separate from the public interface of the class. SQLAlchemy's classical
mapping system, which is the usage of the <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/mapper_config.html#sqlalchemy.orm.mapper">mapper()</a>
function to link a class with table metadata, implemented this pattern as
fully as possible. In modern SQLAlchemy, we use the <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative.html">Declarative</a>
pattern which combines table metadata with the class' declaration as a
shortcut to using <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/mapper_config.html#sqlalchemy.orm.mapper">mapper()</a>,
but the persistence API remains separate.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/unitOfWork.html">Unit of Work</a> - This
pattern is where the system transparently keeps track of changes to objects
and periodically flushes all those pending changes out to the database.
SQLAlchemy's <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/session.html">Session</a> implements this
pattern fully in a manner similar to that of Hibernate.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/identityMap.html">Identity Map</a> - This
is an essential pattern that establishes unique identities for each object
within a particular session, based on database identity. No ORM should be
without this feature, as working with object structures and applications of
the most moderate complexity is vastly simplified and made more efficient with this
pattern in place.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/metadataMapping.html">Metadata Mapping</a> - this chapter
in the book is where the name <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/core/schema.html">MetaData</a> comes from.   The exact
correspondence to Fowler's pattern would be the combination of <tt class="docutils literal">mapper()</tt>
and <tt class="docutils literal">Table</tt>.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/queryObject.html">Query Object</a> - Both
the ORM <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/query.html">Query</a> and
the Core <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/core/tutorial.html#selecting">select()</a>
construct are built on this pattern.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/repository.html">Repository</a> - An
interface that serves as the gateway to the database, in terms of
object-relational mappings. This is the SQLAlchemy <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/session.html">Session</a>.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/lazyLoad.html">Lazy Load</a> - Load a
related collection or object as you need it. SQLAlchemy, like Hibernate, has
<a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/loading.html">a lot of options</a>
in how attributes can load things.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/identityField.html">Identity Field</a> -
Represent the primary key of a table's row within the object that represents
it.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/foreignKeyMapping.html">Foreign Key Mapping</a> - Database
foreign keys are represented using <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/relationships.html">relationships</a> in the
object model.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/associationTableMapping.html">Association Table Mapping</a> - A
class can be mapped that represents information about how two objects are
related to each other. Use the <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/relationships.html#association-object">Association Object</a>
for this pattern.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/embeddedValue.html">Embedded Value</a> -
a value inline on an object represents multiple columns. SQLAlchemy provides
the <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/mapper_config.html#composite-column-types">Composite</a>
pattern here.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/serializedLOB.html">Serialized LOB</a> -
Sometimes you just want to stuff all the objects into a BLOB. Use the
<a class="reference external" href="http://docs.sqlalchemy.org/en/latest/core/types.html#sqlalchemy.types.PickleType">PickleType</a>
or roll a <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/core/types.html#marshal-json-strings">JSON type</a>.</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/inheritanceMappers.html">Inheritance Mappers</a> - Represent
class hierarchies within database tables. See <a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/inheritance.html">Inheritance Mapping</a>.<ul>
<li>Single Table Inheritance - <a class="reference external" href="http://martinfowler.com/eaaCatalog/singleTableInheritance.html">POEAA (1)</a> -
<a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#single-table-inheritance">SQLA (1)</a></li>
<li>Class Table Inheritance - <a class="reference external" href="http://martinfowler.com/eaaCatalog/classTableInheritance.html">POEAA (2)</a> -
<a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance">SQLA (2)</a></li>
<li>Concrete Table Inheritance - <a class="reference external" href="http://martinfowler.com/eaaCatalog/concreteTableInheritance.html">POEAA (3)</a> -
<a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#concrete-table-inheritance">SQLA (3)</a></li>
</ul>
</li>
<li><a class="reference external" href="http://martinfowler.com/eaaCatalog/optimisticOfflineLock.html">Optimistic Offline Lock</a> - Set up a
<a class="reference external" href="http://docs.sqlalchemy.org/en/latest/orm/mapper_config.html#sqlalchemy.orm.mapper">version id</a>
on your mapping to enable this feature in SQLAlchemy.</li>
</ul>
<p>Thanks for reading!</p>
</div>
]]></content:encoded>
    </item>
  </channel>
</rss>
