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

<channel>
	<title>The Braindonor Network &#187; SQLAlchemy</title>
	<atom:link href="http://www.braindonor.net/tag/sqlalchemy/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.braindonor.net</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Tue, 01 Jun 2010 17:42:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>SQLAlchemy and memcached</title>
		<link>http://www.braindonor.net/coding-blog/sqlalchemy-and-memcached/151/</link>
		<comments>http://www.braindonor.net/coding-blog/sqlalchemy-and-memcached/151/#comments</comments>
		<pubDate>Thu, 12 Mar 2009 03:27:54 +0000</pubDate>
		<dc:creator>John Hoff</dc:creator>
				<category><![CDATA[Coding Blog]]></category>
		<category><![CDATA[memcached]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[SQLAlchemy]]></category>

		<guid isPermaLink="false">http://www.braindonor.net/?p=151</guid>
		<description><![CDATA[I think it is safe to say that my personal goal of learning and using Python this winter has been a huge success! I have now found myself hard at work on a large Python-based project in my spare time and investigating issues that I haven't been able to track down much documentation on. How [...]]]></description>
			<content:encoded><![CDATA[I think it is safe to say that my personal goal of learning and using Python this winter has been a huge success!  I have now found myself hard at work on a large Python-based project in my spare time and investigating issues that I haven't been able to track down much documentation on.  How to use Memcached in conjunction with SQLAlchemy was one of those issues.<span id="more-151"></span><br /><br />

<b>Making Sure Everything Is Ready</b><br />
Nearly all of the trouble I encountered with SQLAlchemy boiled down to how I initialized my objects.  For a given mapped object, how I am doing things in my projects now is:
<ol>
<li>Create the engine</li>
<li>Create the schema metadata</li>
<li>Bind the engine to the MetaData</li>
<li>Declare the orm class to be mapped</li>
<li>Create the schema table to be mapped</li>
<li>Create the orm mapping</li>
<li>Bind and the orm mapping to the schema table</li>
<li>Compile the bound orm mapping</li>
</ol>

<b>Leaving The Session Behind</b><br />
One of the first things I attempted to do in my web application with SQLAlchemy was detach a mapped object from the session and store it accross page requests.  I wanted to detach the object from the session context to separate class inheritance from the context of the child and avoid the thread-safety dangers of the session.<br /><br />

<code>class DetachedORMObject(object):
    @classmethod
    def fetch_by_field(cls, field, value):
        session = SESSION()
        try:
            class_object = session.query(cls).filter(field == value).one()
        except sqlalchemy.orm.exc.NoResultFound:
            class_object = None
        finally:
            session.close()
        return class_object</code><br />

The above code works when a common sessionmaker, SESSION, has been defined in the module.  It provides the ability to create a whole collection of utility tasks to be used in implementation.  For my purposes, it allowed for a common path for fetching orm objects from the database that could be overridden in the inheritance chain.<br /><br />

The issue I ran into with the above code dealt with related tables.  The default behavior for SQLAlchemy is for related table attributes to be lazy-loaded.  Once the orm object has been detached from session, the related attribute no longer has the ability to fetch the related data from the database.  This can be fixed by disabling the lazy loading of relations in mappings that are going to be disconnected.<br /><br />

<code>UserTable.mapper = mapper(User, UserTable, \
    properties = { 'user_status': relation(UserStatus, lazy=False)})</code><br />

<b>Serial Killer</b><br />
Now that I had objects being detached from the session successfully, I needed to start serializing them.  My goal for serialization is to store the orm objects in memcached.  We can avoid the extra complexity of introducing memcached into the mix at this point by using cpickle for testing.  This is the same package that python-memcached uses to serialize objects as it interacts with a memcached server.<br /><br />

Initially, I thought pickling worked like a charm.  I was able to pickle an object to a string and load it again without encountering errors.  Once I tried to interact with the attributes of the object, I started getting AttributeError exceptions.  After doing some digging, I discovered that the mapping was broken when we attempted to unpickle the object.  The solution was to explicitly compile the mapping.<br /><br />

<code>UserTable.mapper = mapper(User, UserTable, \
    properties = { 'user_status': relation(UserStatus, lazy=False)})
UserTable.mapper.compile()</code><br />

The compilation step is not included in the tutorials in the SQLAlchemy documentation.  It is implicitly invoked when python interacts with the mapped object through the SQLAlchemy API.  In fact, if program that is un-pickling loads a seperate object first, an AttributeError exception will not be thrown.  By explicitly compiling the mapping, we ensure that pickling can occur successfully before the SQLAlchemy API is called.<br /><br />

<b>Who's Object is it Anyway?</b><br />
The final issue I encountered was in finding a method to generate a instance key in a generic fashion.  While including abstract methods forcing child classes to provide instance keys to the parent class would work, I wanted a more elegant solution.  Investigating the SQLAlchemy internals pointed me in the direction of the class manager for the mapped objects.  It links the orm objects to the mapper, with in turn links it to the metadata.  I can update the fetch_by_field method as follows:<br /><br />

<code>    @classmethod
    def fetch_by_field(cls, field, value):
        """Fetch the requested object from the cache and database"""
        orm_object = None
        matched_primary_key = True
        for key in cls._sa_class_manager.mapper.primary_key:
            if field.key != key.key:
                matched_primary_key = False
        if matched_primary_key:
            orm_object = cls.get_cached_instance('(' + str(value) + ')')
        if orm_object is None:
            orm_object = super(MemcachedORMObject, cls). \
                fetch_by_field(field, value)
            if orm_object is not None:
                orm_object.set_cached_instance()
        return orm_object</code><br />

The method first compares the field to the primary key collection in the mapper.  If it is found, it attempts to fetch the cached value.  If not found, it fetches it using the parent fetch_by_field and adds it to the cache.  It should be noted that I am converting the field value to a string when creating the instance key.  A long integer column will append the letter L to the end of __repr__, but not __str__.  Because of this discrepancy, keys may not match between the initial set and subsequent get unless the conversion is explicitly handled.<br /><br />

<b>Putting it All Together</b><br />
with all of the issues handled, it's time include memcached in the mix.  My solution was to a set of classes that mapped objects can inherit to include the necessary caching behavior.
<ul>
<li><b>DetachedORMObject</b><br />Implements a generic fetch_by_field as well as the necessary db synchronization tasks.  All session handling in the dependency chain is done here.<br /><br /></li>
<li><b>MemcachedObject</b><br />Abstract class that has the ability to save and restore itself from memcached.<br /><br /></li>
<li><b>MemcachedORMObject</b><br />Implements both DetachedORMObject and MemcachedObject.  Contains the instance key management logic.</li>
</ul>

<b>Final Notes</b><br />
I have included a tarball of example scripts that show the full interaction with memcached.  I pulled the database classes straight out of my application, and verified that all of the issues were repeatable using SQLite instead of PostgreSQL.<br /><br />

In my own implementation, I included classes to implement an optional second level of caching using resident memory. I also included a separate class hierarchy covering read-only database objects as well as object collections.]]></content:encoded>
			<wfw:commentRss>http://www.braindonor.net/coding-blog/sqlalchemy-and-memcached/151/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Updated mod_python Mako Handler</title>
		<link>http://www.braindonor.net/projects/updated-mod_python-mako-handler/127/</link>
		<comments>http://www.braindonor.net/projects/updated-mod_python-mako-handler/127/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 17:43:43 +0000</pubDate>
		<dc:creator>John Hoff</dc:creator>
				<category><![CDATA[Coding Blog]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[Mako]]></category>
		<category><![CDATA[mod_python]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SQLAlchemy]]></category>

		<guid isPermaLink="false">http://www.braindonor.net/?p=127</guid>
		<description><![CDATA[I have been using the mod_python handler to parse Mako templates for about a month now in a personal project. As I have done more and more development on my project, I have naturally encountered shortcomings and errors in my handler. The first thing I encountered when using the handler was the incorrect status being [...]]]></description>
			<content:encoded><![CDATA[I have been using the mod_python handler to parse Mako templates for about a month now in a personal project.  As I have done more and more development on my project, I have naturally encountered shortcomings and errors in my handler.<span id="more-127"></span><br /><br />

The first thing I encountered when using the handler was the incorrect status being returned after a template was parsed.  Initially, I was not aware of the 500 status attached to all of the responses because the content came through correctly.  Once I started to implement some AJAX features, everything came crashing down.  While content was indeed returned, the ajax request looked at the status in the response header first, and started erring out all of my AJAX calls.  I tracked this down to how I was previously setting the status so that it could be updated inside of the template:<br /><br />

<code>req.status = apache.OK
req.write(template.render(req=req))
return req.status</code><br />

After some digging, I discovered that the reason for the 500 status was that I was attempting to set the status of the request.  Instead of attempting to use the request status, I needed to make a temporary place-holder:<br /><br />

<code>req.mako_status = apache.OK
req.write(template.render(req=req))
return req.mako_status</code><br />

After that fix, it was smooth sailing until I started integrating <a href="http://www.sqlalchemy.org/" target="_blank">SQLAlchemy</a> into my application.  The moment I imported SQLAlchemy into my template file, mod_python started throwing error pages concerning the directory to cache eggs into.  Because I had already been testing my ORM objects through the command line, this came as a surprise.  The quick fix was to create a directory for it, and add it to the environment from within the handler.  Once that was done, everything imported cleanly.<br /><br />

Now that I had my ORM objects imported, it was time to use them.  As i was implementing a form-handling routine, I ran into another issue.  When I passed in the raw value from the util.FieldStorage object provided by mod_python, I started receiving ProgrammingError exceptions from SQLAlchemy indicating that it was unable to adapt the select statements.  After some digging, I found one little reference pointing back to the behavior of FieldStorage.  I found the reason for the error <a href="http://osdir.com/ml/python.sqlalchemy.user/2006-08/msg00084.html" target="_blank">here</a>.  FieldStorage was returning StringField objects instead of raw strings when I parsed the form inputs.  When I placed those into the orm calls, it was unable to perform the needed type-matches.  For the solution, I created a wrapper object for FieldStorage to implement some additional methods that <i>did</i> return string values.<br /><br />]]></content:encoded>
			<wfw:commentRss>http://www.braindonor.net/projects/updated-mod_python-mako-handler/127/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
