<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Daily Build &#187; python</title>
	<atom:link href="http://blog.bstpierre.org/category/python/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.bstpierre.org</link>
	<description>Software Development, version 3.0</description>
	<lastBuildDate>Fri, 03 Feb 2012 02:59:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>Preserve Your Sanity When Dealing with Unicode in Python</title>
		<link>http://blog.bstpierre.org/simple-python-unicode</link>
		<comments>http://blog.bstpierre.org/simple-python-unicode#comments</comments>
		<pubDate>Wed, 05 Oct 2011 16:09:13 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=341</guid>
		<description><![CDATA[I have not yet played with python 3, which sounds like it makes working with Unicode easier. In python 2.x, working with Unicode can be annoying, but when you remember this rule of thumb, it&#8217;s much easier and allows you to keep your sanity: Always use unicode strings internally. Decode whatever you read/receive. Encode whatever [...]]]></description>
			<content:encoded><![CDATA[<p>I have not yet played with python 3, which sounds like it makes working with Unicode easier.</p>
<p>In python 2.x, working with Unicode can be annoying, but when you remember this rule of thumb, it&#8217;s <em>much</em> easier and allows you to keep your sanity:</p>
<blockquote><p>Always use unicode strings internally. Decode whatever you read/receive. Encode whatever you write/send.</p></blockquote>
<p>I&#8217;ve recently done some work on a project to generate ReStructuredText (as an intermediate form on the way to generating HTML). The input data has Unicode sprinkled throughout (in UTF-8). I kept getting <code>UnicodeDecodeError: 'ascii' codec can't decode byte</code> exceptions in various places, until I applied that rule everywhere:</p>
<ul>
<li>When reading, decode from UTF-8.</li>
<li>Use Unicode strings <code>u'E.g. this formatted %s string' % (decoded_string1, decoded_string2)</code> internally &#8212; <em>everywhere</em>.</li>
<li>When writing, encode to UTF-8.</li>
</ul>
<p>Hat tip to <a href="http://stackoverflow.com/q/492483/67022#492711">nosklo on StackOverflow</a> for mentioning this simple rule.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/simple-python-unicode/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Use Linux to build win32 installers for Python apps</title>
		<link>http://blog.bstpierre.org/linux-win32-python-installer</link>
		<comments>http://blog.bstpierre.org/linux-win32-python-installer#comments</comments>
		<pubDate>Wed, 20 Jul 2011 15:00:36 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[howto]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=319</guid>
		<description><![CDATA[A python-based project I&#8217;m working on has a win32 user that I need to support. Until yesterday I&#8217;ve been moving to a win32 laptop in order to run python setup.py bdist_wininst so I can produce a self-installing executable. Then I discovered how trivial it is to use wine to do the job: Install wine. (sudo [...]]]></description>
			<content:encoded><![CDATA[<p>A python-based project I&#8217;m working on has a win32 user that I need to support. Until yesterday I&#8217;ve been moving to a win32 laptop in order to run <code>python setup.py bdist_wininst</code> so I can produce a self-installing executable. Then I discovered how trivial it is to use wine to do the job:</p>
<ol>
<li>Install wine. (<code>sudo aptitude install wine</code>)</li>
<li>Install python into the wine environment. (Download an msi from python.org and run <code>msiexec /i python-x.x.x.msi</code>.)</li>
<li>Install whatever prerequisite packages you need (e.g. wxPython) using <code>wine</code> or <code>msiexec</code>.</li>
<li>When you&#8217;ve got everything ready to build, just do <code>wine c:/Python27/python.exe setup.py bdist_wininst</code> and look in ./dist/ for your exe!</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/linux-win32-python-installer/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>3 Easy Ways to Stick to a Coding Standard</title>
		<link>http://blog.bstpierre.org/3-easy-ways-to-stick-to-a-coding-standard</link>
		<comments>http://blog.bstpierre.org/3-easy-ways-to-stick-to-a-coding-standard#comments</comments>
		<pubDate>Tue, 25 Aug 2009 18:40:58 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[codereview]]></category>
		<category><![CDATA[software-engineering]]></category>
		<category><![CDATA[tool]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=192</guid>
		<description><![CDATA[When you&#8217;re writing python, you don&#8217;t need a lot of debate over the minutiae of most coding standards. PEP 8 does that for you. Even better, there are some tools that make it really easy to stick to the standard. Why do this? Well, for one thing it makes code reviews easier when everyone follows [...]]]></description>
			<content:encoded><![CDATA[<p>When you&#8217;re writing python, you don&#8217;t need a lot of debate over the minutiae of most coding standards. <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> does that for you. Even better, there are some tools that make it really easy to stick to the standard.</p>
<p>Why do this? Well, for one thing it makes code reviews easier when everyone follows the same conventions. It also makes maintenance easier.</p>
<ol>
<li><a href="http://github.com/cburroughs/pep8.py/tree/master">pep8.py</a> is a style checker that enforces the rules of PEP 8. The &#8220;official home&#8221; (?) <a href="http://svn.browsershots.org/trunk/devtools/pep8/pep8.py">at browsershots.org </a>was dead as I was writing this. (Thanks GitHub!) Run pep8.py on your code and it will tell you where you&#8217;ve drifted from the standard.</li>
<li><a href="http://www.logilab.org/857">pylint</a> is lint for python. It provides more functionality than pep8.py, but is not a strict superset. (pep8.py is pickier about whitespace issues.) Pylint is also configurable to enforce various naming rules. Like most lints, the SNR is pretty low, but you can turn off most of the noise and get a reasonable signal for the things you want to check.</li>
<li>Subversion (as well as most other tools) can be configured to run a script every time you check in code. Run one or both of the above tools in the pre-commit hook and bad code will be rejected. (I&#8217;d be wary of doing this with pylint unless you&#8217;ve got the categories of &#8220;noisy&#8221; warnings turned off.) I don&#8217;t have anything cookbook for this yet, but I&#8217;m working on it&#8230;</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/3-easy-ways-to-stick-to-a-coding-standard/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Python&#8217;s ctypes to Call Into C Libraries</title>
		<link>http://blog.bstpierre.org/using-pythons-ctypes-to-make-system-calls</link>
		<comments>http://blog.bstpierre.org/using-pythons-ctypes-to-make-system-calls#comments</comments>
		<pubDate>Wed, 05 Aug 2009 10:35:55 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=185</guid>
		<description><![CDATA[The ctypes module makes loading and calling into a dynamic library incredibly easy.]]></description>
			<content:encoded><![CDATA[<p>The ctypes module makes loading and calling into a dynamic library incredibly easy:</p>
<pre>&gt;&gt;&gt; from ctypes import CDLL
&gt;&gt;&gt; libc = CDLL('libc.so.6')
&gt;&gt;&gt; print libc.strlen('abcde')
5</pre>
<p>As with everything else in python, it gets even better when you scratch the surface. In the example above, CDLL returns an object that represents the dynamic library. You can access the functions in that library by attribute access (&#8220;libc.strlen&#8221;) or item access (&#8220;libc['strlen']&#8220;). Both access mechanisms return a callable object.</p>
<p>This callable object has an &#8220;errcheck&#8221; attribute that can be assigned a callable. We can use this for error-checking our calls into the library. Let&#8217;s write a simple version of the &#8220;kill&#8221; command that uses the kill(2) system call.</p>
<pre>import sys
from ctypes import *

# Load the library.
libc = CDLL('libc.so.6')

# Our error checking function. This will receive the
# return value of the library function, the function that
# was called, and the arguments passed to the function as a
# tuple.
def kill_errcheck(retval, func, funcargs):
    '''Check for error -- retval == -1.'''
    if retval &lt; 0:
        raise Exception('kill%s failed' % (funcargs, ))
    return True

# Get the kill function from the standard library.
kill = libc.kill

# Set the error checker for kill().
kill.errcheck = kill_errcheck

# Pass the command line argument as a pid to kill, with
# SIGSEGV (11).
pid = int(sys.argv[1])
kill(pid, 11)</pre>
<p>Save this as kill.py. Then, in your shell, try something like this:</p>
<pre># Notice that the 3401 is the pid of the process
# we're putting into the background. Yours will
# be different.
bash$ sleep 120&amp;
[1] 3401
bash$ python kill.py 3401
[1]+ Segmentation Fault         sleep 120
bash$ python kill.py 3401
Traceback (most recent call last):
  File "kill.py", line 17, in
    kill(pid, 11)
  File "kill.py", line 10, in kill_errcheck
    raise Exception('kill%s failed' % (funcargs, ))
Exception: kill(3401, 11) failed</pre>
<p>At line 4 of the output we run sleep in the background. At line 5 we learn the pid of this process. At line 6 we run our kill program, giving it the pid we just spawned, and we see the notification from bash that the process was killed (with signal 11, segmentation fault). At line 8 we run our kill program again on pid 3401, but it doesn&#8217;t exist, the kill system call returns -1, and our error checker raises an exception when it detects the system call failure.</p>
<p>But wait, there&#8217;s more&#8230; I&#8217;m working on a follow up post that combines ctypes.Structure with calls into a linux system call.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/using-pythons-ctypes-to-make-system-calls/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Yet Another Python Enum Module</title>
		<link>http://blog.bstpierre.org/yet-another-python-enum-module</link>
		<comments>http://blog.bstpierre.org/yet-another-python-enum-module#comments</comments>
		<pubDate>Mon, 20 Jul 2009 02:21:36 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/yet-another-python-enum-module</guid>
		<description><![CDATA[I didn&#8217;t like the existing enum recipes, so I cooked up what I feel is a better way of working with enumerations in python. The result is yapyenum, hosted on github. Rather than come up with something new to say about it, I&#8217;ll just repost the README here: This module provides named enumerations for python. [...]]]></description>
			<content:encoded><![CDATA[<p>I didn&#8217;t like the existing enum recipes, so I cooked up what I feel is a better way of working with enumerations in python. The result is <a href="http://github.com/bstpierre/yapyenum/tree/master">yapyenum</a>, hosted on github. Rather than come up with something new to say about it, I&#8217;ll just repost the README here:</p>
<blockquote class="gmail_quote" style="border-left: 1px solid #cccccc; margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex; font-family: courier new,monospace;"><p>This module provides named enumerations for python.</p>
<p>Unlike other implementations that I have seen, this is *not* an anonymous enumeration. To use it derive from the Enumeration class provided in enum.py and list the names of the enum members in the class member _enum_.</p>
<p>The enum is itself a singleton class. It tries to be immutable via __slots__ and by refusing to allow its members to be changed.</p>
<p>Enum members are an integer subclass with a &#8220;name&#8221; property and that knows how to pretty print itself. The enum values are interchangeable with integers, which may or may not be what you want.</p>
<p>The class supports membership (&#8220;FOO in MyEnum&#8221;) and mapping a non-instance-member value to a name. (I.e. if FOO uses the integer value 1, then MyEnum.name(1) returns &#8220;FOO&#8221;.)</p>
<p>Tested on 2.4.6, 2.5.2, 2.6.2, on a combination of debian sarge, etch, lenny, and ubuntu 9.04.</p>
<p>There are obvious capabilities that could be added but this does all that I need so far. Patches will be happily accepted.</p>
<p>Permissive license (MIT). Have fun.</p></blockquote>
<p>For other enum recipes, see:</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0354/">PEP 354</a> (rejected enum proposal for python)</li>
<li>The <a href="http://pypi.python.org/pypi/enum/">enum</a> module in pypi</li>
<li>Recipe 413486: <a href="http://code.activestate.com/recipes/413486/">First Class Enums in Python</a></li>
<li>Recipe 305271: <a href="http://code.activestate.com/recipes/305271/">Enumerated values by name or number</a></li>
<li>Recipe 67107: <a href="http://code.activestate.com/recipes/67107/">Enums for Python</a></li>
<li>Recipe 81098: <a href="http://code.activestate.com/recipes/81098/">python enum with strings</a></li>
<li>At Stack Overflow: <a href="http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python">What’s the best way to implement an ‘enum’ in Python?</a></li>
<li>The Python Cookbook (at page 607 on <a href="http://books.google.com/books?id=Q0s6Vgb98CQC&amp;lpg=PA607&amp;ots=hc1236Snoz&amp;dq=python%20cookbook%20enum&amp;pg=PA607">Google Books</a>)</li>
</ul>
<p>Several of these recipes have comments along the lines of &#8220;if you&#8217;re using one of these too-fancy enum recipes in python, you&#8217;re doing something unpythonic&#8221;. This is likely true, but sometimes unavoidable for social, political, and/or historical reasons.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/yet-another-python-enum-module/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Python Exception Handling: Cleanup and Reraise</title>
		<link>http://blog.bstpierre.org/python-exception-handling-cleanup-and-reraise</link>
		<comments>http://blog.bstpierre.org/python-exception-handling-cleanup-and-reraise#comments</comments>
		<pubDate>Thu, 16 Jul 2009 03:35:49 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/python-exception-handling-cleanup-and-reraise</guid>
		<description><![CDATA[I&#8217;ve had this code around for a while and had an opportunity to drag it out the other day and dust it off. The problem: Every now and again there&#8217;s a situation where you don&#8217;t really want to catch an exception, but you do want to perform some cleanup and let the exception propagate up [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve had <a href="http://gist.github.com/148135">this code</a> around for a while and had an opportunity to drag it out the other day and dust it off. The problem: Every now and again there&#8217;s a situation where you don&#8217;t really want to catch an exception, but you do want to perform some cleanup and let the exception propagate up the stack. Sometimes there&#8217;s an extra wrinkle in that the cleanup code may itself throw an exception (that I&#8217;m simply going to assume we can ignore).</p>
<p><script src="http://gist.github.com/148135.js"></script></p>
<p>You can run the file to see the behavior. Simply provide an integer 1-5 as a command line argument and you&#8217;ll run the selected scenario and see the output. The goal in this case is for cleanup to occur and an exception to be reported as having occurred at line 10.</p>
<p>The code in reraiser1 is wrong because this behaves as if a brand new exception were thrown at line 27. That may not seem so bad, but this code is pretty simple. If this happens and the stack trace is deep, it will be almost impossible to diagnose what went wrong.</p>
<p>The code in reraiser2 shows what happens when a second exception occurs in the except block. A bare raise statement here might be an attempt to re-raise the original exception, but python&#8217;s rules about re-raising specify that the most recent exception in the scope is what is reraised. In this case, that&#8217;s the exception thrown from the cleanup function. Again, this makes troubleshooting difficult.</p>
<p>In reraiser3 I worked around the problem in reraiser2 by moving the cleanup function&#8217;s exception into a separate scope by defining a local cleanup function and calling it from within the except block. This prevents the cleanup function&#8217;s exception from polluting the scope with an irrelevant exception and we can re-raise the original exception. This results in a stack trace rooted at line 10.</p>
<p>Reraiser4 takes a different approach. Instead of moving the cleanup function&#8217;s exception into a separate scope, it captures the traceback information from the original exception and then passes it back to the raise statement so that the reported traceback is accurate.</p>
<p>The cleanest way to handle this is to use a finally block as shown in reraiser5. This situation is what &#8220;finally&#8221; is meant for: it does not trap the exception, it just gives you a chance to clean up before control moves back up the stack to the caller. The presence of finally clues readers in to the fact that you aren&#8217;t messing with the exception, and that the point of the block is to perform cleanup.</p>
<p>Kindly drop me a note if I&#8217;ve got something wrong above, or if I&#8217;m missing a technique (or a common anti-pattern!). Thanks.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/python-exception-handling-cleanup-and-reraise/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Five Days to a Django Web App: Day Three, Coding</title>
		<link>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-three-coding</link>
		<comments>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-three-coding#comments</comments>
		<pubDate>Wed, 11 Feb 2009 15:14:41 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[howto]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=141</guid>
		<description><![CDATA[Thanks for coming back for Day Three! [Note: Sorry this post is a day late. It was all ready to go late yesterday, but some of the code included below triggered a bug either in WordPress or ScribeFire and the whole post got mangled. I managed to resurrect it today from drafts, and I think [...]]]></description>
			<content:encoded><![CDATA[<p>Thanks for coming back for Day Three!</p>
<p>[Note: Sorry this post is a day late. It was all ready to go late yesterday, but some of the code included below triggered a bug either in WordPress or ScribeFire and the whole post got mangled. I managed to resurrect it today from drafts, and I think it's coherent, but if you find some problem with it please drop me a note.]</p>
<h2>Progress So Far</h2>
<p>Yesterday we <a href="../five-days-to-a-django-web-app-day-two-mockups">built some mockups</a>, just HTML and CSS — nothing active. Hopefully you’ve had a chance to run your mockups past a couple of people for feedback and ideas.</p>
<p>Armed with these mockups, we’re ready to get started coding. Today’s post is the longest in the series. Take it in chunks if you need to. (I didn’t write it all at once either.)</p>
<h2>Foundation</h2>
<h3>MySQL</h3>
<p>First, go to your web host’s control panel and create two MySQL databases for this project. I created &#8220;resumandb&#8221; and &#8220;test_resumandb&#8221;. This latter database is needed for running the built-in test system.</p>
<p>You’ll get an error/warning if the test database exists when you first run tests. However, the control panel needs to set user privileges and it seems like the only way it knows how to do this is by creating the database.</p>
<p>Set up the same databases on your local system:</p>
<pre><code>
bash$ mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1969
Server version: 5.0.32-Debian_7etch8-log Debian etch distribution

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql&gt; CREATE DATABASE resumandb;
Query OK, 1 row affected (0.00 sec)

mysql&gt; GRANT ALL ON resumandb.* TO 'resuman'@'localhost' identified
    by 'reallY_baD_9passworD!';
Query OK, 0 rows affected (0.11 sec)

mysql&gt; GRANT ALL ON test_resumandb.* TO 'resuman'@'localhost' identified
    by 'reallY_baD_9passworD!';
Query OK, 0 rows affected (0.0 sec)

</code></pre>
<p>Notice that you don&#8217;t need to create the test database. As mentioned above, this will happen when you run tests.</p>
<h3>Project Skeleton</h3>
<p>What follows is a bunch of steps: do-this, do-that. At the end of this section you should have a runnable (but empty) project that is ready to start hanging functionality onto.</p>
<p>Then generate a skeleton for your project: <code>django-admin.py  startproject YOURPROJECT</code>.</p>
<p>Then dive right in to settings.py and change a few things:</p>
<ul>
<li>Set the admin email to your email address.</li>
<li>Set the MySQL database according to your web host&#8217;s settings.</li>
<li>Timezone.</li>
<li>MEDIA_ROOT, MEDIA_URL and variants — see note below.</li>
<li>TEMPLATE_DIRS — see note below.</li>
</ul>
<p>To make it easier to use the same settings file to test both locally and on your host, I add the following to my settings.py to set MEDIA_ROOT and TEMPLATE_DIRS:</p>
<pre><code>
import os

def full_path_to(path):
    '''This makes this settings file relocatable.'''
    return os.path.join(os.getcwd(), path)

MEDIA_ROOT = full_path_to('static/')
TEMPLATE_DIRS = (
    full_path_to('templates')
)
</code></pre>
<p>Then you just have to make sure to cd to the directory where your settings.py lives whenever the app runs (more on this when we deploy to the host). I find this easier than monkeying with PYTHONPATH.</p>
<p>Similarly, the following will change your URLs based on whether you&#8217;re running locally or on the host. (Just make sure you test for a directory that only exists locally! My paths are a little different on the host.)</p>
<pre><code>
MEDIA_URL = 'http://media.resuman.com/resuman/static/'
if os.path.exists('/home/brian/projects/resuman'):
    MEDIA_URL = 'http://localhost/apache2-default/resuman-static/'

ADMIN_MEDIA_PREFIX = 'http://media.example.com/admin_media/'
if os.path.exists('/home/brian/projects/resuman'):
    ADMIN_MEDIA_PREFIX = 'http://localhost/apache2-default/resuman-admin/'
</code></pre>
<p>Now it&#8217;s time to generate the app: <code>./manage.py startapp YOURAPP</code>. Notice that the app name should be different from the project name (otherwise it gets too confusing later on).</p>
<p>Edit your YOURPROJECT/urls.py to include a reference to YOURAPP:</p>
<pre><code>
    (r'^funnel/$', include('resuman.jobfunnel.urls')),
</code></pre>
<p>Also uncomment the admin lines so you can use the built-in admin app.</p>
<p>Now it&#8217;s time to generate the app: <code>./manage.py startapp YOURAPP</code>.</p>
<p>Now edit YOURAPP/urls.py &#8212; paste in the needed bits from the existing urls.py, but drop the admin lines and the include().</p>
<p>In your settings file, add the admin and admindoc apps and &#8220;YOURPROJECT.YOURAPP&#8221; to INSTALLED_APPS.</p>
<p>Under the YOURPROJECT directory, create a templates directory and a static directory. Copy your HTML files from the mockup to the templates directory. Copy the CSS file to the static directory.</p>
<p>My system is configured by default to serve from /var/www/apache2-default/, and we specified above to fetch static files from http://localhost/resuman-static/, so we need to do the following to make this possible (substituting your paths, of course):</p>
<pre><code>
bash$ ln -s /home/brian/projects/resuman/static /var/www/apache2-default/resuman-static
bash$ ln -s /home/brian/projects/django/git/django/contrib/admin/media/ \
    /var/www/apache2-default/resuman-admin
</code></pre>
<p>Restart apache.</p>
<p>Change directory to YOURPROJECT and <code>./manage.py syncdb; ./manage.py runserver</code>.</p>
<p>Browse to <a href="http://127.0.0.1:8000/admin/">http://127.0.0.1:8000/admin/</a>. Log in, and you should see the admin app in all its glory. If the stylesheet didn&#8217;t load (ie. it looks really ugly), View Source on the page. At the top, find the URL to that ends something like &#8230;/resuman-admin/css/base.css. Copy-paste this into the address bar. It probably doesn&#8217;t load. Verify that it is the right URL — if not then change your settings.py to have the right URL base. If the URL is right, then you need to fix your symlink, server config, or permissions (I often get bit by having the wrong permissions).</p>
<h3>Adding Some Meat</h3>
<p>This wouldn&#8217;t be a bad time to push a snapshot into your version control system (e.g. <code>git init; git add .; git commit -m'YOURPROJECT skeleton done'</code>).</p>
<p>Now we&#8217;re finally ready to write the first view for this app. Edit YOURAPP/urls.py. Lay out the URL map that you want to use for your app. We&#8217;re on a tight five day schedule, so don&#8217;t go nuts! There&#8217;s only time to get a couple of pages done. Don&#8217;t worry, you can add more later. Here&#8217;s what mine looks like:</p>
<pre><code>
from django.conf.urls.defaults import *

urlpatterns = patterns(
    '',
    (r'^$', 'resuman.jobfunnel.views.dashboard'),
    (r'^add/$', 'resuman.jobfunnel.views.add_job'),
    (r'^edit/$', 'resuman.jobfunnel.views.edit_job'),
)
</code></pre>
<p>Remember that my toplevel urls.py includes this based on the <code>^funnel/$</code> pattern, so each of the patterns above will have …funnel/ as a prefix in the URL.</p>
<p>Now let’s write our first couple of tests. Edit YOURAPP/tests.py and add something similar to the code below. You’ll have to change URLs and logins. The class ViewTestCase is defined in viewtestcase.py, a convenience TestCase subclass I wrote for testing Django views. Copy that file into YOURAPPNAME directory.</p>
<pre><code>
from viewtestcase import ViewTestCase
class DashboardViewTestBase(ViewTestCase):
    # Override in subclass to use post/head/etc. Must match a
    # method defined in django.test.TestCase.
    TESTMETHOD = 'get'

    # Override.
    TESTURL = '/funnel/'
    TESTARGS = {}
    TEMPLATE = 'dashboard.html'

class DashboardViewLoginTest(DashboardViewTestBase):
    # We're expecting an error, so set TEMPLATE to None to avoid getting a bogus test failure.
    TEMPLATE = None

    def test_login_required(self):
        """
        Tests that a login is required to view the page.
        """
        self.expect_login_redirect()
        return

class DashboardViewTest(DashboardViewTestBase):
    # This uses TEMPLATE from the parent class.

    # Set username and password and the base class will automagically login the test client.
    USERNAME = 'brian'
    TESTLOGIN = (USERNAME, 'a')

    def test_logged_in_ok(self):
        pass
</code></pre>
<p>Now run the test: <code>./manage.py test</code>. You should see exactly two failures. If a bunch of stuff fails (like built-in django tests), fix whatever is wrong before continuing.</p>
<pre><code>
bash$ ./manage.py test
Creating test database...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table jobfunnel_job
Installing index for admin.LogEntry model
Installing index for auth.Permission model
Installing index for auth.Message model
Installing index for jobfunnel.Job model
Installing json fixture 'initial_data' from '/home/brian/projects/resuman/../resuman/jobfunnel/fixtures'.
Installed 1 object(s) from 1 fixture(s)
..........EE......
======================================================================
ERROR: test_login_required (resuman.jobfunnel.tests.DashboardViewLoginTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/brian/projects/resuman/../resuman/jobfunnel/viewtestcase.py", line 98, in setUp
    self.fetch_view(self.TESTMETHOD, self.TESTURL, self.TESTARGS)
  File "/home/brian/projects/resuman/../resuman/jobfunnel/viewtestcase.py", line 79, in fetch_view
    self.response = function(testurl, testargs, **extra)
  File "/usr/lib/python2.5/site-packages/django/test/client.py", line 277, in get
    return self.request(**r)
  File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 77, in get_response
    request.path_info)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 183, in resolve
    sub_match = pattern.resolve(new_path)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 183, in resolve
    sub_match = pattern.resolve(new_path)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 124, in resolve
    return self.callback, args, kwargs
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 136, in _get_callback
    raise ViewDoesNotExist, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))
ViewDoesNotExist: Tried dashboard in module resuman.jobfunnel.views. Error was: 'module' object has no attribute 'dashboard'

======================================================================
ERROR: test_logged_in_ok (resuman.jobfunnel.tests.DashboardViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/brian/projects/resuman/../resuman/jobfunnel/viewtestcase.py", line 98, in setUp
    self.fetch_view(self.TESTMETHOD, self.TESTURL, self.TESTARGS)
  File "/home/brian/projects/resuman/../resuman/jobfunnel/viewtestcase.py", line 79, in fetch_view
    self.response = function(testurl, testargs, **extra)
  File "/usr/lib/python2.5/site-packages/django/test/client.py", line 277, in get
    return self.request(**r)
  File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 77, in get_response
    request.path_info)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 183, in resolve
    sub_match = pattern.resolve(new_path)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 183, in resolve
    sub_match = pattern.resolve(new_path)
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 124, in resolve
    return self.callback, args, kwargs
  File "/usr/lib/python2.5/site-packages/django/core/urlresolvers.py", line 136, in _get_callback
    raise ViewDoesNotExist, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))
ViewDoesNotExist: Tried dashboard in module resuman.jobfunnel.views. Error was: 'module' object has no attribute 'dashboard'

----------------------------------------------------------------------
Ran 18 tests in 4.364s

FAILED (errors=2)
Destroying test database...
</code></pre>
<p>Let’s write the view so the test will pass. Edit views.py:</p>
<pre><code>
@login_required
def dashboard(request):
    return render_to_response('dashboard.html',
                              {'title': 'Dashboard'},
                              context_instance=RequestContext(request))
</code></pre>
<p>This view uses a template called dashboard.html. Let’s make that template. Go back to the mockup for the dashboard. Copy everything into templates/base.html, then rip out the content so all you have left is the generic skeleton of a page in your app. Something like this (notice that this is using the title variable passed into the context by the view):</p>
<pre><code>
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;

&lt;!--
# Resuman: keep track of job applications, cover letters, and resumes
#
# Copyright (c) 2009, Blakita Software LLC
# All rights reserved.
--&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"&gt;
&lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8" /&gt;

  &lt;title&gt;
    {{ title }}
  &lt;/title&gt;

  &lt;style type="text/css"&gt;
    @import "{{ MEDIA_URL }}base.css";
  &lt;/style&gt;

  {% block scripts %}
  {% endblock scripts %}

&lt;/head&gt;

&lt;body&gt;

&lt;div id="container"&gt;

&lt;div id="menu"&gt;
TBD
&lt;/div&gt; &lt;!-- end div=menu --&gt;

&lt;div id="header"&gt;
&lt;h1&gt;{{ title }}&lt;/h1&gt;
&lt;/div&gt; &lt;!-- end div=header --&gt;

&lt;div id="content"&gt;

{% block content %}
{% endblock content %}

&lt;/div&gt; &lt;!-- end div=content --&gt;

&lt;div id="footer"&gt;
&lt;div class="nav"&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;a href="/"&gt;Home&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="/blog/about"&gt;About&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href="/privacy.html"&gt;Privacy&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;

&lt;div class="copyright"&gt;Copyright © 2009, Blakita Software LLC&lt;/div&gt;
&lt;/div&gt; &lt;!-- end div=footer --&gt;

&lt;/div&gt; &lt;!-- end div=container --&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Now take the content you ripped out and put it into dashboard.html:</p>
<pre><code>
{% extends "base.html" %}

{% block content %}
&lt;ul id="funnel"&gt;
  &lt;li class="phase first"&gt;
    &lt;div class="phase"&gt;Applied&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;AAA&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase"&gt;
    &lt;div class="phase"&gt;Confirmed&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;BBB&lt;/li&gt;
        &lt;li class="company"&gt;CCC&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase"&gt;
    &lt;div class="phase"&gt;Screen&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;Fubar&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase"&gt;
    &lt;div class="phase"&gt;Interview&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;Rabuf&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase"&gt;
    &lt;div class="phase"&gt;Offer&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;Oof Rab&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li class="phase last"&gt;
    &lt;div class="phase"&gt;Start!&lt;/div&gt;
    &lt;div class="companies"&gt;
    &lt;ul class="companies"&gt;
        &lt;li class="company"&gt;Rab Oof&lt;/li&gt;
    &lt;/ul&gt;
    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

{% endblock content %}
</code></pre>
<p>Obviously this still just has dummy static data. We&#8217;ll get some active data in there very soon, but now we&#8217;re ready to rerun the test. It should pass this time. If not, fix the problem. When you get all tests passing, celebrate!</p>
<p>For real data, we need to write the model(s) used by this app. Let&#8217;s add another test:</p>
<pre><code>
class DashboardViewTest(DashboardViewTestBase):
    USERNAME = 'brian'
    TESTLOGIN = (USERNAME, 'a')

    def test_company_list(self):
        self.expect_div_content('content', 'Foobar Corp')
        return
</code></pre>
<p>Edit models.py to add the model:</p>
<pre><code>
from django.contrib.auth.models import User
from django.db import models

class Job(models.Model):
    applicant = models.ForeignKey(User)
    company = models.CharField(max_length=80)
</code></pre>
<p>The test depends on having a job in the database. Let&#8217;s set up a test fixture. Edit YOURAPPNAME/fixtures/initial_data.json:</p>
<pre><code>
[{"pk": 1, "model": "auth.user", "fields":
    {"username": "brian", "first_name": "", "last_name": "",
     "is_active": 1, "is_superuser": 0, "is_staff": 0,
     "last_login": "2009-02-06 13:50:02", "groups": [], "user_permissions": [],
     "password": "sha1$0fcc8$c4cf5184f5c005f90165e782fb090e7d75b72986",
     "email": "brian@example.com", "date_joined": "2009-02-06 13:44:04"}},
 {"pk": 2, "model": "auth.user", "fields":
    {"username": "alan", "first_name": "", "last_name": "",
     "is_active": 1, "is_superuser": 0, "is_staff": 0,
     "last_login": "2009-02-06 13:50:02", "groups": [], "user_permissions": [],
     "password": "sha1$0fcc8$c4cf5184f5c005f90165e782fb090e7d75b72986",
     "email": "alan@example.org", "date_joined": "2009-02-06 13:44:04"}},
 {"pk": 1, "model": "jobfunnel.job", "fields":
    {"position_url": "http://example.com/career/", "title": "Foobar Eng",
     "company_url": "http://example.com/", "company": "Foobar Corp", "applicant": 1,
     "phase": "Apply", "date": "2009-02-11", "position": "Engineer",
     "notes": "Applied via website"}}
]
</code></pre>
<p>This will populate the database with a couple of users, both with password &#8220;a&#8221;, and a job before each test runs.</p>
<p>Run this test, expecting exactly one failure — the content div does not contain the expected string. Let&#8217;s grab the list of jobs in the view and pass it into the template:</p>
<pre><code>
@login_required
def dashboard(request):
    jobs = models.Job.objects.all()
    return render_to_response('dashboard.html',
                              {'title': 'Dashboard',
                               'jobs': jobs,
                               },
                              context_instance=RequestContext(request))
</code></pre>
<p>I won&#8217;t paste all of the code here again, but we need to edit the template to use the jobs list:</p>
<pre><code>
    &lt;ul class="companies"&gt;
      {% for job in jobs %}
        &lt;li class="company"&gt;{{ job.company }}&lt;/li&gt;
      {% empty %}
        &lt;li class="company"&gt;No jobs in this phase.&lt;/li&gt;
      {% endfor %}
    &lt;/ul&gt;
</code></pre>
<p>Now rerun the test and expect it to pass. Hooray!</p>
<p>One last refinement before we quit for today: users shouldn&#8217;t be able to see each others applications. The way this is coded, all jobs are going to show up on everybody&#8217;s dashboards. Not good. Here&#8217;s another test that checks that the application for Foobar Corp only shows up on Brian&#8217;s dashboard, not on Alan&#8217;s.</p>
<pre><code>
class PrivateDashboardViewTest(DashboardViewTestBase):
    USERNAME = 'alan'
    TESTLOGIN = (USERNAME, 'a')

    def test_private_applications(self):
        assert('Foobar' not in self.get_div_content('content'))
        return
</code></pre>
<p>Run the test, watch it fail, and then change one line in the view:</p>
<pre><code>
    jobs = models.Job.objects.filter(applicant=request.user)
</code></pre>
<p>Now the all the tests should pass.</p>
<p>Push a copy of your code into your version control tool. Take a break, you deserve it.</p>
<p>For &#8220;homework&#8221;, put together your other views in the same way as this one. We’ll look at deployment tomorrow.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/five-days-to-a-django-web-app-day-three-coding/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jesse Noller on Python</title>
		<link>http://blog.bstpierre.org/jesse-noller-on-python</link>
		<comments>http://blog.bstpierre.org/jesse-noller-on-python#comments</comments>
		<pubDate>Mon, 09 Feb 2009 13:12:41 +0000</pubDate>
		<dc:creator>Brian St. Pierre</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://blog.bstpierre.org/?p=143</guid>
		<description><![CDATA[Jesse Noller has been republishing articles he wrote for Python Magazine. These are very informative: I learned new things about the &#8220;with&#8221; statement in python 2.5 and tonight I was introduced to Paramiko, a library for using SSH.]]></description>
			<content:encoded><![CDATA[<p><a href="http://jessenoller.com/category/python-magazine/">Jesse Noller</a> has been republishing articles he wrote for Python Magazine. These are very informative: I learned new things about the <a href="http://jessenoller.com/2009/02/03/get-with-the-program-as-contextmanager-completely-different/">&#8220;with&#8221; statement</a> in python 2.5 and tonight I was <a href="http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/">introduced to Paramiko</a>, a library for using SSH.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bstpierre.org/jesse-noller-on-python/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

