<?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>My stuff &#187; Python</title>
	<atom:link href="http://michelhollands.net/blog/index.php/category/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://michelhollands.net/blog</link>
	<description>Tech and travel tidbits</description>
	<lastBuildDate>Tue, 13 Dec 2011 09:59:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Cool Python</title>
		<link>http://michelhollands.net/blog/2011/10/09/cool-python/</link>
		<comments>http://michelhollands.net/blog/2011/10/09/cool-python/#comments</comments>
		<pubDate>Sun, 09 Oct 2011 15:33:36 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/?p=256</guid>
		<description><![CDATA[Check out the example in the 3rd comment : http://code.activestate.com/recipes/413137-call-a-functionmethod-x-times-per-second/ That is cool.]]></description>
			<content:encoded><![CDATA[<p>Check out the example in the 3rd comment :</p>
<p><a href="http://code.activestate.com/recipes/413137-call-a-functionmethod-x-times-per-second/">http://code.activestate.com/recipes/413137-call-a-functionmethod-x-times-per-second/</a></p>
<p>That is cool.</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2011/10/09/cool-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The __enter__ method in the with statement</title>
		<link>http://michelhollands.net/blog/2010/07/06/the-__enter__-method-in-the-with-statement/</link>
		<comments>http://michelhollands.net/blog/2010/07/06/the-__enter__-method-in-the-with-statement/#comments</comments>
		<pubDate>Tue, 06 Jul 2010 19:44:04 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/?p=194</guid>
		<description><![CDATA[The with statement is a great addition to Python. One thing that might not be immediately clear from the documentation is how the __enter__ method has to be implemented. If you want to use the object containing __enter__ then you have to return self there. You should not create a new object and return it. [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://docs.python.org/reference/compound_stmts.html#the-with-statement">with</a> statement is a great addition to <a href="http://www.python.org">Python</a>. One thing that might not be immediately clear from the documentation is how the __enter__ method has to be implemented. If you want to use the object containing __enter__ then you have to return self there. You should not create a new object and return it. Here&#8217;s an example :</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> example<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
  <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, login=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>:
      <span style="color: #008000;">self</span>.<span style="color: black;">setting</span> = <span style="color: #483d8b;">'A'</span>
      <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'__init__'</span>
&nbsp;
  <span style="color: #ff7700;font-weight:bold;">def</span> __enter__<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
      <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Entering '</span>
      <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>
&nbsp;
  <span style="color: #ff7700;font-weight:bold;">def</span> __exit__<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, exctype, value, <span style="color: #dc143c;">traceback</span><span style="color: black;">&#41;</span>:
      <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Exiting '</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">with</span> example<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">as</span> e:
   <span style="color: #ff7700;font-weight:bold;">print</span> e.<span style="color: black;">setting</span></pre></div></div>

<p>The output of this script is :</p>
<p><code>__init__<br />
Entering<br />
A<br />
Exiting </code></p>
<p>So __init__ is called first and then __enter__. Then the block after the with statement is executed, followed by __exit__ .</p>
<p>Of course you can return another object in __enter__ if necessary. In a lot of cases that might make more sense.</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2010/07/06/the-__enter__-method-in-the-with-statement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python logging output file change</title>
		<link>http://michelhollands.net/blog/2009/08/12/python-logging-output-file-change/</link>
		<comments>http://michelhollands.net/blog/2009/08/12/python-logging-output-file-change/#comments</comments>
		<pubDate>Wed, 12 Aug 2009 16:29:02 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/2009/08/12/python-logging-output-file-change/</guid>
		<description><![CDATA[I run unit tests in Python using the standard unittest module. The output should be logged to a file. For this Python has a standard logging library, which is somewhat similar to the log4j library for Java. The problem is that there is no easy way to direct the logging to a new file for [...]]]></description>
			<content:encoded><![CDATA[<p>I run unit tests in <a href="http://www.python.org/">Python</a> using the standard <a href="http://docs.python.org/library/unittest.html">unittest</a> module. The output should be logged to a file. For this <a href="http://www.python.org/">Python</a> has a standard <a href="http://docs.python.org/library/logging.html">logging</a> library, which is somewhat similar to the <a href="http://logging.apache.org/log4j/index.html">log4j </a> library for Java.  </p>
<p>The problem is that there is no easy way to direct the logging to a new file for every test case. Here&#8217;s how I got around it. Firstly the setup method of my testcase object contains the following :</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> setUp<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
    <span style="color: #008000;">self</span>.<span style="color: black;">logger</span> = <span style="color: #dc143c;">logging</span>.<span style="color: black;">getLogger</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'MyLogger'</span><span style="color: black;">&#41;</span>
    <span style="color: #008000;">self</span>.<span style="color: black;">logger</span>.<span style="color: black;">setLevel</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">logging</span>.<span style="color: black;">DEBUG</span><span style="color: black;">&#41;</span>
    <span style="color: #008000;">self</span>.<span style="color: black;">log_handler</span> = <span style="color: #008000;">None</span>
    <span style="color: #008000;">self</span>.<span style="color: #dc143c;">formatter</span> = <span style="color: #dc143c;">logging</span>.<span style="color: black;">Formatter</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%(asctime)s - %(name)s - %(message)s&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>A logger is created and the default level is set. Then variables are set for the log_handler and formatter. These are used in the settestcasename method found below. This gets called in every test method of the testcase class. First it removes the old handler. The testcase name given as parameter is then used to create a new <a href="http://docs.python.org/library/logging.html#filehandler">FileHandler</a>. This will create and log to a new file when something is logged. This new handler is then added to the logger.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> settestcasename<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>,giventestcasename,description=<span style="color: #483d8b;">&quot;&quot;</span><span style="color: black;">&#41;</span>:
    now=<span style="color: #dc143c;">datetime</span>.<span style="color: #dc143c;">datetime</span>.<span style="color: black;">today</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">strftime</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'%Y%m%d_%H%M%S'</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>.<span style="color: black;">log_handler</span> <span style="color: #ff7700;font-weight:bold;">is</span> <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #008000;">None</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">log_handler</span>.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">logger</span>.<span style="color: black;">removeHandler</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">log_handler</span><span style="color: black;">&#41;</span>
    filename=<span style="color: #483d8b;">'%s_%s.log'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>giventestcasename.<span style="color: black;">replace</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">' '</span>,<span style="color: #483d8b;">'_'</span><span style="color: black;">&#41;</span>, now<span style="color: black;">&#41;</span>
    <span style="color: #008000;">self</span>.<span style="color: black;">log_handler</span>=<span style="color: #dc143c;">logging</span>.<span style="color: black;">FileHandler</span><span style="color: black;">&#40;</span>filename,<span style="color: #483d8b;">'w'</span><span style="color: black;">&#41;</span>
    <span style="color: #008000;">self</span>.<span style="color: black;">log_handler</span>.<span style="color: black;">setFormatter</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: #dc143c;">formatter</span><span style="color: black;">&#41;</span>
    <span style="color: #008000;">self</span>.<span style="color: black;">logger</span>.<span style="color: black;">addHandler</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">log_handler</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The fact that the settestcasename has to be called is not ideal. but it works me. Something evil like <a href="http://mail.python.org/pipermail/python-list/2002-November/173802.html">this</a> could be used to get the name of the current method, which can then be used as a filename. A decorator can possibly be created as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2009/08/12/python-logging-output-file-change/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using map with a dictionary in Python</title>
		<link>http://michelhollands.net/blog/2009/07/21/using-map-with-a-dictionary-in-python/</link>
		<comments>http://michelhollands.net/blog/2009/07/21/using-map-with-a-dictionary-in-python/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 10:08:07 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/2009/07/21/using-map-with-a-dictionary-in-python/</guid>
		<description><![CDATA[When you have a dictionary in Python like this : mydict=&#123;'first':1, 'second':2, 'third':3&#125; and you want to get the values into a list with a certain order you can do this : mylist=&#91;mydict&#91;'first'&#93;, mydict&#91;'second'&#93;, mydict&#91;'third'&#93;&#93; However, that can get a bit verbose if there are a lot of entries. For every entry you have to [...]]]></description>
			<content:encoded><![CDATA[<p>When you have a dictionary in Python like this :</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">   mydict=<span style="color: black;">&#123;</span><span style="color: #483d8b;">'first'</span>:<span style="color: #ff4500;">1</span>, <span style="color: #483d8b;">'second'</span>:<span style="color: #ff4500;">2</span>, <span style="color: #483d8b;">'third'</span>:<span style="color: #ff4500;">3</span><span style="color: black;">&#125;</span></pre></div></div>

<p>and you want to get the values into a list with a certain order you can do this :</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">   mylist=<span style="color: black;">&#91;</span>mydict<span style="color: black;">&#91;</span><span style="color: #483d8b;">'first'</span><span style="color: black;">&#93;</span>, mydict<span style="color: black;">&#91;</span><span style="color: #483d8b;">'second'</span><span style="color: black;">&#93;</span>, mydict<span style="color: black;">&#91;</span><span style="color: #483d8b;">'third'</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span></pre></div></div>

<p>However, that can get a bit verbose if there are a lot of entries. For every entry you have to repeat &#8216;mydict&#8217;. An elegant way of solving this is using the <a href="http://docs.python.org/library/functions.html#map">map</a> function :</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">   mylist=<span style="color: #008000;">map</span><span style="color: black;">&#40;</span>mydict.<span style="color: black;">get</span>,<span style="color: black;">&#91;</span><span style="color: #483d8b;">'first'</span>, <span style="color: #483d8b;">'second'</span>, <span style="color: #483d8b;">'third'</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>This applies to &#8216;get&#8217; function of mydict to each of the arguments given in the list. This &#8216;get&#8217; function is the equivalent of calling mydict['some index'] .</p>
<p><a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">List comprehensions</a> can be used a lot of times instead of map. That&#8217;s the case here as well :</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">   mylist=<span style="color: black;">&#91;</span>mydict<span style="color: black;">&#91;</span>x<span style="color: black;">&#93;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: black;">&#91;</span><span style="color: #483d8b;">'first'</span>,<span style="color: #483d8b;">'second'</span>,<span style="color: #483d8b;">'third'</span><span style="color: black;">&#93;</span><span style="color: black;">&#93;</span></pre></div></div>

<p>This is arguably easier to understand than the version using <a href="http://docs.python.org/library/functions.html#map">map</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2009/07/21/using-map-with-a-dictionary-in-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Local SMTP in Python</title>
		<link>http://michelhollands.net/blog/2009/01/29/134/</link>
		<comments>http://michelhollands.net/blog/2009/01/29/134/#comments</comments>
		<pubDate>Thu, 29 Jan 2009 19:54:40 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/2009/01/29/134/</guid>
		<description><![CDATA[From this Django change : The easiest way to test your project's use of e-mail is to use a "dumb" e-mail server that receives the e-mails locally and displays them to the terminal, but does not actually send anything. Python has a built-in way to accomplish this with a single command : python -m smtpd [...]]]></description>
			<content:encoded><![CDATA[<p>From this <a href="http://code.djangoproject.com/changeset/9793">Django change</a> :</p>
<p><code>  The easiest way to test your project's use of e-mail is to use a "dumb" e-mail server that receives the e-mails locally and displays them to the terminal, but does not actually send anything. Python has a built-in way to accomplish this with a single command : </code></p>
<p><code>  python -m smtpd -n -c DebuggingServer localhost:1025 </code></p>
<p><code>This command will start a simple SMTP server listening on port 1025 of localhost. This server simply prints to standard output all email headers and the email body.</code></p>
<p>That is cool.</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2009/01/29/134/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python generators</title>
		<link>http://michelhollands.net/blog/2008/07/03/python-generators/</link>
		<comments>http://michelhollands.net/blog/2008/07/03/python-generators/#comments</comments>
		<pubDate>Thu, 03 Jul 2008 12:57:11 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/2008/07/03/python-generators/</guid>
		<description><![CDATA[Python generators are powerful, but perhaps a bit hard to understand. Luckily, a great tutorial on them can be found at http://www.dabeaz.com/generators/index.html .]]></description>
			<content:encoded><![CDATA[<p>Python generators are powerful, but perhaps a bit hard to understand. Luckily, a great tutorial on them can be found at <a href="http://www.dabeaz.com/generators/index.html">http://www.dabeaz.com/generators/index.html</a> .</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2008/07/03/python-generators/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Workout</title>
		<link>http://michelhollands.net/blog/2008/04/23/85/</link>
		<comments>http://michelhollands.net/blog/2008/04/23/85/#comments</comments>
		<pubDate>Wed, 23 Apr 2008 14:15:14 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/2008/04/23/85/</guid>
		<description><![CDATA[My Google App Engine application is a workout followup utility. You can enter your times or distances, and the results are shown in list. Graphs were added using the Google Chart API. The URL is http://workoutfollowup.appspot.com/ (note : you will have to login with your Google ID). One of the things added recently is the [...]]]></description>
			<content:encoded><![CDATA[<p>My <a href="http://code.google.com/appengine/">Google App Engine</a> application is a workout followup utility. You can enter your times or distances, and the results are shown in list. Graphs were added using the <a href="http://code.google.com/apis/chart/">Google Chart API</a>. The URL is <a href="http://workoutfollowup.appspot.com/">http://workoutfollowup.appspot.com/</a> (note : you will have to login with your Google ID).</p>
<p>One of the things added recently is the ability to download the results as a csv file. The following code snippet shows how to do this. The key thing is setting the <a href="http://support.microsoft.com/kb/260519">Content-Disposition</a> header, this tells the browser that a csv file is coming. The browser will then show a dialog box, where you can specify where you want to save the file. Otherwise the code is pretty standard <a href="http://www.python.org">Python</a> : the standard csv module is used to create a csv file in memory in the StringIO object.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">class</span> CsvPage<span style="color: black;">&#40;</span>webapp.<span style="color: black;">RequestHandler</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> get<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
      <span style="color: #dc143c;">user</span> = users.<span style="color: black;">get_current_user</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
      <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #dc143c;">user</span>:
        output = <span style="color: #dc143c;">StringIO</span>.<span style="color: #dc143c;">StringIO</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        writer=<span style="color: #dc143c;">csv</span>.<span style="color: black;">writer</span><span style="color: black;">&#40;</span>output, dialect=<span style="color: #483d8b;">'excel'</span><span style="color: black;">&#41;</span>
        query = db.<span style="color: black;">GqlQuery</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;&quot;&quot;SELECT *
                                 FROM Workout
                                WHERE added_by = :1
                                ORDER BY date DESC &quot;&quot;&quot;</span>,
                            users.<span style="color: black;">get_current_user</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
        writer.<span style="color: black;">writerow</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'date'</span>, <span style="color: #483d8b;">'minutes'</span>, <span style="color: #483d8b;">'distance'</span>, <span style="color: #483d8b;">'calories'</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> workout <span style="color: #ff7700;font-weight:bold;">in</span> query:
            row=<span style="color: black;">&#91;</span>workout.<span style="color: black;">date</span>.<span style="color: black;">strftime</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%x&quot;</span><span style="color: black;">&#41;</span>, workout.<span style="color: black;">minutes</span>, \
                     workout.<span style="color: black;">distance</span>, workout.<span style="color: black;">calories</span><span style="color: black;">&#93;</span>
            writer.<span style="color: black;">writerow</span><span style="color: black;">&#40;</span>row<span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;Content-Type&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">&quot;application/x-csv&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">headers</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'Content-Disposition'</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">'attachment;'</span> \
                                       <span style="color: #483d8b;">'filename=workouts.csv'</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">out</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span>output.<span style="color: black;">getvalue</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        output.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
      <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">redirect</span><span style="color: black;">&#40;</span>users.<span style="color: black;">create_login_url</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">request</span>.<span style="color: black;">uri</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Lines with \ at the end are continued on the next line, in the standard Python fashion.</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2008/04/23/85/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Google App Engine</title>
		<link>http://michelhollands.net/blog/2008/04/14/google-app-engine/</link>
		<comments>http://michelhollands.net/blog/2008/04/14/google-app-engine/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 16:10:55 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/2008/04/14/google-app-engine/</guid>
		<description><![CDATA[Python&#8216;s creator, Guido Van Rossum, has been hinting at this for a while, and it&#8217;s finally here : Google App Engine. It&#8217;s a way to build and host web apps on the Google servers. I put a small app together, which is a very simple variation on the &#8216;The Django Form Validation Framework on Google [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.python.org">Python</a>&#8216;s creator, Guido Van Rossum, has been hinting at this for a while, and it&#8217;s finally here : <a href="http://code.google.com/appengine/">Google App Engine</a>. It&#8217;s a way to build and host web apps on the Google servers.</p>
<p>I put a small app together, which is a very simple variation on the &#8216;<a href="http://code.google.com/appengine/articles/djangoforms.html">The Django Form Validation Framework on Google App Engine</a>&#8216; article. It let&#8217;s you login, and store some data on workouts. On to some code :</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">cgi</span>
  <span style="color: #ff7700;font-weight:bold;">import</span> wsgiref.<span style="color: black;">handlers</span>
  <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
&nbsp;
  <span style="color: #ff7700;font-weight:bold;">from</span> google.<span style="color: black;">appengine</span>.<span style="color: black;">api</span> <span style="color: #ff7700;font-weight:bold;">import</span> users
  <span style="color: #ff7700;font-weight:bold;">from</span> google.<span style="color: black;">appengine</span>.<span style="color: black;">ext</span> <span style="color: #ff7700;font-weight:bold;">import</span> db
  <span style="color: #ff7700;font-weight:bold;">from</span> google.<span style="color: black;">appengine</span>.<span style="color: black;">ext</span> <span style="color: #ff7700;font-weight:bold;">import</span> webapp
  <span style="color: #ff7700;font-weight:bold;">from</span> google.<span style="color: black;">appengine</span>.<span style="color: black;">ext</span>.<span style="color: black;">webapp</span> <span style="color: #ff7700;font-weight:bold;">import</span> template
&nbsp;
  <span style="color: #ff7700;font-weight:bold;">from</span> google.<span style="color: black;">appengine</span>.<span style="color: black;">ext</span>.<span style="color: black;">db</span> <span style="color: #ff7700;font-weight:bold;">import</span> djangoforms</pre></div></div>

<p>Firstly, a lot of imports are done to get everything we need.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">class</span> Workout<span style="color: black;">&#40;</span>db.<span style="color: black;">Model</span><span style="color: black;">&#41;</span>:
    minutes = db.<span style="color: black;">IntegerProperty</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    distance = db.<span style="color: black;">FloatProperty</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    calories = db.<span style="color: black;">IntegerProperty</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    date = db.<span style="color: black;">DateProperty</span><span style="color: black;">&#40;</span>required=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    added_by = db.<span style="color: black;">UserProperty</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Then a class is defined that is derived from a database Model base class. This will be stored in a database from Google called the <a href="http://code.google.com/appengine/docs/datastore/">Datastore</a>. It contains fields for the minutes, the distance cycled and so on. The only mandatory field is the date. There is also a user field. This will be filled in when the user logs in. It also keeps the data private per user.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">class</span> WorkoutForm<span style="color: black;">&#40;</span>djangoforms.<span style="color: black;">ModelForm</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">class</span> Meta:
      model = Workout
      exclude = <span style="color: black;">&#91;</span><span style="color: #483d8b;">'added_by'</span><span style="color: black;">&#93;</span></pre></div></div>

<p>Next, a form object is created. This is based on the model defined above, and it will not display the added_by field.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">class</span> MainPage<span style="color: black;">&#40;</span>webapp.<span style="color: black;">RequestHandler</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> get<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
      <span style="color: #dc143c;">user</span> = users.<span style="color: black;">get_current_user</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
      <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #dc143c;">user</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">out</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'form goes here'</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">out</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span>WorkoutForm<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">out</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'remainder of form'</span><span style="color: black;">&#41;</span>
      <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">redirect</span><span style="color: black;">&#40;</span>users.<span style="color: black;">create_login_url</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">request</span>.<span style="color: black;">uri</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The MainPage class handles request for a page. Here the get request is handled. If the user is logged in, it displays the form. If not, a redirection is done to Google&#8217;s login page.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">    <span style="color: #ff7700;font-weight:bold;">def</span> post<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
      data = WorkoutForm<span style="color: black;">&#40;</span>data=<span style="color: #008000;">self</span>.<span style="color: black;">request</span>.<span style="color: black;">POST</span><span style="color: black;">&#41;</span>
      <span style="color: #ff7700;font-weight:bold;">if</span> data.<span style="color: black;">is_valid</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
        <span style="color: #808080; font-style: italic;"># Save the data, and redirect to the view page</span>
        entity = data.<span style="color: black;">save</span><span style="color: black;">&#40;</span>commit=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
        entity.<span style="color: black;">added_by</span> = users.<span style="color: black;">get_current_user</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        entity.<span style="color: black;">put</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">redirect</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'/workouts.html'</span><span style="color: black;">&#41;</span>
      <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #808080; font-style: italic;"># Reprint the form</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">out</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'beginning of form'</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">out</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">out</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'remainder of form'</span><span style="color: black;">&#41;</span></pre></div></div>

<p>A post request (from the form in the get method) is handled by the post method. It saves the data in the database if it is valid. If not, for example if the date is not filled here, it will display the data again with an error message.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">class</span> WorkoutPage<span style="color: black;">&#40;</span>webapp.<span style="color: black;">RequestHandler</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> get<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
      <span style="color: #dc143c;">user</span> = users.<span style="color: black;">get_current_user</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
      <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #dc143c;">user</span>:
        query = db.<span style="color: black;">GqlQuery</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;SELECT * FROM Workout WHERE added_by = :1 ORDER BY date DESC&quot;</span>,
                            users.<span style="color: black;">get_current_user</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
        workouts=<span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> workout <span style="color: #ff7700;font-weight:bold;">in</span> query:
            workouts.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: black;">&#123;</span><span style="color: #483d8b;">'date'</span>: workout.<span style="color: black;">date</span>.<span style="color: black;">strftime</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%x&quot;</span><span style="color: black;">&#41;</span>,
                             <span style="color: #483d8b;">'minutes'</span>: workout.<span style="color: black;">minutes</span>,
                             <span style="color: #483d8b;">'distance'</span>: workout.<span style="color: black;">distance</span>,
                             <span style="color: #483d8b;">'calories'</span>: workout.<span style="color: black;">calories</span>
                            <span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>
&nbsp;
        template_values = <span style="color: black;">&#123;</span>
          <span style="color: #483d8b;">'workouts'</span>: workouts,
        <span style="color: black;">&#125;</span>
&nbsp;
        path = <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">dirname</span><span style="color: black;">&#40;</span>__file__<span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'workout.html'</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">response</span>.<span style="color: black;">out</span>.<span style="color: black;">write</span><span style="color: black;">&#40;</span>template.<span style="color: black;">render</span><span style="color: black;">&#40;</span>path, template_values<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
      <span style="color: #ff7700;font-weight:bold;">else</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">redirect</span><span style="color: black;">&#40;</span>users.<span style="color: black;">create_login_url</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">request</span>.<span style="color: black;">uri</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The WorkoutPage class handles a get request that shows the results stored in the database. It uses a template called workout.html, which is not shown. All the necessary data is gathered and then the template is rendered with that data in the template.render call.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">def</span> main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    application = webapp.<span style="color: black;">WSGIApplication</span><span style="color: black;">&#40;</span>
                                         <span style="color: black;">&#91;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'/'</span>, MainPage<span style="color: black;">&#41;</span>,
                                          <span style="color: black;">&#40;</span><span style="color: #483d8b;">'/workouts.html'</span>, WorkoutPage<span style="color: black;">&#41;</span>,
                                          <span style="color: black;">&#93;</span>,
                                         debug=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    wsgiref.<span style="color: black;">handlers</span>.<span style="color: black;">CGIHandler</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">run</span><span style="color: black;">&#40;</span>application<span style="color: black;">&#41;</span>
&nbsp;
  <span style="color: #ff7700;font-weight:bold;">if</span> __name__==<span style="color: #483d8b;">&quot;__main__&quot;</span>:
    main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Lastly, the URLs are setup. The mainpage is mapped to / and the WorkoutPage class to /workouts.html.</p>
<p>The app, which is very Web 0.1, can be found <a href="http://1.1.workoutfollowup.appspot.com/">here</a>. After you login with your Google ID, you can start logging those workouts.</p>
<p>A few things to remark :</p>
<ul>
<li>this code could do with a bit of a cleanup, which is all my fault</li>
<li>the data is stored on Google&#8217;s servers. You may not like that.</li>
<li>a Google ID is needed to login here (this can probably be changed)</li>
</ul>
<p>All said and done, <a href="http://code.google.com/appengine/">Google App Engine</a> is a nice piece of work. It took about an hour to put all of this together and to upload it to the Google servers. So Google seems to have their homework about making it developer friendly. How well it will work for real apps is another matter. Only time will shows us that, and this is definitely still a beta. But it does look promising.</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2008/04/14/google-app-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sqlite with Python</title>
		<link>http://michelhollands.net/blog/2008/03/10/sqlite-with-python/</link>
		<comments>http://michelhollands.net/blog/2008/03/10/sqlite-with-python/#comments</comments>
		<pubDate>Mon, 10 Mar 2008 15:05:23 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/2008/03/10/sqlite-with-python/</guid>
		<description><![CDATA[Python 2.5 has a SQLite library. The documentation says it best what this can be used for : SQLite is a C library that provides a lightweight disk-based database that doesn't require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.python.org">Python</a> 2.5 has a <a href="http://www.sqlite.org/index.html">SQLite</a> library. The documentation says it best what this can be used for :</p>
<pre>
  SQLite is a C library that provides a lightweight disk-based database
  that doesn't require a separate server process and allows accessing
  the database using a nonstandard variant of the SQL query language.
  Some applications can use SQLite for internal data storage. It's also
  possible to prototype an application using SQLite and then port the
  code to a larger database such as PostgreSQL or Oracle.
</pre>
<p>The following code creates the database.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">import</span> sqlite3
&nbsp;
  conn = sqlite3.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'feeds.db'</span><span style="color: black;">&#41;</span>
&nbsp;
  c = conn.<span style="color: black;">cursor</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
  <span style="color: #808080; font-style: italic;"># Create table</span>
  c.<span style="color: black;">execute</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">''</span><span style="color: #483d8b;">'create table feeds (date text, url text)'</span><span style="color: #483d8b;">''</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Adding data can be done as follows. This adds a row to the feeds table, with the current time as a string in the date column and a HTML link in the url field.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  <span style="color: #ff7700;font-weight:bold;">import</span> sqlite3, <span style="color: #dc143c;">time</span>
&nbsp;
  conn = sqlite3.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'feeds.db'</span><span style="color: black;">&#41;</span>
  conn.<span style="color: black;">isolation_level</span> = <span style="color: #008000;">None</span>
  c = conn.<span style="color: black;">cursor</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
  <span style="color: #808080; font-style: italic;"># Insert a row of data</span>
  data = <span style="color: black;">&#40;</span> <span style="color: #dc143c;">time</span>.<span style="color: black;">strftime</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;%a, %d %b %Y %H:%M:%S +0000&quot;</span>,
                                <span style="color: #dc143c;">time</span>.<span style="color: black;">localtime</span><span style="color: black;">&#40;</span><span style="color: #008000;">None</span><span style="color: black;">&#41;</span> <span style="color: black;">&#41;</span>,
              <span style="color: #483d8b;">'http://www.sqlite.org/sqlite.html'</span> <span style="color: black;">&#41;</span>
  c.<span style="color: black;">execute</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;&quot;&quot;insert into feeds values ('%s','%s')&quot;&quot;&quot;</span> <span style="color: #66cc66;">%</span> data <span style="color: black;">&#41;</span></pre></div></div>

<p>Most Linux systems have a command line <a href="http://www.sqlite.org/index.html">SQLite</a> client, called sqlite3 for <a href="http://www.sqlite.org/index.html">SQLite</a> version 3. You can use this to open the database created in Python.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">  $ sqlite3 feeds.db
  SQLite version 3.3.6
  Enter <span style="color: #ff0000;">&quot;.help&quot;</span> <span style="color: #000000; font-weight: bold;">for</span> instructions
  sqlite<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">select</span> <span style="color: #000000; font-weight: bold;">*</span> from feeds;
  Mon, <span style="color: #000000;">10</span> Mar <span style="color: #000000;">2008</span> <span style="color: #000000;">14</span>:<span style="color: #000000;">49</span>:<span style="color: #000000;">11</span> +0000<span style="color: #000000; font-weight: bold;">|</span>http:<span style="color: #000000; font-weight: bold;">//</span>www.sqlite.org<span style="color: #000000; font-weight: bold;">/</span>sqlite.html
  sqlite<span style="color: #000000; font-weight: bold;">&gt;</span> .quit</pre></div></div>

<p>Cool, he ?</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2008/03/10/sqlite-with-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A one line webserver</title>
		<link>http://michelhollands.net/blog/2008/03/03/a-one-line-webserver/</link>
		<comments>http://michelhollands.net/blog/2008/03/03/a-one-line-webserver/#comments</comments>
		<pubDate>Mon, 03 Mar 2008 15:35:42 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://michelhollands.net/blog/2008/03/03/a-one-line-webserver/</guid>
		<description><![CDATA[Python has a built in webserver, that shows the contents of the directory it&#8217;s started in. Here&#8217;s how you run it : python -c &#34;from SimpleHTTPServer import test; test()&#34; This is invaluable if you have to copy some files across to another machine. It won&#8217;t work across the internet, but on a local network it [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.python.org">Python</a> has a built in webserver, that shows the contents of the directory it&#8217;s started in. Here&#8217;s how you run it :</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">  python -c <span style="color: #483d8b;">&quot;from SimpleHTTPServer import test; test()&quot;</span></pre></div></div>

<p>This is invaluable if you have to copy some files across to another machine. It won&#8217;t work across the internet, but on a local network it can&#8217;t be beat. Yesterday I had to move a 2.4 Gig ISO file from the laptop PC to my Mac. Just put in a crossover cable, run the Python one liner and Bob&#8217;s your uncle.</p>
<p>BTW : the port used by default is 8000. So http://<ip_address>:8000 will get you to the right place.</p>
]]></content:encoded>
			<wfw:commentRss>http://michelhollands.net/blog/2008/03/03/a-one-line-webserver/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 1.587 seconds -->

