<?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>coder . cl &#187; python</title>
	<atom:link href="http://coder.cl/category/programming/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://coder.cl</link>
	<description>web developer &#38; system programmer</description>
	<lastBuildDate>Sat, 04 Feb 2012 12:07:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>django and amazon s3</title>
		<link>http://coder.cl/2012/01/django-and-amazon-s3/</link>
		<comments>http://coder.cl/2012/01/django-and-amazon-s3/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 13:18:45 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2183</guid>
		<description><![CDATA[Amazon S3 is a well known web based storage system provided as SaaS service provided by Amazon Web Services. On Django you can integrate that service using the storage interface called Django Storages, but you must have some considerations using that SaaS storage interface. Mainly regarding the Date header sent to the service on each [...]]]></description>
			<content:encoded><![CDATA[<p><a href='http://aws.amazon.com/s3/' title='Amazon Simple Storage Service (Amazon S3)'>Amazon S3</a> is a well known web based storage system provided as SaaS service provided by <a href='http://aws.amazon.com/' title='Amazon Web Services (AWS)'>Amazon Web Services</a>. On Django you can integrate that service using the storage interface called <a href='http://code.welldev.org/django-storages/' title='Django Storages (django-storages)'>Django Storages</a>, but you must have some considerations using that SaaS storage interface. Mainly regarding the <tt>Date</tt> header sent to the service on each read, write and similar operations, where you must send an updated header with the proper Time Zone and format.</p>
<p><span id="more-2183"></span></p>
<p>Once you have configured and working the django-storages package, you should fill the <tt>Date</tt> header or the <tt>x-amz-date</tt> header each time that you do a request to S3. So, the only way to do that is not to leave the module sending the date automatically, instead you should write the settings variable <tt>AWS_HEADERS</tt>.</p>
<pre name="code" class="brush:python;">

import pytz
from datetime import datetime
from django.conf import settings

def get_aws_date(self):
    """
    Returns the server date formatted and using the server
    time zone localized to be used as Date header with
    Amazon S3.
    """
    stz = pytz.timezone(settings.TIME_ZONE)
    dtm = stz.localize(datetime.now()).strftime("%a, %d %b %Y %H:%M:%S %z")
    settings.AWS_HEADERS['Date'] = dtm
    settings.AWS_HEADERS['x-amz-date'] = dtm
    return dtm
</pre>
<p>Also, you must consider this requirement to work with S3 on all your requests. Since django-storages checks if the <tt>AWS_HEADERS</tt> has the Date or x-amz-date headers set, you must set that header each time that you make a request to S3, so you cannot use a batch <tt>read()</tt> from the storage or a batch <tt>write()</tt> to the storage, because it will use the previously sent Date header and it will fail, because it is considered inconsistent by the S3 authentication mechanism. If we use S3 as default storage, the example below will fail, because it will send file chunks with the same Date header, because the header was set previously.</p>
<pre name="code" class="brush:python;">

from django.core.files.storage import default_storage

if default_storage.exist('test-large-file.mp3'):
    mp3file = open('test-large-file.mp3')
    s3file = default_storage.open('test-large-file.mp3')
    mp3file.write(s3file.read())
    mp3file.close()
    s3file.close()
</pre>
<p>So, you need to use small chunks to read from the storage, as the example below.</p>
<pre name="code" class="brush:python;">

from django.core.files.storage import default_storage

if default_storage.exist('test-large-file.mp3'):
    get_aws_date()
    mp3file = open('test-large-file.mp3')
    s3file = default_storage.open('test-large-file.mp3')
    buff = s3file.read(settings.AWS_CHUNK_SIZE)
    while buff:
        mp3file.write(buff)
        try:
            buff = s3file.read(settings.AWS_CHUNK_SIZE)
        except Exception, exc:
            buff = None
    mp3file.close()
    s3file.close()
</pre>
<p>But also you must consider few issues about this. Since AWS_HEADERS is a global variable, writing to that variable will slow down your code because it lacks time on GIL usage, also it will lack your threaded application if it written twice, even if you are using locks and Django can handle parallel writes to that variable. So, be careful reading and writing large files from S3, and take a look on how the Date header is sent on each request.</p>
<pre name="code" class="brush:python;">

def _add_aws_auth_header(self, headers, method,
                         bucket, key, query_args):
    if not headers.has_key('Date'):
        headers['Date'] = time.strftime("%a, %d %b %Y %X GMT",
                                        time.gmtime())

    c_string = canonical_string(method, bucket, key,
                                query_args, headers)
    headers['Authorization'] = \
        "AWS %s:%s" % (self.aws_access_key_id,
                       encode(self.aws_secret_access_key, c_string))
</pre>
<p>Where the <tt>%X</tt> <a href='http://docs.python.org/library/datetime.html#strftime-strptime-behavior' title='Python Manual, strftime() and strptime() Behavior'>specifier for localized machines</a> with an environment variable <tt>LC_ALL</tt> different from <i>C</i> will throw the wrong date format disallowing your application to work with S3. This is a well known bug reported <a href='https://bitbucket.org/david/django-storages/issue/56/aws-authentication-requires-a-valid-date' title='#56 "AWS authentication requires a valid Date or x-amz-date header"' rel="nofollow">on this link</a>. So, the right implementation, should be as follows.</p>
<pre name="code" class="brush:python;">

def _add_aws_auth_header(self, headers, method,
                         bucket, key, query_args):
    if not 'Date' in headers:
        stz = pytz.timezone(settings.TIME_ZONE)
        dtm = stz.localize(datetime.now()).strftime("%a, %d %b %Y %H:%M:%S %z")
        headers['Date'] = dtm

    c_string = canonical_string(method, bucket, key,
                                query_args, headers)
    headers['Authorization'] = \
        "AWS %s:%s" % (self.aws_access_key_id,
                       encode(self.aws_secret_access_key, c_string))
</pre>
<p>Good luck using S3.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2012 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2012. | <a href="http://coder.cl/2012/01/django-and-amazon-s3/">Permalink</a> | <a href="http://coder.cl/2012/01/django-and-amazon-s3/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/01/django-and-amazon-s3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>decorated template tags in django</title>
		<link>http://coder.cl/2012/01/decorated-template-tags-in-django/</link>
		<comments>http://coder.cl/2012/01/decorated-template-tags-in-django/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 17:26:01 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2153</guid>
		<description><![CDATA[Django provides an API to create custom template tags for those applications mounted over this nice Web Application Framework. Sometimes we need to decorate our functions, but you cannot decorate a function registered as tag in Django. The most elegant solution to solve this problem is to use a closure which will wrap the template [...]]]></description>
			<content:encoded><![CDATA[<p>Django provides an API to create custom template tags for those applications mounted over this nice Web Application Framework. Sometimes we need to <a href='http://wiki.python.org/moin/PythonDecorators' title='Python Decorators'>decorate</a> our functions, but you cannot decorate a function registered as tag in Django. The most elegant solution to solve this problem is to use a closure which will wrap the template tag function to be used decorated template tag.</p>
<p><span id="more-2153"></span></p>
<pre name="code" class="brush:python;">

from django import template
from django.conf import settings

from owner.common.decorators import html_escape_output

register = template.Library()

def fmt_owner_name(_owner):
    """
    Formats the Owner Name
    """
    @html_escape_output()
    def _fmt_owner_name(owner):
        nms = u'%s %s' % (first_word_on_string(owner.first_name),
                          first_word_on_string(owner.last_name))
        if len(nms) &gt; settings.MAX_NAME_ON_CARD:
            return u'%s...' % (nms[0:settings.MAX_NAME_ON_CARD])
        else:
            return nms
    return _format_owner_name(_owner)
fmt_owner_name = register.simple_tag(fmt_owner_name)
</pre>
<p>So, in this example, the template tag will escape the owner name, where all template tags in Django are considering HTML output as safe output, so they do not escape the HTML output automatically, even if you use <i>is_safe</i> and <i>needs_autoescape</i> properties, they require special treatment when you need to escape the HTML tags. In the example above the closure <tt>_fmt_owner_name</tt> is decorated with <tt>@html_escape_output</tt> which forces escaped HTML output to the Django template.</p>
<p>Also you can stack any number of decorators that you want. I think that this avoids using <i>cgi.escape</i> and similar stuff on each return statement. This helps you on Django template tag processing with common operations, like the example above. And it reduces the amount of code, making it more legible and simple, where we are using the fourth aphorism from the <a href='http://www.python.org/dev/peps/pep-0020/' title='PEP20: Zen of Python'>Zen of Python</a>: <i>&laquo;complex is better than complicated&raquo;</i>. Then we apply the template tag in the Django template as follows.</p>
<pre name="code" class="brush:xhtml;">

&lt;div class=&quot;owner-name&quot;&gt;
  {% fmt_owner_name owner_obj %}
&lt;/div&gt;
</pre>
<p>I hope that this will help you on the task of reducing the amount of repeated calls.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2012 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2012. | <a href="http://coder.cl/2012/01/decorated-template-tags-in-django/">Permalink</a> | <a href="http://coder.cl/2012/01/decorated-template-tags-in-django/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/01/decorated-template-tags-in-django/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>integrating selenium and django</title>
		<link>http://coder.cl/2011/12/integrating-selenium-and-django/</link>
		<comments>http://coder.cl/2011/12/integrating-selenium-and-django/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 20:53:34 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2090</guid>
		<description><![CDATA[As you know, using unit tests will only provide a testing over algorithms and low level interfaces. For a higher level approach, you have the automated testing suite that provides the Selenium, which provides you a test case API to be used in functional tests. If you want to automate functional tests under Django, you [...]]]></description>
			<content:encoded><![CDATA[<p>As you know, using unit tests will only provide a testing over algorithms and low level interfaces. For a higher level approach, you have the automated testing suite that provides the Selenium, which provides you a test case API to be used in functional tests. If you want to automate functional tests under Django, you can use the selenium IDE to record your actions on the web site, and export them as test case instructions for the selenium API, which will run those tests as you in the web browser, or even other tools like <a href='http://htmlunit.sourceforge.net/' title='Html Unit'>Html Unit</a>. This includes several browsers supported by the API, including a server that allows you to mount a test grid using various machines.</p>
<p><span id="more-2090"></span></p>
<p>Without falling in numerous details, I will try to explain how to mount selenium tests under Django. The very first step is to download and install the <a href='http://seleniumhq.org/projects/ide/' title='Selenium IDE Plug-In'>selenium plug-in</a>, that allows you to create automated functional tests for the selenium API.</p>
<div class="figure">
<a href='http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2011/12/selenium-ide.jpg?v=2.0' title='Selenium IDE' target="_blank"><img src='http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2011/12/selenium-ide.jpg?v=2.0' border='0' alt='Selenium IDE' /></a></p>
<div>Selenium IDE</div>
</div>
<p>Once you have created the functional test using the record option, you can save it with the native selenium format, which is a simplified HTML file. Once you saved the test case, you can <i>export</i> the test case using the export option on the file menu, where you will see two formats provided for Python integration, called <i>Web Driver</i> and <i>Remote Control</i>. The first one called <i>Web Driver</i> is used with a local browser &mdash; on the local test server &mdash; and the second one called <i>Remote Control</i> should be used with grid servers, an option that supports multiple browsers by calling remote actions on a grid of parallel test servers. Once you export the file in the Web Driver format, you see that the python code is based on the standard unit testing suite, as the example that follows.</p>
<pre name="code" class="brush: python;">

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re

class TestWebdriver(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://myserver.com/"
        self.verificationErrors = []

    def test_login_view(self):
        driver = self.driver
        driver.get("/home/")
        driver.find_element_by_link_text("Login").click()
        driver.find_element_by_id("username").clear()
        driver.find_element_by_id("username").send_keys("test@myserver.com")
        driver.find_element_by_id("password").clear()
        driver.find_element_by_id("password").send_keys("testpass123123")
        driver.find_element_by_css_selector("input.submit.login-but").click()
        driver.find_element_by_link_text("MainPanel").click()

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()
</pre>
<p>To run that test, the file should be saved on the <tt>app/tests/</tt> directory, and should run using a standard browser. In my case, I am using <a href='https://github.com/kmmbvnr/django-jenkins' title='django-jenkins module'>django-jenkins</a> for continuous integration with <a href='http://jenkins-ci.org/' title='Jenkins'>Jenkins</a> or <a href='http://www.atlassian.com/software/bamboo/overview' title='Atlassian Bamboo'>Atlassian Bamboo</a>. So, you should add the <a href='http://pypi.python.org/pypi/selenium/' title='Python Selenium'>Python Selenium</a> API, where you will find the <tt>webdriver</tt> package to use with the web driver API &mdash; remember that it is used with a local browser &mdash; or the <tt>selenium</tt> package that provides API calls to use grid servers for parallel tests.</p>
<p>So, the functional test integration runs as standard integration for any build. You can separate the test suites customising the build script for Jenkins or Bamboo and have separate reports. That is a preferred option if you want to keep detailed information about your tests. Enjoy integrating automated functional tests.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/12/integrating-selenium-and-django/">Permalink</a> | <a href="http://coder.cl/2011/12/integrating-selenium-and-django/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/12/integrating-selenium-and-django/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>why to go with multi-paradigm?</title>
		<link>http://coder.cl/2011/11/why-to-go-with-multi-paradigm/</link>
		<comments>http://coder.cl/2011/11/why-to-go-with-multi-paradigm/#comments</comments>
		<pubDate>Fri, 18 Nov 2011 15:07:57 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1957</guid>
		<description><![CDATA[Hybrid languages are cool. Most powerful programming languages are those languages which can handle a multi-paradigm scope. You can reduce the amount of code considerably when you are using a multi-paradigm approach. Due to the imperative origin and procedural approach of object oriented languages, having only object oriented language approach is not enough to solve [...]]]></description>
			<content:encoded><![CDATA[<p>Hybrid languages are cool. Most powerful programming languages are those languages which can handle a multi-paradigm scope. You can reduce the amount of code considerably when you are using a multi-paradigm approach. Due to the imperative origin and procedural approach of object oriented languages, having only object oriented language approach is not enough to solve problems. For example as we reviewed the widely used MapReduce distributed computing model has its origin on the functional paradigm in two higher order functions called <tt>map</tt> and <tt>reduce</tt> &mdash; where the synonym of <i>reduce</i> is <tt>fold</tt>, applying a kind of Monoid where the data is lifted and transformed by the <tt>map</tt> function and then is processed and reduced by the <tt>fold</tt> or <tt>reduce</tt> function.</p>
<p><span id="more-1957"></span></p>
<p><br/></p>
<h3>tl;dr</h3>
<p>I prefer multi-paradigm languages because you can do cool stuff with less code.</p>
<p><br/></p>
<h3>why do I prefer it?</h3>
<p>If you reduce the amount of code that you are programming, you can decrease the amount of possible bugs by reducing its cyclomatic complexity. So, using functional approach in certain cases will reduce the amount of code that you are producing, increasing your productivity considerably. Take a look on the following code made on PHP to find the lowest value in an array of associative arrays.</p>
<pre class="brush: php;">
&lt;?php

/* PHP example on associative arrays */

$min = 9999;
$tst = array(array('a' =&gt; 30, 'b' =&gt; 20, 'c' =&gt; 10),
             array('a' =&gt; 29, 'b' =&gt; 19, 'c' =&gt; 9),
             array('a' =&gt; 28, 'b' =&gt; 18, 'c' =&gt; 8));

foreach ($tst as $t) {
    if ($t['a'] &lt; $min) {
        $min = $t['a'];
    }
}

echo &quot;{$min}\n&quot;;

 ?&gt;
</pre>
<p>Now take a look on the same problem but implemented in Python using multi-paradigm approach, with functional features and using higher order functions.</p>
<pre class="brush: python;">

### Python example using higher order functions and
### functional approach

tst = [{'a': 30, 'b': 20, 'c': 10},
       {'a': 29, 'c': 19, 'c': 9},
       {'a': 28, 'c': 18, 'c': 8}]

t = min(*tst, key=lambda x: x['a'])
print(t['a'])
</pre>
<p>You can clearly see that the code was reduced to only one line of code using a functional approach, using <tt>min</tt> as higher order function, so the <i>&eta;-reduction</i> is evident. And you can handle a wide variety of problems using the functional approach, reducing the amount of lines of code considerably, increasing your productivity and doing better code. Do you remember how to calculate the factorial?, do you remember the factorial example in Python?. Take a look on the PHP implementation against the Python implementation.</p>
<pre class="brush: php;">
&lt;?php

/* PHP factorial example */

function fact($n) {
    if ($n == 0) return 1;
    $r = 1;
    for ($i = 1; $i &lt;= $n; $i++) {
        $r = $r * $i;
    }
    return $r;
}

$f = fact(4);
echo &quot;{$f}\n&quot;;

 ?&gt;
</pre>
<p>Now take a look on the Python implementation. You will notice a multi-paradigm approach using procedural and functional paradigms, using higher order functions again.</p>
<pre class="brush: python;">

### Python factorial example

def fact(n):
    if n == 0: return 1
    return reduce(int.__mul__, xrange(1, n + 1))

print(fact(4))
</pre>
<p>I really like to know how functional programming can allow you to reduce the amount of lines of code which are required to complete certain tasks, and how it is expressive as procedural code does, but it is pretty much well fluent and it has less cyclomatic complexity than the procedural approach. Functional code is very legible. The other advantage is the fact that some compilers supporting the functional paradigm are enabled with <i>tail calls</i> implementation, so you do not need to worry about creating stack frames and generating stack overflows with recursive functions. Languages that currently supports multi-paradigm approach are JavaScript, Python, Ruby and Scala, among other languages.</p>
<p>So, I recommend you that you should start learning some functional programming principles and techniques. On the past I got tired of those companies with silly restrictions about using reductions and making the code looks like literate programming code, instead of well qualified <i>enterprise code</i>, and since I am working as freelancer, I just use the best practices that each language requires.</p>
<p>Do not get stuck in object oriented and procedural paradigms <i>only</i>, learn other paradigms and approaches, so you can handle a wider number of problems reaching better solutions, more optimal in lines of code, cyclomatic complexity, algorithmic complexity and time complexity. In some manner, what I can say is the fact that <i>more lines of code</i> do not means better, it depends on the language that you are using and how do you implement your solutions, and having a multi-paradigm approach can lead you to deliver better code. Sometimes &mdash; certain languages &mdash; can allow you to implement the same solution with less code, you just need to know the proper technique.</p>
<p>Many languages now are including some functional features, and are going multi-paradigm. For example Java 8 has included Lambda Expressions, C# includes Lambda Expressions, they just need to implement Closures to start doing some cool stuff in certain cases. PHP 5.3 now includes Lambda Expressions or Anonymous Functions. So, you should learn about the functional paradigm, among other stuff that will be required in the future.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/11/why-to-go-with-multi-paradigm/">Permalink</a> | <a href="http://coder.cl/2011/11/why-to-go-with-multi-paradigm/#comments">No comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/11/why-to-go-with-multi-paradigm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>instant xml api using pyxser</title>
		<link>http://coder.cl/2011/11/instant-xml-api-using-pyxser/</link>
		<comments>http://coder.cl/2011/11/instant-xml-api-using-pyxser/#comments</comments>
		<pubDate>Sat, 05 Nov 2011 13:42:24 +0000</pubDate>
		<dc:creator>Daniel Molina Wegener</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[pyxser]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=1915</guid>
		<description><![CDATA[Probably you do not understand pyxser at all. It is a serializer and deserializer which converts Python objects into XML as plain text. Among JSON and other formats, XML can help in some tasks like transmitting object through the network, for example building API calls using remote queries. Here I will guide you on how [...]]]></description>
			<content:encoded><![CDATA[<p>Probably you do not understand <a href='http://coder.cl/products/pyxser/' title='Python XML Serialization'>pyxser</a> at all. It is a serializer and deserializer which converts Python objects into XML as plain text. Among JSON and other formats, XML can help in some tasks like transmitting object through the network, for example building API calls using remote queries. Here I will guide you on how to build an XML query API for your Django driven application in few minutes. You just need to understand how <a href='http://coder.cl/products/pyxser/' title='Python XML Serialization'>pyxser</a> works and how to use the pyxser module. Remember that you can see the documentation once it is installed, even if you do not have Internet, just by running the pydoc daemon with <tt>pydoc -p 8080</tt> and connecting to the port <i>8080</i> in your machine &mdash; you can choose another port if it is not working.</p>
<p><span id="more-1915"></span></p>
<p><br/></p>
<h3>tl;dr</h3>
<p>You can setup a query API that throws XML through HTTP under Django using pyxser.</p>
<p><br/></p>
<h3>advice</h3>
<p>All examples here are working, you must be really careful with the authentication and object permissions before using the routines in this post. So, try to wrap those routines correctly using the Django authentication components to filter query requests. Probably OAuth related modules may help. Also the examples are not using the Python and Django best practices, so you need to adjust them to fit the best practices requirements. Finally, do not take all examples very literal, they are just examples and this is just a proof of concept article.</p>
<p><br/></p>
<h3>serializing model objects</h3>
<p>The <a href='http://coder.cl/products/pyxser/' title='Python XML Serialization'>pyxser</a> extension &mdash; which is written in C and uses libxml2 as its basis for XML processing &mdash; has two main arguments for the serialization routines: <tt>obj</tt> and <tt>enc</tt>, where <tt>obj</tt> is the object to be serialized and <tt>enc</tt> is the XML encoding to be used, so you can serialize a <i>valid</i> object using <tt>pyxser.serialize(obj = my_object, enc = 'utf-8')</tt>. You can see the full <a href='http://coder.cl/products/pyxser/' title='Python XML Serialization'>pyxser</a> documentation using the pydoc command and looking forward for the pyxser module.</p>
<p>To serialize Django models, you need to restrict some fields, so you need to filter them, you do not need to worry about processing each model field, you just need to worry to filter the model fields properly using the <tt>selector</tt> argument and the <tt>depth</tt> argument. Take a look on the following decorator.</p>
<pre class="brush: python;">

import pyxser as px

def render_to_xml(**pyxser_args):
    def outer(f):
        @wraps(f)
        def inner_xml(request, *args, **kwargs):

            result = f(request, *args, **kwargs)
            r = HttpResponse(mimetype='text/xml')
            try:
                render = px.serialize(obj=result,
                                      enc='utf-8',
                                      **pyxser_args)
            except Exception, exc:
                render = &quot;&lt;pyxs:obj/&gt;&quot;
            if result:
                r.write(render)
            else:
                r.write(&quot;&lt;pyxs:obj/&gt;&quot;)
            return r
        return inner_xml
    return outer
</pre>
<p>If you apply the decorator above in a Django view, it will return the serialized object as <tt>text/xml</tt> to the HTTP client. So, your view must return a valid object to be serialized by pyxser. It applies the <tt>pyxser.serialize</tt> function to the given output from your view. Now take a look to a view which uses this decorator to throw XML.</p>
<pre class="brush: python;">
def get_class(kls):
    try:
        parts = kls.split('.')
        module = ".".join(parts[:-1])
        m = __import__(module)
        for comp in parts[1:]:
            m = getattr(m, comp)
        return m
    except:
        return False

## use an URL as follows:
## (r'x/g/(?P&lt;model&gt;[\w\.]+)/(?P&lt;oid&gt;\d+)/',
##  u'views_xml.get_model_object'),
@require_http_methods(["GET", "OPTIONS", "HEAD"])
@render_to_xml(selector=do_value_attrs, depth=2)
def get_model_object(request, model=None, oid=None):
    obj = object()
    try:
        db_model = get_class(model)
        obj = db_model.objects.get(pk=oid)
        return obj
    except Exception, exc:
        log.error(exc)
    return obj
</pre>
<p>The view above returns an object from the given model name <tt>model</tt> and the given primary key <tt>oid</tt>, and passes the <tt>do_value_attrs</tt> selector function as attribute selector to pyxser, and restrict the serialization <tt>depth</tt> to two levels. Remember that pyxser allows to serialize circular references and cross references between objects, so we need to restrict the serialization depth, in case of Django models we can work with 2 levels in almost all models and the field selector <tt>do_value_attrs</tt> can be defined as follows.</p>
<pre class="brush: python;">

DENIED_FIELDS = ['user', 'customer', 'users', 'customers']
DENIED_CLASSES = ['Related', 'Foreign', 'Many']

def is_allowed_class(fld):
    for nm in DENIED_CLASSES:
        if nm in fld.__class__.__name__:
            return False
    for nm in DENIED_FIELDS:
        if nm in fld.name:
            return False
    return True

def do_value_attrs(o):
    values = dict()
    if hasattr(o, '_meta') and hasattr(o._meta, 'fields'):
        for fldn in o._meta.fields:
            if is_allowed_class(fldn):
                values[fldn.name] = getattr(o, fldn.name)
    else:
        for kw in o.__dict__:
            values[kw] = getattr(o, kw)
    return values
</pre>
<p>Where we are filtering all fields in model objects that we do not want to serialize and all field classes that pyxser should not serialize for plain object transmision. Other objects which are not model related objects are serialized as plain Python objects using their dictionaries to get the object attributes, and also <tt>DENIED_FIELDS</tt> are skipped and <tt>DENIED_CLASSES</tt> are skipped too. The resulting XML for URLs like <i>/p/x/g/offer.models.Marca/1/</i> is as follows.</p>
<pre class="brush: xml;">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;pyxs:obj xmlns:pyxs="http://projects.coder.cl/pyxser/model/"
          version="1.0"
          type="Marca"
          module="prod.models"
          objid="id3128007116"&gt;
  &lt;pyxs:prop type="unicode" name="nombre" size="4"&gt;Sony&lt;/pyxs:prop&gt;
  &lt;pyxs:prop type="long" name="id"&gt;1&lt;/pyxs:prop&gt;
  &lt;pyxs:prop type="unicode" name="slug" size="4"&gt;sony&lt;/pyxs:prop&gt;
&lt;/pyxs:obj&gt;
</pre>
<p>The pyxser serialization model holds <i>type information</i>, so any serialized object carries <i>type information</i> to be user in deserialization tasks, then you can handle the object back in any machine supporting pyxser and get the object deserialized to its original class using the <tt>unserialize</tt> function.</p>
<p><br/></p>
<h3>defining object containers</h3>
<p>The pyxser extension cannot handle Django model containers directly, I mean those returned by the <tt>all</tt> method in query sets. So, you need to create a plain container to hold those objects that are retrieved from the database. Take a look on following view.</p>
<pre class="brush: python;">
class Container(object):
    count = 0
    items = []
    def __init__(self):
        pass

def collect_filters(qd):
    data = qd.copy()
    filters = dict()
    for kw in data:
        if kw.startswith('filter__'):
            name = kw.replace('filter__', '')
            filters[name] = data[kw]
    return filters

### use an URL as follows:
### (r'x/l/(?P&lt;model&gt;[\w\.]+)/(?P&lt;limit&gt;\d+)/',
###  u'views_xml.get_model_list'),
@require_http_methods(["GET", "OPTIONS", "HEAD"])
@render_to_xml(selector=select_value_attrs, depth=4)
def get_model_list(request, model=None, limit=1):
    container = Container()
    container.count = 0
    container.items = []
    try:
        db_model = get_class(model)
        filters = collect_filters(request.GET)
        objs = db_model.objects.filter(**filters).all()[0:limit]
        container.count = len(objs)
        container.items = map(lambda x: x, objs)
        return container
    except Exception, exc:
        log.error(exc)
    return container
</pre>
<p>If you take a look carefully to this example, you will notice that we are using a very simple <tt>Container</tt> class to hold your objects. The resulting XML for the URL <i>/p/x/l/prod.models.Marca/5/?filter__nombre__contains=son</i> is as follows.</p>
<pre class="brush: xml;">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;pyxs:obj xmlns:pyxs="http://projects.coder.cl/pyxser/model/"
          version="1.0"
          type="Container"
          module="prod.views_xml"
          objid="id3107379372"&gt;
  &lt;pyxs:prop type="int" name="count"&gt;3&lt;/pyxs:prop&gt;
  &lt;pyxs:col type="list" name="items"&gt;
    &lt;pyxs:obj type="Marca" module="prod.models" objid="id3107380204"&gt;
      &lt;pyxs:prop type="unicode" name="nombre" size="5"&gt;Epson&lt;/pyxs:prop&gt;
      &lt;pyxs:prop type="long" name="id"&gt;10&lt;/pyxs:prop&gt;
      &lt;pyxs:prop type="unicode" name="slug" size="5"&gt;epson&lt;/pyxs:prop&gt;
    &lt;/pyxs:obj&gt;
    &lt;pyxs:obj type="Marca" module="prod.models" objid="id3107380300"&gt;
      &lt;pyxs:prop type="unicode" name="nombre" size="8"&gt;Ericsson&lt;/pyxs:prop&gt;
      &lt;pyxs:prop type="long" name="id"&gt;15&lt;/pyxs:prop&gt;
      &lt;pyxs:prop type="unicode" name="slug" size="8"&gt;ericsson&lt;/pyxs:prop&gt;
    &lt;/pyxs:obj&gt;
  &lt;/pyxs:col&gt;
&lt;/pyxs:obj&gt;
</pre>
<p>The resulting XML serialized object holds three Marca objects and all of them have their <tt>type</tt> to be deserialized once they are retrieved. If you want your objects to be deserialized back, you just need to use the <tt>pyxser.unserialize</tt> function properly, which is documented in the pyxser extension itself. I hope that you will like how pyxser works.</p>
<br/><hr height="1px" width="50%" />
<div style='text-align: center !important;'><b>Copyright © 2011 Daniel Molina Wegener</b><br/><b>Atribución-No Comercial-Sin Derivadas 2.0 Chile</b><br/><a target='_new' rel="license" href="http://creativecommons.org/licenses/by-nc-nd/2.0/cl/"><img alt="Creative Commons License" style="border-width:0" src="http://coder.cl.qfl.wpcdn.arcostream.com/cc88x31.png" /></a></div>
<br/><hr height="1px" width="100%" />
<p><small>© Daniel Molina Wegener for <a href="http://coder.cl">coder . cl</a>, 2011. | <a href="http://coder.cl/2011/11/instant-xml-api-using-pyxser/">Permalink</a> | <a href="http://coder.cl/2011/11/instant-xml-api-using-pyxser/#comments">One comment</a><br/>Post tags: <br/></small></p>
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6234432850133541";
/* main-feed */
google_ad_slot = "0763600725";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2011/11/instant-xml-api-using-pyxser/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  coder.cl/category/programming/python/feed/ ) in 0.38746 seconds, on Feb 7th, 2012 at 3:09 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 7th, 2012 at 4:09 am UTC -->
