<?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>Kolios &#187; python</title>
	<atom:link href="http://www.kolios.dk/category/tech/python-tech/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kolios.dk</link>
	<description></description>
	<lastBuildDate>Tue, 31 Aug 2010 11:38:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>How to extend django&#039;s user class and change authentication middleware.</title>
		<link>http://www.kolios.dk/2010/01/22/how-to-extend-django-user-class-and-change-authentication-middleware/</link>
		<comments>http://www.kolios.dk/2010/01/22/how-to-extend-django-user-class-and-change-authentication-middleware/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 12:59:39 +0000</pubDate>
		<dc:creator>sebastien</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.kickban.net/?p=74</guid>
		<description><![CDATA[<img src="http://www.kolios.dk/icons/python-48x48.png" width="48" height="48" alt="" title="python" /><br/>Hi everyone, Welcome for the first edition for python-friday ! This python friday will be dedicated to the so popular django web framework because I really have my hands in it for the time being. Django offers a very nice User class to manage all sort of users, set rights, contact information and so on. [...]]]></description>
			<content:encoded><![CDATA[<img src="http://www.kolios.dk/icons/python-48x48.png" width="48" height="48" alt="" title="python" /><br/><p>Hi everyone,</p>
<p>Welcome for the first edition for python-friday ! This python friday will be dedicated to the so popular django web framework because I really have my hands in it for the time being.</p>
<p>Django offers a very nice User class to manage all sort of users, set rights, contact information and so on. But sometimes, you want to extend that class to add some extra information.</p>
<p>The problem:<br />
You want to use your  &#8211; let&#8217;s call it &#8211; Customer class as the central user class and authenticate using django&#8217;s user modules.</p>
<p>The solution:<br />
Extend the user classs to add your data and configure django framework to use your new class as a middleware and authenticate on it.</p>
<p><span id="more-347"></span></p>
<h3>Extending the class.</h3>
<pre class="brush: python">

from django.contrib.auth.models import User, UserManager

class Customer(User):
	"""
	Model for customer.Hold administrative information
	"""
	company_name = models.CharField('company name', unique=True, max_length = 50)
	tax_number = models.CharField('tax number', max_length = 12)
	address = models.CharField('address line 1', max_length = 200)
	zip_code = models.IntegerField('zip code', max_length = 10)
	city_name = models.CharField('city name', max_length = 20)
	country = models.CharField('country', max_length = 20)
	edited_on = models.DateTimeField(auto_now=True, auto_now_add=True, editable=False)

	# We setup a manager here.. not really sure this is useful
	objects = UserManager()

	def __unicode__(self):
		return self.company_name

	# In the save function, we implement our own password
	# management. If the password is already hashed in the form
	# we just dont change anything otherwise we call the set_password()
	def save(self):
		password = ""
		r = re.compile('sha1\$.*')
		if not r.match(self.password):
			password = self.password
			self.set_password(self.password)
		User.save(self)
</pre>
<p>Now that we have extended the class, we can play a bit with it to see how things goes :</p>
<pre class="brush: python">
> c = Customer()
> c.username = "mms"
> c.lastname = "sauvage"
> c.firstname = "manumanu"
> c.company_name = "the Corp"
#and so on ...
and finally
> c.save()
</pre>
<p>But wait &#8230;. Haven&#8217;t we said that django has its own authentication methods ? Well, how do you want Django framework to know that it has to authenticate against the <em>customer table</em> and <strong>NOT</strong> against django users&#8217; table ?</p>
<p>Well, django can let us redefine the authentication backend. Doing so will then change the authentication behavior the way we want to be.</p>
<h3>Redefining djjango&#8217;s authentication backend.</h3>
<p>First we have to declare our new authenticate backend in the settings.py. While we are in that file, we will also tell django which class to use to authenticate :</p>
<pre name='code' classe='python'>
AUTHENTICATION_BACKENDS = (
    'project.auth_backend.CustomerModelBackend',
)

CUSTOM_USER_MODEL = 'accounts.Customer'
</pre>
<p>We just say here that the backend will be in the file auth_backen.py and the class will be named CustomerModelBackend.</p>
<p>Then create a file called auth-backend.py in your project directory and add it the following content:</p>
<pre  class='brush: python'>
from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_model

class CustomerModelBackend(ModelBackend):
	def authenticate(self, username=None, password=None):
		try:
			user = self.user_class.objects.get(username=username)
			if user.check_password(password):
				return user
		except self.user_class.DoesNotExist:
			return None

	def get_user(self, user_id):
		try:
			return self.user_class.objects.get(pk=user_id)
		except self.user_class.DoesNotExist:
			return None

	@property
	def user_class(self):
		if not hasattr(self, '_user_class'):
			self._user_class = get_model(*settings.CUSTOM_USER_MODEL.split('.', 2))
		if not self._user_class:
			raise ImproperlyConfigured('Could not get custom user model')
		return self._user_class
</pre>
<p>The authentication backend is a class with 2 methods (get_user and authenticate). This is well explained in the documentation of <a href="http://docs.djangoproject.com/en/dev/topics/auth/#specifying-authentication-backends">django framework</a>.</p>
<p>Now we have a Class for our Extended users, an authentication backend that is configured through our settings.py.</p>
<p>Yes ! This is what we want. The most lazy of you can stop here and start coding his favorite user management webapp.</p>
<h3>Syncdb / admin problem.</h3>
<p>But .. wait a minute. Do you remember when you do your first syncdb ? manage.py ask you if you want to fill in an administrator. If you say yes at that point, manage.py will create a <strong>django user</strong> and now that we authenticate on Custome&#8217;s table, there is a lot of chances that the admin module will not authenticate properly (for the admin only though &#8230;).</p>
<p>The solution is to modify the authentication backend to authenticate on django users&#8217; table in case of a failed authentication on customer&#8217;s table.</p>
<pre class="brush: python">
       def authenticate(self, username=None, password=None):
               try:
                        user = self.user_class.objects.get(username=username)
                except self.user_class.DoesNotExist:
                        try:
                                user = User.objects.get(username=username)
                        except User.DoesNotExist:
                                return None
</pre>
<p>As you can see, the code is pretty straight forward and self explanatory. The only tricky part is the &#8220;@property&#8221; but I let you dig into that yourself as you will learn a lot of things if you want to understand it completely.</p>
<p>Et voila !</p>
]]></content:encoded>
			<wfw:commentRss>http://www.kolios.dk/2010/01/22/how-to-extend-django-user-class-and-change-authentication-middleware/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dynamic loading of python module</title>
		<link>http://www.kolios.dk/2010/01/18/dynamic-loading-of-python-module/</link>
		<comments>http://www.kolios.dk/2010/01/18/dynamic-loading-of-python-module/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 09:29:53 +0000</pubDate>
		<dc:creator>sebastien</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.kickban.net/?p=80</guid>
		<description><![CDATA[<img src="http://www.kolios.dk/icons/python-48x48.png" width="48" height="48" alt="" title="python" /><br/>Sometimes ago, a friend of mine recommended me to have a look at python language. Very quickly I got hooked by how easy and developer friendly is that language. The language is straight forward and the number of loadable modules is absolutely amazing. So we go on our python serie with a small piece of [...]]]></description>
			<content:encoded><![CDATA[<img src="http://www.kolios.dk/icons/python-48x48.png" width="48" height="48" alt="" title="python" /><br/><p>Sometimes ago, a <a href="http://manu.manusauvage.com" title="manusavage's blog">friend of mine</a> recommended me to have a look at python language. Very quickly I got hooked by how easy and developer friendly is that language. The language is straight forward and the number of <a href="http://pypi.python.org/pypi" title="python package index">loadable modules</a> is absolutely amazing.</p>
<p>So we go on our python serie with a small piece of code that could be useful for python developers who want to dynamically load &#8216;packages&#8217; (called on the fly import)</p>
<p><em>The problem:</em><br />
Being able to load dynamically (at runtime) some packages to extend your code.</p>
<p><em>Solution:</em><br />
in all this tutorial, we will use the so unfamous <a href='http://docs.python.org/library/functions.html#__import__' title='python __import__ function'>__import__</a> python builtin.<br />
<span id="more-348"></span><br />
First, let&#8217;s create a package that we can &#8220;autoload&#8221;.<br />
In fact, it will be a regular (and respectful) package like there is tons for python. A package is a piece of code that realize a specific task. It has also a well defined structure.</p>
<p>The structure of the package will be as follow :<br />
<code><br />
package_name:<br />
		-> __init__.py<br />
		-> mymodule.py<br />
</code></p>
<p>First the file <em>__init__.py</em> is a mandatory file that tells that your directory is in fact a package. The file <em>mymodule.py</em> is a regular python script that contain the class that we want to use.</p>
<p>Here is the code of these two file.</p>
<p>The first file (<em>__init__.py</em>)</p>
<pre class='brush: python'>
"""
This modules should keep help use in the future
"""
__author__ = "sebastien requiem (kolios.dk)"
__license__ = "No License"
__version__ = "0.0.1"

from .mymodule import MyModule

def instantiate():
	return MyModule()
</pre>
<p>and the python module code itself (<em>mymodule.py</em>)</p>
<pre class='brush: python'>
import os
import logging

class MyModule:
	"""
	This class is a very cool and helpful class
	"""
	def __init__(self):
		print "We are initializing MyModule.. w00t !"

	def mymethod(self):
		"""
		Simple routines
		"""
		print "mymethod has been called"
</pre>
<p>As you can see, there is no fancy code here. Just note that the <em>__init__.py</em> script contain a function call <em>instantiate</em> and that return an instance of the class that we need.<br />
Now let&#8217;s see how we can make use of that module.</p>
<p>The following piece of code is meant to be used in a production environment but gives you a clear view on how to load dynamically.</p>
<pre class='brush: python'>
import sys
#first we make sure that the current path is in our path.
	sys.path.append(0, '.')

# we need a placeholder for all our modules
	modules ={}
# we define a list of modules we want to load
	module_list = []
	module_list.append('mymodule')

	for module_name in module_list:
		try:
			modules[module_name] =  __import__(module_name)
			print "Successfully loaded module : %s" % module_name
		except ImportError, e:
			print e
			print "can't load %s module" % module_name)
</pre>
<p>That&#8217;s is folks, as simple as that. Let me know in the comments all the troubles you can have with that piece of code. As I am not a python expert, let me know any improvements and ideas you can have regarding this subject.</p>
<p>For those who want to <em>unload</em> any module, you should be able to do it by deleting the key in <em>sys.modules</em> but I must admit that I haven&#8217;t been able to notice any memory improvement after having released any modules. Does that really works ?</p>
<p>See ya !</p>
<p>references:</p>
<ol>
<li>the __import__ python function : <a href='http://docs.python.org/library/functions.html#__import__' title='python __import__ function'>http://docs.python.org/library/functions.html#__import__</a></li>
<li>Python package structure : <a href='http://docs.python.org/tutorial/modules.html' title='python module tutorial'>http://docs.python.org/tutorial/modules.html</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.kolios.dk/2010/01/18/dynamic-loading-of-python-module/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
