<?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 Mouse Vs. The Python &#187; SqlAlchemy</title>
	<atom:link href="http://www.blog.pythonlibrary.org/tag/sqlalchemy/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.blog.pythonlibrary.org</link>
	<description>Python Programming from the Frontlines</description>
	<lastBuildDate>Sun, 08 Jan 2012 12:45:28 +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>Improving MediaLocker: wxPython, SQLAlchemy, and MVC</title>
		<link>http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/</link>
		<comments>http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/#comments</comments>
		<pubDate>Thu, 01 Dec 2011 02:26:54 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Education]]></category>
		<category><![CDATA[SqlAlchemy]]></category>
		<category><![CDATA[wxPython]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=2092</guid>
		<description><![CDATA[This blog ran an article about wxPython, SQLAlchemy, CRUD and MVC earlier this month. The program that we created in that post was dubbed &#8220;MediaLocker&#8221;, whether or not it was explicitly stated as such. Anyway, since then, I have received a couple comments about improving the program. One came from Michael Bayer, one of the [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/" data-url="http://bit.ly/vJC7nC" data-text="Improving MediaLocker: wxPython, SQLAlchemy, and MVC" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/";
			reddit_title = "Improving MediaLocker: wxPython, SQLAlchemy, and MVC";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/"></g:plusone></div></div><p>This blog ran an article about wxPython, SQLAlchemy, CRUD and MVC earlier this month. The program that we created in that post was dubbed &#8220;MediaLocker&#8221;, whether or not it was explicitly stated as such. Anyway, since then, I have received a couple comments about improving the program. One came from <a href="http://techspot.zzzeek.org/" target="_blank">Michael Bayer</a>, one of the creative minds behind SQLAlchemy itself and the other comments came from Werner Bruhin, a nice guy who haunts the wxPython mailing list, helping new users. So I went about creating an improved version of the code following their advice. Werner then improved it a bit more. So in this article, we will be looking at improving the code, first with my example and then with his. Enough talk though; let&#8217;s get to the meat of story!<span id="more-2092"></span></p>
<h2>Making MediaLocker Better</h2>
<p>Michael Bayer and Werner Bruhin both thought that I should only connect to the database once as that&#8217;s a fairly &#8220;expensive&#8221; operation. This could be an issue if there were multiple sessions existing at the same time too, but even in my original code, I made sure to close the session so that wouldn&#8217;t happen. When I wrote my original version, I thought about separating out the session creation, but ended up going with what I thought was more straightforward. To fix this niggling issue, I changed the code so that I passed the session object around instead of constantly calling my controller&#8217;s <strong>connectToDatabase</strong> function. You can read more about Sessions <a href="http://www.sqlalchemy.org/docs/orm/session.html?highlight=session" target="_blank">here</a>. See the code snippet from <strong>mediaLocker.py</strong>:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">class</span> BookPanel<span style="color: black;">&#40;</span>wx.<span style="color: black;">Panel</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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>, parent<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        wx.<span style="color: black;">Panel</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, parent<span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">exists</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;devdata.db&quot;</span><span style="color: black;">&#41;</span>:
            controller.<span style="color: black;">setupDatabase</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #008000;">self</span>.<span style="color: black;">session</span> = controller.<span style="color: black;">connectToDatabase</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">try</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">bookResults</span> = controller.<span style="color: black;">getAllRecords</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">session</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">except</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">bookResults</span> = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span></pre>
<p>Note that we have a little conditional right up front that will create the database if it doesn&#8217;t already exist. Next I create the session object in the main GUI as a property of the panel sub-class. Then I pass it where ever I need to. One example can be seen above where I pass the session object to the controller&#8217;s <strong>getAllRecords</strong> method. </p>
<p>Another big change was to remove the ObjectListView model from <strong>model.py</strong> and just use the SQLAlchemy table class instead:</p>
<pre class="python"><span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Book<span style="color: black;">&#40;</span>DeclarativeBase<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">&quot;book&quot;</span>
&nbsp;
    <span style="color: #008000;">id</span> = Column<span style="color: black;">&#40;</span>Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    author_id = Column<span style="color: black;">&#40;</span>Integer, ForeignKey<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;person.id&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    title = Column<span style="color: black;">&#40;</span>Unicode<span style="color: black;">&#41;</span>
    isbn = Column<span style="color: black;">&#40;</span>Unicode<span style="color: black;">&#41;</span>
    publisher = Column<span style="color: black;">&#40;</span>Unicode<span style="color: black;">&#41;</span>
    person = relation<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Person&quot;</span>, backref=<span style="color: #483d8b;">&quot;books&quot;</span>, cascade_backrefs=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
&nbsp;
    @<span style="color: #008000;">property</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> author<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;">return</span> <span style="color: #483d8b;">&quot;%s %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">person</span>.<span style="color: black;">first_name</span>, <span style="color: #008000;">self</span>.<span style="color: black;">person</span>.<span style="color: black;">last_name</span><span style="color: black;">&#41;</span></pre>
<p>This is actually mostly the same as the original class except that it uses SQLAlchemy constructs. I also needed to add a special property to return the author&#8217;s full name for display in our widget, so we used Python&#8217;s built-in function: <a href="http://docs.python.org/library/functions.html#property" target="_blank">property</a> which returns a property attribute. It&#8217;s easier to understand if you just look at the code. As you can see, we applied <strong>property </strong>as a decorator to the <strong>author </strong>method.</p>
<h2>Werner&#8217;s Additions</h2>
<p>Werner&#8217;s additions are mostly adding more explicit imports in the model. The biggest change in the model is as follows:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>
<span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #008000;">hasattr</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>, <span style="color: #483d8b;">'frozen'</span><span style="color: black;">&#41;</span>:
    <span style="color: #808080; font-style: italic;"># needed when having multiple versions of SA installed</span>
    <span style="color: #ff7700;font-weight:bold;">import</span> pkg_resources
    pkg_resources.<span style="color: black;">require</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sqlalchemy&quot;</span><span style="color: black;">&#41;</span> <span style="color: #808080; font-style: italic;"># get latest version</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">import</span> sqlalchemy as sa
<span style="color: #ff7700;font-weight:bold;">import</span> sqlalchemy.<span style="color: black;">orm</span> as sao
<span style="color: #ff7700;font-weight:bold;">import</span> sqlalchemy.<span style="color: black;">ext</span>.<span style="color: black;">declarative</span> as sad
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">ext</span>.<span style="color: black;">hybrid</span> <span style="color: #ff7700;font-weight:bold;">import</span> hybrid_property
&nbsp;
maker = sao.<span style="color: black;">sessionmaker</span><span style="color: black;">&#40;</span>autoflush=<span style="color: #008000;">True</span>, autocommit=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
DBSession = sao.<span style="color: black;">scoped_session</span><span style="color: black;">&#40;</span>maker<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Base<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Extend the base class
&nbsp;
    - Provides a nicer representation when a class instance is printed.
        Found on the SA wiki, not included with TG
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><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;">return</span> <span style="color: #483d8b;">&quot;%s(%s)&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>
                 <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.__class__.__name__<span style="color: black;">&#41;</span>,
                 <span style="color: #483d8b;">', '</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;%s=%r&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>key, <span style="color: #008000;">getattr</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, key<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
                            <span style="color: #ff7700;font-weight:bold;">for</span> key <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">sorted</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: #0000cd;">__dict__</span>.<span style="color: black;">keys</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
                            <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> key.<span style="color: black;">startswith</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'_'</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
DeclarativeBase = sad.<span style="color: black;">declarative_base</span><span style="color: black;">&#40;</span>cls=Base<span style="color: black;">&#41;</span>
metadata = DeclarativeBase.<span style="color: black;">metadata</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> init_model<span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Call me before using any of the tables or classes in the model.&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    DBSession.<span style="color: black;">configure</span><span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span></pre>
<p>The first few lines are for people with SetupTools / easy_install on their machine. If the user has multiple versions of SQLALchemy installed, it will force it to use the latest. Most of the other imports are shortened to make it very obvious where various classes and attributes come from. I am honestly not familiar with the <strong>hybrid_property</strong>, so here&#8217;s what its docstring had to say:</p>
<p><em>A decorator which allows definition of a Python descriptor with both instance-level and class-level behavior.</em></p>
<p>You can read more here: <a href="http://www.sqlalchemy.org/docs/orm/extensions/hybrid.html" target="_blank">http://www.sqlalchemy.org/docs/orm/extensions/hybrid.html</a></p>
<p>Werner also added a little <strong>__repr__</strong> method to the Base class to make it return a better representation of the class instance when it&#8217;s printed, which is handy for debugging. Finally, he added a function called <strong>init_model</strong> to initialize the model.</p>
<h2>Wrapping Up</h2>
<p>Now you should know that Werner and I have decided to make MediaLocker into an example of a wxPython database-enabled application. He&#8217;s been doing a bunch of work on it since the simple edits I mentioned above. We&#8217;ll be making an official announcement about that soon. In the mean time, I hope that this has helped open your eyes to some fun ways to enhance a project and clean it up a bit. It is my plan to add lots of new features to this program and chronicle those on this blog in addition to all my other articles.</p>
<h2>Source Code</h2>
<ul>
<li><a href='http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/wxSa2.zip'>wxSa2.zip</a></li>
<li><a href='http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/wxSa2.tar'>wxSa2.tar</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2011/11/30/improving-medialocker-wxpython-sqlalchemy-and-mvc/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>wxPython and SqlAlchemy: An Intro to MVC and CRUD</title>
		<link>http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/</link>
		<comments>http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 04:15:35 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Education]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[SqlAlchemy]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=2035</guid>
		<description><![CDATA[In this article, we will be creating a program to store our personal books or perhaps just the books you&#8217;ve read. It will demonstrate how to combine wxPython and SqlAlchemy, a SQL Object Relational Mapper (ORM). This program will also give you an introduction to the model-view-controller (MVC) and &#8220;create, read, update and destroy&#8221; (CRUD) [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/" data-url="http://bit.ly/tNneVU" data-text="wxPython and SqlAlchemy: An Intro to MVC and CRUD" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/";
			reddit_title = "wxPython and SqlAlchemy: An Intro to MVC and CRUD";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/"></g:plusone></div></div><p>In this article, we will be creating a program to store our personal books or perhaps just the books you&#8217;ve read. It will demonstrate how to combine wxPython and SqlAlchemy, a SQL Object Relational Mapper (ORM). This program will also give you an introduction to the model-view-controller (MVC) and &#8220;create, read, update and destroy&#8221; (CRUD) methodologies. The aim is to show you how to create an application that can do the following:</p>
<ul>
<li>Create a database (create)</li>
<li>Add records to that database (sort of create)</li>
<li>Display the records (read and view)</li>
<li>Modify records (update)</li>
<li>Delete records (destroy)</li>
</ul>
<p>The order of this tutorial will follow MVC, so we will start with the model. The model is the basis for the GUI (the View) anyway, so it&#8217;s a good place to start.<span id="more-2035"></span></p>
<h2>Prerequisites</h2>
<p>Before we jump into the model section, you may need to download some extras to follow along. Here&#8217;s what you&#8217;ll need:</p>
<ul>
<li>Python 2.5 or better, but not 3.x</li>
<li><a href="http://www.wxpython.org/" target="_blank">wxPython </a>>= 2.8.10.1</li>
<li><a href="http://www.sqlalchemy.org/" target="_blank">SqlAlchemy </a>>= 0.5.0</li>
<li><a href="http://pypi.python.org/pypi/ObjectListView" target="_blank">ObjectListView</a></li>
</ul>
<p>Once you have all those installed, you&#8217;re ready to move on to the next section!</p>
<h2>The Model</h2>
<p>Our model contains our SqlAlchemy database classes and a model for our ObjectListView widget, which we&#8217;ll be using to display our data later. The SqlAlchemy classes are using the <a href="http://www.sqlalchemy.org/docs/orm/extensions/declarative.html" target="_blank">Declarative system</a>, which combines the table creation and the class creation. It&#8217;s a little easier to understand if you just take a look at the code.</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># model.py</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Table, Column, create_engine
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Integer, ForeignKey, String, Unicode
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">ext</span>.<span style="color: black;">declarative</span> <span style="color: #ff7700;font-weight:bold;">import</span> declarative_base
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> backref, relation
&nbsp;
engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sqlite:///devdata.db&quot;</span>, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
DeclarativeBase = declarative_base<span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span>
metadata = DeclarativeBase.<span style="color: black;">metadata</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> OlvBook<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Book model for ObjectListView
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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>, <span style="color: #008000;">id</span>, title, author, isbn, publisher, last_name, first_name<span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: #008000;">id</span> = <span style="color: #008000;">id</span>  <span style="color: #808080; font-style: italic;"># unique row id from database</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">title</span> = title
        <span style="color: #008000;">self</span>.<span style="color: black;">author</span> = author
        <span style="color: #008000;">self</span>.<span style="color: black;">isbn</span> = isbn
        <span style="color: #008000;">self</span>.<span style="color: black;">publisher</span> = publisher
        <span style="color: #008000;">self</span>.<span style="color: black;">last_name</span> = last_name
        <span style="color: #008000;">self</span>.<span style="color: black;">first_name</span> = first_name
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Person<span style="color: black;">&#40;</span>DeclarativeBase<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">&quot;people&quot;</span>
&nbsp;
    <span style="color: #008000;">id</span> = Column<span style="color: black;">&#40;</span>Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    first_name = Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;first_name&quot;</span>, String<span style="color: black;">&#40;</span><span style="color: #ff4500;">50</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    last_name = Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;last_name&quot;</span>, String<span style="color: black;">&#40;</span><span style="color: #ff4500;">50</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot;&lt;Person: %s %s&gt;&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">first_name</span>, <span style="color: #008000;">self</span>.<span style="color: black;">last_name</span><span style="color: black;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Book<span style="color: black;">&#40;</span>DeclarativeBase<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">&quot;books&quot;</span>
&nbsp;
    <span style="color: #008000;">id</span> = Column<span style="color: black;">&#40;</span>Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    author_id = Column<span style="color: black;">&#40;</span>Integer, ForeignKey<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;people.id&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    title = Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;title&quot;</span>, Unicode<span style="color: black;">&#41;</span>
    isbn = Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;isbn&quot;</span>, Unicode<span style="color: black;">&#41;</span>
    publisher = Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;publisher&quot;</span>, Unicode<span style="color: black;">&#41;</span>
    person = relation<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Person&quot;</span>, backref=<span style="color: #483d8b;">&quot;books&quot;</span>, cascade_backrefs=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
&nbsp;
metadata.<span style="color: black;">create_all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>We&#8217;re not going to spend a lot of time parsing this code as there are several SqlAlchemy tutorials out there and the SqlAlchemy documentation is really good. Instead, we&#8217;ll just give a quick overview. The beginning of the code imports all the SqlAlchemy stuff we need. One of the most important bits is where create the engine:</p>
<pre class="python">engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sqlite:///devdata.db&quot;</span>, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span></pre>
<p>This means that we&#8217;ll be creating a SQLite database in the same directory as the model is in. You can pass a path in too, like this: <strong>create_engine(&#8220;sqlite:///c:/path/to/devdata.db&#8221;)</strong> and you can name the database whatever you want, including the extension. The <strong>echo</strong> parameter is turned on for debugging purposes. It will output all the SQL that SqlAlchemy issues so we can use it to figure out our queries or issues that may crop up when we create the database.</p>
<p>The first class we encounter is <strong>OlvBook</strong>, which defines a book class. We&#8217;ll be using that later to help us populate the previously mentioned ObjectListView widget that we will use to display our records. The next two classes are called <strong>Person</strong> and <strong>Book</strong>, respectively. The tablename is defined by the magic method: __tablename__. Person is a ForeignKey in Book, which we use for our Author. Originally, I thought I could use Person to add multiple authors or other people related to the book, like the artist. Or maybe for the Songwriter for one of my CDs, but I decided to just keep it simple instead. You can enhance this model a little to make it more polymorphic so it can behave in that way though. </p>
<p>Anyway, if you run this script, it will execute the last line: <strong>metadata.create_all()</strong> This causes the database file to be created with those two tables defined. Now we&#8217;re ready to add data to it. But first, we need to take a look at the View!</p>
<h2>The View</h2>
<p><a href="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/media_organizer.png"><img src="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/media_organizer-300x113.png" alt="" title="media_organizer" width="300" height="113" class="aligncenter size-medium wp-image-2044" /></a></p>
<p>The View is our wxPython interface that we will use to display the records as well as filter, add, modify and delete them. The code for our GUI is just over 150 lines long. Let&#8217;s take a look!</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> addModRecord
<span style="color: #ff7700;font-weight:bold;">import</span> commonDlgs
<span style="color: #ff7700;font-weight:bold;">import</span> controller
<span style="color: #ff7700;font-weight:bold;">import</span> wx
<span style="color: #ff7700;font-weight:bold;">from</span> ObjectListView <span style="color: #ff7700;font-weight:bold;">import</span> ObjectListView, ColumnDefn
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> BookPanel<span style="color: black;">&#40;</span>wx.<span style="color: black;">Panel</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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>, parent<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        wx.<span style="color: black;">Panel</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, parent<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">try</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">bookResults</span> = controller.<span style="color: black;">getAllRecords</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">except</span>:
            <span style="color: #008000;">self</span>.<span style="color: black;">bookResults</span> = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
&nbsp;
        mainSizer = wx.<span style="color: black;">BoxSizer</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">VERTICAL</span><span style="color: black;">&#41;</span>
        searchSizer = wx.<span style="color: black;">BoxSizer</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">HORIZONTAL</span><span style="color: black;">&#41;</span>
        btnSizer = wx.<span style="color: black;">BoxSizer</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">HORIZONTAL</span><span style="color: black;">&#41;</span>
        font = wx.<span style="color: black;">Font</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span>, wx.<span style="color: black;">SWISS</span>, wx.<span style="color: black;">NORMAL</span>, wx.<span style="color: black;">BOLD</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;"># create the search related widgets</span>
        cat = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;Author&quot;</span>, <span style="color: #483d8b;">&quot;Title&quot;</span>, <span style="color: #483d8b;">&quot;ISBN&quot;</span>, <span style="color: #483d8b;">&quot;Publisher&quot;</span><span style="color: black;">&#93;</span>
        searchByLbl = wx.<span style="color: black;">StaticText</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=<span style="color: #483d8b;">&quot;Search By:&quot;</span><span style="color: black;">&#41;</span>
        searchByLbl.<span style="color: black;">SetFont</span><span style="color: black;">&#40;</span>font<span style="color: black;">&#41;</span>
        searchSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>searchByLbl, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #008000;">self</span>.<span style="color: black;">categories</span> = wx.<span style="color: black;">ComboBox</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, value=<span style="color: #483d8b;">&quot;Author&quot;</span>, choices=cat<span style="color: black;">&#41;</span>
        searchSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">categories</span>, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #008000;">self</span>.<span style="color: black;">search</span> = wx.<span style="color: black;">SearchCtrl</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, style=wx.<span style="color: black;">TE_PROCESS_ENTER</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">search</span>.<span style="color: black;">Bind</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">EVT_TEXT_ENTER</span>, <span style="color: #008000;">self</span>.<span style="color: black;">onSearch</span><span style="color: black;">&#41;</span>
        searchSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">search</span>, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #008000;">self</span>.<span style="color: black;">bookResultsOlv</span> = ObjectListView<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, style=wx.<span style="color: black;">LC_REPORT</span>
                                                        |wx.<span style="color: black;">SUNKEN_BORDER</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">bookResultsOlv</span>.<span style="color: black;">SetEmptyListMsg</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;No Records Found&quot;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">setBooks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;"># create the button row</span>
        addRecordBtn = wx.<span style="color: black;">Button</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=<span style="color: #483d8b;">&quot;Add&quot;</span><span style="color: black;">&#41;</span>
        addRecordBtn.<span style="color: black;">Bind</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">EVT_BUTTON</span>, <span style="color: #008000;">self</span>.<span style="color: black;">onAddRecord</span><span style="color: black;">&#41;</span>
        btnSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>addRecordBtn, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
&nbsp;
        editRecordBtn = wx.<span style="color: black;">Button</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=<span style="color: #483d8b;">&quot;Edit&quot;</span><span style="color: black;">&#41;</span>
        editRecordBtn.<span style="color: black;">Bind</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">EVT_BUTTON</span>, <span style="color: #008000;">self</span>.<span style="color: black;">onEditRecord</span><span style="color: black;">&#41;</span>
        btnSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>editRecordBtn, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
&nbsp;
        deleteRecordBtn = wx.<span style="color: black;">Button</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=<span style="color: #483d8b;">&quot;Delete&quot;</span><span style="color: black;">&#41;</span>
        deleteRecordBtn.<span style="color: black;">Bind</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">EVT_BUTTON</span>, <span style="color: #008000;">self</span>.<span style="color: black;">onDelete</span><span style="color: black;">&#41;</span>
        btnSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>deleteRecordBtn, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
&nbsp;
        showAllBtn = wx.<span style="color: black;">Button</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=<span style="color: #483d8b;">&quot;Show All&quot;</span><span style="color: black;">&#41;</span>
        showAllBtn.<span style="color: black;">Bind</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">EVT_BUTTON</span>, <span style="color: #008000;">self</span>.<span style="color: black;">onShowAllRecord</span><span style="color: black;">&#41;</span>
        btnSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>showAllBtn, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
&nbsp;
        mainSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>searchSizer<span style="color: black;">&#41;</span>
        mainSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">bookResultsOlv</span>, <span style="color: #ff4500;">1</span>, wx.<span style="color: black;">ALL</span>|wx.<span style="color: black;">EXPAND</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
        mainSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>btnSizer, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">CENTER</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">SetSizer</span><span style="color: black;">&#40;</span>mainSizer<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> onAddRecord<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Add a record to the database
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        dlg = addModRecord.<span style="color: black;">AddModRecDialog</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        dlg.<span style="color: black;">ShowModal</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        dlg.<span style="color: black;">Destroy</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">showAllRecords</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> onEditRecord<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Edit a record
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        selectedRow = <span style="color: #008000;">self</span>.<span style="color: black;">bookResultsOlv</span>.<span style="color: black;">GetSelectedObject</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> selectedRow == <span style="color: #008000;">None</span>:
            commonDlgs.<span style="color: black;">showMessageDlg</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;No row selected!&quot;</span>, <span style="color: #483d8b;">&quot;Error&quot;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">return</span>
        dlg = addModRecord.<span style="color: black;">AddModRecDialog</span><span style="color: black;">&#40;</span>selectedRow, title=<span style="color: #483d8b;">&quot;Modify&quot;</span>,
                                           addRecord=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
        dlg.<span style="color: black;">ShowModal</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        dlg.<span style="color: black;">Destroy</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">showAllRecords</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> onDelete<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Delete a record
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        selectedRow = <span style="color: #008000;">self</span>.<span style="color: black;">bookResultsOlv</span>.<span style="color: black;">GetSelectedObject</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> selectedRow == <span style="color: #008000;">None</span>:
            commonDlgs.<span style="color: black;">showMessageDlg</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;No row selected!&quot;</span>, <span style="color: #483d8b;">&quot;Error&quot;</span><span style="color: black;">&#41;</span>
            <span style="color: #ff7700;font-weight:bold;">return</span>
        controller.<span style="color: black;">deleteRecord</span><span style="color: black;">&#40;</span>selectedRow.<span style="color: #008000;">id</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">showAllRecords</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> onSearch<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Searches database based on the user's filter choice and keyword
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        filterChoice = <span style="color: #008000;">self</span>.<span style="color: black;">categories</span>.<span style="color: black;">GetValue</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #dc143c;">keyword</span> = <span style="color: #008000;">self</span>.<span style="color: black;">search</span>.<span style="color: black;">GetValue</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;%s %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>filterChoice, <span style="color: #dc143c;">keyword</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">bookResults</span> = controller.<span style="color: black;">searchRecords</span><span style="color: black;">&#40;</span>filterChoice, <span style="color: #dc143c;">keyword</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">setBooks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> onShowAllRecord<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Updates the record list to show all of them
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">showAllRecords</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> setBooks<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;">bookResultsOlv</span>.<span style="color: black;">SetColumns</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>
            ColumnDefn<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Title&quot;</span>, <span style="color: #483d8b;">&quot;left&quot;</span>, <span style="color: #ff4500;">350</span>, <span style="color: #483d8b;">&quot;title&quot;</span><span style="color: black;">&#41;</span>,
            ColumnDefn<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Author&quot;</span>, <span style="color: #483d8b;">&quot;left&quot;</span>, <span style="color: #ff4500;">150</span>, <span style="color: #483d8b;">&quot;author&quot;</span><span style="color: black;">&#41;</span>,
            ColumnDefn<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;ISBN&quot;</span>, <span style="color: #483d8b;">&quot;right&quot;</span>, <span style="color: #ff4500;">150</span>, <span style="color: #483d8b;">&quot;isbn&quot;</span><span style="color: black;">&#41;</span>,
            ColumnDefn<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Publisher&quot;</span>, <span style="color: #483d8b;">&quot;left&quot;</span>, <span style="color: #ff4500;">150</span>, <span style="color: #483d8b;">&quot;publisher&quot;</span><span style="color: black;">&#41;</span>
        <span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">bookResultsOlv</span>.<span style="color: black;">SetObjects</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">bookResults</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> showAllRecords<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Show all records in the object list view control
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">bookResults</span> = controller.<span style="color: black;">getAllRecords</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">setBooks</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> BookFrame<span style="color: black;">&#40;</span>wx.<span style="color: black;">Frame</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        wx.<span style="color: black;">Frame</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #008000;">None</span>, title=<span style="color: #483d8b;">&quot;MvP Media Organizer&quot;</span>,
                          size=<span style="color: black;">&#40;</span><span style="color: #ff4500;">800</span>, <span style="color: #ff4500;">600</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        panel = BookPanel<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #008000;">self</span>.<span style="color: black;">Show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    app = wx.<span style="color: black;">App</span><span style="color: black;">&#40;</span><span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
    frame = BookFrame<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    app.<span style="color: black;">MainLoop</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>You&#8217;ll notice that we import a few custom items, like addModRecord, commonDlgs and controller. The <strong>addModRecord</strong> is a dialog that can be used both to add a record and modify one. The <strong>commonDlgs </strong>module is used just to simplify creating message dialogs. If we add some new features to this program, we would add other small dialog code in that module. The <strong>controller</strong> module is where all the SqlAlchemy code is executed. Most programs have some configuration options, so this would be a good place to store that code.</p>
<p>Anyway, let&#8217;s go over the highlights of the GUI. The search bar is set to search when the user presses enter. That&#8217;s what the style flag <strong>wx.TE_PROCESS_ENTER</strong> means. That and the ObjectListView&#8217;s <strong>SetEmptyListMsg </strong>method are probably the only really unfamiliar things here. That method just shows a message to the user when there&#8217;s no data in the control.</p>
<p>The <strong>onAddRecord </strong>and <strong>onEditRecord</strong> both call our addModRecord module to display the Add / Modify dialog. It should look something like this:</p>
<p><a href="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/media_org_add_record.png"><img src="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/media_org_add_record.png" alt="" title="media_org_add_record" width="400" height="250" class="aligncenter size-full wp-image-2045" /></a></p>
<p>The <strong>onEditRecord</strong> method sets a couple parameters that affect the look of the widget and passes in some information to populate the fields. The <strong>onDelete</strong> method just takes the selected item and calls the controller to delete it, then it updates the display.</p>
<p>Our <strong>onSearch</strong> method does what you&#8217;d expect. It searches for records in our database based on what filter the user chooses and their keyword. They can choose &#8220;Author&#8221;, &#8220;Title&#8221;, &#8220;ISBN&#8221; or &#8220;Publisher&#8221; as their filter. </p>
<p>The <strong>onShowAllRecord</strong> method just shows all the records on the display. A future enhancement would be to limit the number of currently showed records so we don&#8217;t cause major slow down of the application. The <strong>setBooks</strong> method just updates the displayed records. </p>
<p>Now we&#8217;ve reached the last piece of our puzzle: the Controller.</p>
<h2>The Controller and CRUD</h2>
<p>The controller is the glue which holds the model and the view together. At least, that&#8217;s what it seems like to me. It uses the model for queries and for adding, updating and deleting records. It also reports the updates to the database to the view (our GUI) so it can update appropriately. Let&#8217;s take a look at our controller code:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># controller.py</span>
<span style="color: #ff7700;font-weight:bold;">from</span> model <span style="color: #ff7700;font-weight:bold;">import</span> Book, Person, OlvBook
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> sessionmaker
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> addRecord<span style="color: black;">&#40;</span>data<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Data should be a tuple of two dictionaries in the following format:
&nbsp;
    (&quot;</span>author<span style="color: #483d8b;">&quot;:{&quot;</span>first_name<span style="color: #483d8b;">&quot;:&quot;</span>John<span style="color: #483d8b;">&quot;, &quot;</span>last_name<span style="color: #483d8b;">&quot;:&quot;</span>Doe<span style="color: #483d8b;">&quot;},
     &quot;</span>book<span style="color: #483d8b;">&quot;:{&quot;</span>title<span style="color: #483d8b;">&quot;:&quot;</span>Some book<span style="color: #483d8b;">&quot;, &quot;</span>isbn<span style="color: #483d8b;">&quot;:&quot;</span><span style="color: #ff4500;">1234567890</span><span style="color: #483d8b;">&quot;,
             &quot;</span>publisher<span style="color: #483d8b;">&quot;:&quot;</span>Packt<span style="color: #483d8b;">&quot;}
    )
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    book = Book<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    book.<span style="color: black;">title</span> = data<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;book&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;title&quot;</span><span style="color: black;">&#93;</span>
    book.<span style="color: black;">isbn</span> = data<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;book&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;isbn&quot;</span><span style="color: black;">&#93;</span>
    book.<span style="color: black;">publisher</span> = data<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;book&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;publisher&quot;</span><span style="color: black;">&#93;</span>
    author = Person<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    author.<span style="color: black;">first_name</span> = data<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;author&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;first_name&quot;</span><span style="color: black;">&#93;</span>
    author.<span style="color: black;">last_name</span> = data<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;author&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;last_name&quot;</span><span style="color: black;">&#93;</span>
    book.<span style="color: black;">person</span> = author
&nbsp;
    <span style="color: #808080; font-style: italic;"># connect to session and commit data to database</span>
    session = connectToDatabase<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    session.<span style="color: black;">add</span><span style="color: black;">&#40;</span>book<span style="color: black;">&#41;</span>
    session.<span style="color: black;">commit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    session.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> connectToDatabase<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Connect to our SQLite database and return a Session object
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sqlite:///devdata.db&quot;</span>, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    Session = sessionmaker<span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span>
    session = Session<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> session
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> convertResults<span style="color: black;">&#40;</span>results<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Convert results to OlvBook objects
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span>
    books = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> record <span style="color: #ff7700;font-weight:bold;">in</span> results:
        author = <span style="color: #483d8b;">&quot;%s %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>record.<span style="color: black;">person</span>.<span style="color: black;">first_name</span>,
                            record.<span style="color: black;">person</span>.<span style="color: black;">last_name</span><span style="color: black;">&#41;</span>
        book = OlvBook<span style="color: black;">&#40;</span>record.<span style="color: #008000;">id</span>, record.<span style="color: black;">title</span>, author,
                       record.<span style="color: black;">isbn</span>, record.<span style="color: black;">publisher</span>,
                       record.<span style="color: black;">person</span>.<span style="color: black;">last_name</span>,
                       record.<span style="color: black;">person</span>.<span style="color: black;">first_name</span>
                       <span style="color: black;">&#41;</span>
        books.<span style="color: black;">append</span><span style="color: black;">&#40;</span>book<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> books
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> deleteRecord<span style="color: black;">&#40;</span>idNum<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Delete a record from the database
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    session = connectToDatabase<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    record = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Book<span style="color: black;">&#41;</span>.<span style="color: black;">filter_by</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span>=idNum<span style="color: black;">&#41;</span>.<span style="color: black;">one</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    session.<span style="color: black;">delete</span><span style="color: black;">&#40;</span>record<span style="color: black;">&#41;</span>
    session.<span style="color: black;">commit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    session.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> editRecord<span style="color: black;">&#40;</span>idNum, row<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Edit a record
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    session = connectToDatabase<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    record = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Book<span style="color: black;">&#41;</span>.<span style="color: black;">filter_by</span><span style="color: black;">&#40;</span><span style="color: #008000;">id</span>=idNum<span style="color: black;">&#41;</span>.<span style="color: black;">one</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span>
    record.<span style="color: black;">title</span> = row<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;title&quot;</span><span style="color: black;">&#93;</span>
    record.<span style="color: black;">person</span>.<span style="color: black;">first_name</span> = row<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;first_name&quot;</span><span style="color: black;">&#93;</span>
    record.<span style="color: black;">person</span>.<span style="color: black;">last_name</span> = row<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;last_name&quot;</span><span style="color: black;">&#93;</span>
    record.<span style="color: black;">isbn</span> = row<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;isbn&quot;</span><span style="color: black;">&#93;</span>
    record.<span style="color: black;">publisher</span> = row<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;publisher&quot;</span><span style="color: black;">&#93;</span>
    session.<span style="color: black;">add</span><span style="color: black;">&#40;</span>record<span style="color: black;">&#41;</span>
    session.<span style="color: black;">commit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    session.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> getAllRecords<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Get all records and return them
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    session = connectToDatabase<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    result = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Book<span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    books = convertResults<span style="color: black;">&#40;</span>result<span style="color: black;">&#41;</span>
    session.<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;">return</span> books
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> searchRecords<span style="color: black;">&#40;</span>filterChoice, <span style="color: #dc143c;">keyword</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Searches the database based on the filter chosen and the keyword
    given by the user
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    session = connectToDatabase<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> filterChoice == <span style="color: #483d8b;">&quot;Author&quot;</span>:
        qry = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Person<span style="color: black;">&#41;</span>
        result = qry.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>Person.<span style="color: black;">first_name</span>.<span style="color: black;">contains</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'%s'</span> <span style="color: #66cc66;">%</span> <span style="color: #dc143c;">keyword</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        records = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> record <span style="color: #ff7700;font-weight:bold;">in</span> result:
            <span style="color: #ff7700;font-weight:bold;">for</span> book <span style="color: #ff7700;font-weight:bold;">in</span> record.<span style="color: black;">books</span>:
                records.<span style="color: black;">append</span><span style="color: black;">&#40;</span>book<span style="color: black;">&#41;</span>
        result = records
        <span style="color: #ff7700;font-weight:bold;">print</span> result
    <span style="color: #ff7700;font-weight:bold;">elif</span> filterChoice == <span style="color: #483d8b;">&quot;Title&quot;</span>:
        qry = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Book<span style="color: black;">&#41;</span>
        result = qry.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>Book.<span style="color: black;">title</span>.<span style="color: black;">contains</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'%s'</span> <span style="color: #66cc66;">%</span> <span style="color: #dc143c;">keyword</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">elif</span> filterChoice == <span style="color: #483d8b;">&quot;ISBN&quot;</span>:
        qry = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Book<span style="color: black;">&#41;</span>
        result = qry.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>Book.<span style="color: black;">isbn</span>.<span style="color: black;">contains</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'%s'</span> <span style="color: #66cc66;">%</span> <span style="color: #dc143c;">keyword</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        qry = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Book<span style="color: black;">&#41;</span>
        result = qry.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>Book.<span style="color: black;">publisher</span>.<span style="color: black;">contains</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'%s'</span> <span style="color: #66cc66;">%</span> <span style="color: #dc143c;">keyword</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    books = convertResults<span style="color: black;">&#40;</span>result<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> books</pre>
<p>Our controller has 7 functions defined: </p>
<ul>
<li>addRecord</li>
<li>connectToDatabase</li>
<li>convertResults</li>
<li>deleteRecord</li>
<li>editRecord</li>
<li>getAllRecords</li>
<li>searchRecords</li>
</ul>
<p>These are pretty self explanatory. However, we&#8217;ll spend a little time explaining what <strong>convertResults</strong> does and how <strong>searchRecords</strong> works. </p>
<p>The <strong>convertResults</strong> method is for converting the SqlAlchemy book results that we get from querying the database, into the ObjectListView Book model objects. This is necessary so we can display them when there are updates to the database or when displaying the results of a query. As you can see, we just iterate over the results and massage the data appropriately.</p>
<p>In the <strong>searchRecords</strong> method, we pass in our filter and keyword and do queries on the database using our session object via a conditional &#8220;if&#8221; statement. Depending on the type of filter, we query differently. For the most part, the query is the same though, so this could use some refactoring. I&#8217;ll leave that for the reader to figure out as an assignment. Once we have the results converted, we then return them to the calling function, which in this case happens to be our GUI&#8217;s search event handler.</p>
<p>The CRUD part is covered in the other methods where we create, read, update, and delete records. </p>
<h2>Wrapping Up</h2>
<p>Now you should know the basics behind creating a wxPython program using the MVC framework. This isn&#8217;t a perfect example and I don&#8217;t claim that it is, but it should give you an idea of how to start making your own. It also shows how to interact with a SQLite database using SqlAlchemy. I hope you&#8217;ve found this helpful and look forward to hearing your comments.</p>
<h2>Source Code</h2>
<ul>
<li><a href='http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/mediaLocker.zip'>mediaLocker.zip</a></li>
<li><a href='http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/mediaLocker.tar'>mediaLocker.tar</a></li>
<li>You can also check out the code from <a href="https://bitbucket.org/driscollis/mousevspython/src" target="_blank">Bitbucket</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2011/11/10/wxpython-and-sqlalchemy-an-intro-to-mvc-and-crud/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>SqlAlchemy ProgrammingError 42000 and MS SQL</title>
		<link>http://www.blog.pythonlibrary.org/2011/01/15/sqlalchemy-programmingerror-42000-and-ms-sql/</link>
		<comments>http://www.blog.pythonlibrary.org/2011/01/15/sqlalchemy-programmingerror-42000-and-ms-sql/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 22:19:40 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[SqlAlchemy]]></category>
		<category><![CDATA[MSSQL]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1533</guid>
		<description><![CDATA[I have been working on a software inventory script lately using SqlAlchemy on Windows XP to connect to a newly created table in a Microsoft SQL Server 2005 database. I created the table using Aqua Data Studio, logging in as the SQL Administrator (sa) and thought all was well until I tried to commit some [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2011/01/15/sqlalchemy-programmingerror-42000-and-ms-sql/" data-url="http://bit.ly/vINpRg" data-text="SqlAlchemy ProgrammingError 42000 and MS SQL" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2011/01/15/sqlalchemy-programmingerror-42000-and-ms-sql/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>I have been working on a software inventory script lately using SqlAlchemy on Windows XP to connect to a newly created table in a Microsoft SQL Server 2005 database. I created the table using Aqua Data Studio, logging in as the SQL Administrator (sa) and thought all was well until I tried to commit some data to the table. Here&#8217;s the screwy error that I received:</p>
<pre class="python">pyodbc.<span style="color: black;">ProgrammingError</span>: <span style="color: black;">&#40;</span><span style="color: #483d8b;">'42000'</span>, <span style="color: #483d8b;">'[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot find the object &quot;dbo.software&quot; because it does not exist or you do not have permissions. (1088) (SQLExecDirectW)'</span><span style="color: black;">&#41;</span></pre>
<p><span id="more-1533"></span><br />
Now, what does that mean? I know the database exists because I just created it with Aqua Data Studio (a database management suite) and I gave myself the following permissions: Select, Insert, Update and Delete. If you Google this error, you&#8217;ll end up finding four references to one <a href="http://groups.google.com/group/sqlalchemy/browse_thread/thread/78a3912426d48cba?fwc=2">thread</a>. They don&#8217;t really have a solution in the thread, although they mention that adding permission to alter the schema might work. Note that this problem only happens when you use the declarative syntax. Anyway, at this point, you probably want to see my code, so take a look:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine, Column, DateTime, Integer, String
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">ext</span>.<span style="color: black;">declarative</span> <span style="color: #ff7700;font-weight:bold;">import</span> declarative_base
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> sessionmaker
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">datetime</span>
&nbsp;
uri = <span style="color: #483d8b;">&quot;mssql://username:pw@mssqlServerPath/Inventory&quot;</span>
engine = create_engine<span style="color: black;">&#40;</span>uri<span style="color: black;">&#41;</span>
engine.<span style="color: black;">echo</span> = <span style="color: #008000;">True</span>
Base = declarative_base<span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Software<span style="color: black;">&#40;</span>Base<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    SqlAlchemy table representation of &quot;</span>software<span style="color: #483d8b;">&quot; login
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">&quot;software&quot;</span>
    __table_args__ = <span style="color: black;">&#123;</span><span style="color: #483d8b;">&quot;schema&quot;</span>:<span style="color: #483d8b;">&quot;dbo&quot;</span><span style="color: black;">&#125;</span>
&nbsp;
    <span style="color: #008000;">id</span> = Column<span style="color: black;">&#40;</span>Integer, primary_key=<span style="color: #008000;">True</span>, autoincrement=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    name = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#40;</span><span style="color: #ff4500;">100</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    date_added = Column<span style="color: black;">&#40;</span>DateTime<span style="color: black;">&#41;</span>
    date_checked = Column<span style="color: black;">&#40;</span>DateTime<span style="color: black;">&#41;</span>
    machine_name = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#40;</span><span style="color: #ff4500;">25</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    version = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#40;</span><span style="color: #ff4500;">25</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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>, name, date_added, date_checked, machine_name, version<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">name</span> = name
        <span style="color: #008000;">self</span>.<span style="color: black;">date_added</span> = date_added
        <span style="color: #008000;">self</span>.<span style="color: black;">date_checked</span> = date_checked
        <span style="color: #008000;">self</span>.<span style="color: black;">machine_name</span> = machine_name
        <span style="color: #008000;">self</span>.<span style="color: black;">version</span> = version
&nbsp;
Session = sessionmaker<span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span>
session = Session<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
now = <span style="color: #dc143c;">datetime</span>.<span style="color: #dc143c;">datetime</span>.<span style="color: black;">now</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
new_record = Software<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Adobe Acrobat&quot;</span>, now, now, <span style="color: #483d8b;">&quot;MCIS0467&quot;</span>, <span style="color: #483d8b;">&quot;9.0&quot;</span><span style="color: black;">&#41;</span>
session.<span style="color: black;">add</span><span style="color: black;">&#40;</span>new_record<span style="color: black;">&#41;</span>
session.<span style="color: black;">commit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>From what my boss could figure out, the declarative syntax using an identity-based query system and if the identity isn&#8217;t set, then SqlAlchemy  cannot find the database. If you use SqlAlchemy to create the table, then you won&#8217;t have this problem. Anyway, it turns out that you have to use Microsoft SQL Server Management Studio to rectify this particular situation. Load it up and navigate to the correct database and table, then open the columns tree. Right-click the primary key field and choose &#8220;Modify&#8221;. There&#8217;s a &#8220;Column Properties&#8221; tab at the bottom of the screen. Go there and scroll down to Identity Specification and expand it. Finally, make sure that the &#8220;(Is Identity)&#8221; field is set to &#8220;Yes&#8221;. Save it and you&#8217;re done!</p>
<p>This is a pretty weird and rare issue so you probably won&#8217;t have it, but I thought it was an interesting problem and I wanted to document the solution. Note: I was using Python 2.5 with SqlAlchemy 0.6.6 on Windows XP.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2011/01/15/sqlalchemy-programmingerror-42000-and-ms-sql/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Top Ten Articles of 2010</title>
		<link>http://www.blog.pythonlibrary.org/2010/12/30/top-ten-articles-of-2010/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/12/30/top-ten-articles-of-2010/#comments</comments>
		<pubDate>Thu, 30 Dec 2010 23:00:40 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[PyWin32]]></category>
		<category><![CDATA[SqlAlchemy]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[PyPDF]]></category>
		<category><![CDATA[Reportlab]]></category>
		<category><![CDATA[Roundup]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1480</guid>
		<description><![CDATA[A lot of websites are doing year-end retrospectives this week, so I thought you might find it interesting to know which articles on this blog were the most popular this year. Below you will find links to each article along with the page view count I got from Google Analytics: A Simple Step-by-Step Reportlab Tutorial, [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/12/30/top-ten-articles-of-2010/" data-url="http://bit.ly/vNQ57f" data-text="Top Ten Articles of 2010" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/12/30/top-ten-articles-of-2010/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>A lot of websites are doing year-end retrospectives this week, so I thought you might find it interesting to know which articles on this blog were the most popular this year. Below you will find links to each article along with the page view count I got from Google Analytics:</p>
<ol>
<li><a href="http://www.blog.pythonlibrary.org/2010/03/08/a-simple-step-by-step-reportlab-tutorial/">A Simple Step-by-Step Reportlab Tutorial</a>, 9,709 page views, posted 03/08/2010</li>
<li><a href="http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-1-of-2/">Another Step-by-Step SqlAlchemy Tutorial</a> Part 1, 7,746 page views, posted 02/03/2010</li>
<li><a href="http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-2-of-2/">Another Step-by-Step SqlAlchemy Tutorial Part 2</a>, 4,858 page views, posted 02/03/2010</li>
<li><a href="http://www.blog.pythonlibrary.org/2010/05/15/manipulating-pdfs-with-python-and-pypdf/">Manipulating PDFs with Python and pyPdf</a>, 4,511 page views, posted 05/15/2010</li>
<li><a href="http://www.blog.pythonlibrary.org/2010/10/14/python-101-introspection/">Python 101: Introspection</a>, 4,473 page views, posted 10/14/2010</li>
<li><a href="http://www.blog.pythonlibrary.org/2010/04/04/wxpython-grid-tips-and-tricks/">wxPython: Grid Tips and Tricks</a>, 3,476 page views, posted 04/04/2010</li>
<li><a href="http://www.blog.pythonlibrary.org/2010/04/20/wxpython-creating-a-simple-mp3-player/">wxPython: Creating a Simple MP3 Player</a>, 3,401 page views, posted 04/20/2010</li>
<li><a href="http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/">Python and Microsoft Office &#8211; Using PyWin32</a>, 3,323  page views, posted 07/16/2010</li>
<li><a href="http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/">wxPython and Threads</a>, 3,183  page views, posted 05/22/2010</li>
</ol>
<p>It would seem that SqlAlchemy and Reportlab are pretty popular topics. Are there any articles about either of these cool packages that you think I should write? As you can see, wxPython makes it into the top ten 3 times! What should I write about next regarding wxPython? </p>
<p>This upcoming year, I plan to write about some of the other GUI toolkits. Which one do you think I should do first? Tkinter, PySide, PyGUI or something else? What packages or standard libraries do you think I should cover? Feel free to let me know via the comments below or via my contact form (link at top). I&#8217;m looking forward to another year of Python tinkering and writing and I hope you are too! Thanks for your readership and encouragement this year!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/12/30/top-ten-articles-of-2010/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>SqlAlchemy: A Simple Tutorial for Elixir</title>
		<link>http://www.blog.pythonlibrary.org/2010/11/25/sqlalchemy-a-simple-tutorial-for-elixir/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/11/25/sqlalchemy-a-simple-tutorial-for-elixir/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 01:55:10 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SqlAlchemy]]></category>
		<category><![CDATA[elixir]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[sqlite]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=580</guid>
		<description><![CDATA[Elixir is a lightweight declarative layer on top of SqlAlchemy that&#8217;s been around since 2006, well before SqlAlchemy released their own built-in Declarative syntax. Elixir was created by a collaboration between Jonathan LaCour, Daniel Haus and Gaëtan de Menten who had a passion for making SqlAlchemy even easier to use. In this tutorial, we&#8217;ll look [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/11/25/sqlalchemy-a-simple-tutorial-for-elixir/" data-url="http://bit.ly/uHHw2C" data-text="SqlAlchemy: A Simple Tutorial for Elixir" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/11/25/sqlalchemy-a-simple-tutorial-for-elixir/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Elixir is a lightweight declarative layer on top of SqlAlchemy that&#8217;s been around since 2006, well before SqlAlchemy released their own built-in Declarative syntax. Elixir was created by a collaboration between Jonathan LaCour, Daniel Haus and Gaëtan de Menten who had a passion for making SqlAlchemy even easier to use. In this tutorial, we&#8217;ll look at how to to create our own database with Elixir and how to communicate with a pre-existing database.<span id="more-580"></span></p>
<p><em>Note: This is my first time using Elixir so I wouldn&#8217;t be surprised if there are better ways to do some of the stuff mentioned herein.</em></p>
<h2>Creating a Database with Elixir</h2>
<p>For this section, we&#8217;re going to look at creating a super simple bookmark database where each record is made up of a title, a url and a description. It will also have an id column that will be our primary key. Elixir does this for us automatically whenever we create a database without a primary key specified and it will auto-increment the id as well. Let&#8217;s get this party started with some code!</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> elixir <span style="color: #ff7700;font-weight:bold;">import</span> metadata, Entity, Field
<span style="color: #ff7700;font-weight:bold;">from</span> elixir <span style="color: #ff7700;font-weight:bold;">import</span> Unicode, UnicodeText
&nbsp;
metadata.<span style="color: black;">bind</span> = <span style="color: #483d8b;">&quot;sqlite:///bookmarks.sqlite&quot;</span>
metadata.<span style="color: black;">bind</span>.<span style="color: black;">echo</span> = <span style="color: #008000;">True</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Bookmarks<span style="color: black;">&#40;</span>Entity<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Custom made bookmark example
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    title = Field<span style="color: black;">&#40;</span>Unicode<span style="color: black;">&#41;</span>
    url = Field<span style="color: black;">&#40;</span>Unicode<span style="color: black;">&#41;</span>
    description = Field<span style="color: black;">&#40;</span>UnicodeText<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot;&lt;Bookmark '%s' (%s) - %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">title</span>, <span style="color: #008000;">self</span>.<span style="color: black;">url</span>,
                                             <span style="color: #008000;">self</span>.<span style="color: black;">description</span><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>:
    <span style="color: #ff7700;font-weight:bold;">from</span> elixir <span style="color: #ff7700;font-weight:bold;">import</span> create_all, setup_all, session
    setup_all<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    create_all<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># Adding records</span>
    Bookmarks<span style="color: black;">&#40;</span>title=<span style="color: #483d8b;">&quot;Google&quot;</span>, url=<span style="color: #483d8b;">&quot;http://www.google.com&quot;</span>,
              description=<span style="color: #483d8b;">&quot;Search engine&quot;</span><span style="color: black;">&#41;</span>
    Bookmarks<span style="color: black;">&#40;</span>title=<span style="color: #483d8b;">&quot;Digital Photography School&quot;</span>,
              url=<span style="color: #483d8b;">&quot;http://www.digital-photography-school.com&quot;</span>,
              description=<span style="color: #483d8b;">&quot;An Australian Photography blog&quot;</span><span style="color: black;">&#41;</span>
    Bookmarks<span style="color: black;">&#40;</span>title=<span style="color: #483d8b;">&quot;Mouse Vs. the Python&quot;</span>,
              url=<span style="color: #483d8b;">&quot;http://www.blog.pythonlibrary.org/&quot;</span>,
              description=<span style="color: #483d8b;">&quot;Mike Driscoll's Python blog&quot;</span><span style="color: black;">&#41;</span>
    session.<span style="color: black;">commit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># --------------------------------------------------</span>
    <span style="color: #808080; font-style: italic;"># Simple Queries</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># get all the records</span>
    records = Bookmarks.<span style="color: black;">query</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> record <span style="color: #ff7700;font-weight:bold;">in</span> records:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;-&quot;</span> <span style="color: #66cc66;">*</span> <span style="color: #ff4500;">20</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> record.<span style="color: black;">title</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> record.<span style="color: black;">url</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> record.<span style="color: black;">description</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># find a specific record</span>
    qry = Bookmarks.<span style="color: black;">query</span>.<span style="color: black;">filter_by</span><span style="color: black;">&#40;</span>title=u<span style="color: #483d8b;">'Google'</span><span style="color: black;">&#41;</span>
    record = qry.<span style="color: black;">first</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;%s (%s)&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>record.<span style="color: black;">title</span>, record.<span style="color: black;">url</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># delete the record</span>
    record.<span style="color: black;">delete</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    session.<span style="color: black;">commit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>Let&#8217;s take a moment to study this code and see if we can figure it out. In this example, we import just the classes we want from the elixir package. </p>
<p>After the imports are two lines dealing with metadata. According to Gaëtan de Menten, the metadata is &#8220;a container of python objects representing database tables.&#8221; Anyway, what happens in those lines is the creation of the sqlite database file (assuming it doesn&#8217;t  already exist) and the setting of the echo to True. That means that all the SQL that Elixir emits will be sent to stdout so you can read it too.</p>
<p>Next we subclass the Entity object in our Bookmarks class. Here we create our three fields (or columns). The &#8220;__repr__&#8221; basically makes the printing of the Bookmarks objects more friendly for humans such that it prints out the title, url and description of the Bookmark rather than just something like &#8220;Bookmark object <abcd>&#8220;. </p>
<p>Lastly, in the &#8220;if&#8221; statement at the end, we setup the mappings and such and create the database. Then we add three rows and commit them to said database. Next, we do a couple of simple queries against the database and at the very end, we delete a record. Hopefully you can follow all that without explicit description. </p>
<p>For our next trick, we will look at how to read an already existing database with Elixir.</p>
<h2>Reading a Pre-Existing Database</h2>
<p>In this example, we will use a copy of the places.sqlite database that is generated by Mozilla Firefox. It holds bookmarks and (I think) your browsing history. The code in this example will assume that the database file has been copied into the same location as the Python code file. Let&#8217;s take a look at that code now:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> elixir <span style="color: #ff7700;font-weight:bold;">import</span> metadata, using_options, Entity, Field
<span style="color: #ff7700;font-weight:bold;">from</span> elixir <span style="color: #ff7700;font-weight:bold;">import</span> Integer, Unicode, UnicodeText
&nbsp;
metadata.<span style="color: black;">bind</span> = <span style="color: #483d8b;">&quot;sqlite:///places.sqlite&quot;</span>
metadata.<span style="color: black;">bind</span>.<span style="color: black;">echo</span> = <span style="color: #008000;">True</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Bookmarks<span style="color: black;">&#40;</span>Entity<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Firefox Bookmarks class
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    using_options<span style="color: black;">&#40;</span>tablename=<span style="color: #483d8b;">&quot;moz_bookmarks&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
    _id = Field<span style="color: black;">&#40;</span>Integer, colname=<span style="color: #483d8b;">&quot;id&quot;</span>, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    _type = Field<span style="color: black;">&#40;</span>Integer, colname=<span style="color: #483d8b;">&quot;type&quot;</span><span style="color: black;">&#41;</span>
    fk = Field<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    parent = Field<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    position = Field<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    title = Field<span style="color: black;">&#40;</span>Unicode<span style="color: black;">&#41;</span>
    keyword_id = Field<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    folder_type = Field<span style="color: black;">&#40;</span>UnicodeText<span style="color: black;">&#41;</span>
    dateAdded = Field<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    lastModified = Field<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">'&lt;Bookmark &quot;%s&quot; - &quot;%s&quot;'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._id, <span style="color: #008000;">self</span>.<span style="color: black;">title</span><span style="color: black;">&#41;</span>
&nbsp;
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    <span style="color: #ff7700;font-weight:bold;">from</span> elixir <span style="color: #ff7700;font-weight:bold;">import</span> setup_all
    setup_all<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    result = Bookmarks.<span style="color: black;">query</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    x = <span style="color: #ff4500;">0</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;-&quot;</span> <span style="color: #66cc66;">*</span> <span style="color: #ff4500;">10</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> item <span style="color: #ff7700;font-weight:bold;">in</span> result:
        <span style="color: #ff7700;font-weight:bold;">if</span> x <span style="color: #66cc66;">&gt;</span> <span style="color: #ff4500;">10</span>:
            <span style="color: #ff7700;font-weight:bold;">break</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> item.<span style="color: black;">title</span>
        x += <span style="color: #ff4500;">1</span></pre>
<p>The first few lines are basically the same as the ones in the previous example. The only real difference is that we specify a database that exists this time and we imported a few more classes. In the Bookmark class, we need to mirror the columns in the &#8220;moz_bookmarks&#8221; database. There&#8217;s a difference right there. We use the &#8220;using_options&#8221; class from Elixir to specify which table we want. Then we create a matching field name. The first two fields would actually shadow Python builtins, so we give them an underscore to differentiate them and set the column name by passing it in the <strong>colname </strong>keyword argument of the <strong>Field </strong>class. </p>
<p>When testing this code, I noticed that some of the titles were nulls, so the __repr__ may not work as expected. Anyway, in the &#8220;if&#8221; statement at the end, we do a query against the table and print out the first 10 records we find. </p>
<p>As a side note, if you don&#8217;t want to declare all the field names, you don&#8217;t have to. Elixir supports the same autoload functionality that SqlAlchemy does. So instead of declaring the field names, you would do something like this: using_options(tablename=&#8221;moz_bookmarks&#8221;, autoload=True)</p>
<h2>Wrapping Up</h2>
<p>As you can see, using Elixir is pretty simple. SqlAlchemy has since added its own built-in declarative method, but for some, Elixir proves to be a potent help. There are many more query examples and relational examples on their official website (see link below). I encourage you to check it out and see if you find it helpful in learning SqlAlchemy.</p>
<h2>Further Reading</h2>
<ul>
<li>Official Elixir <a href="http://elixir.ematia.de/trac/">website</a></li>
<li><a href="http://elixir.ematia.de/trac/wiki/TutorialDivingIn">Official Elixir Tutorial</a></li>
<li>Elixir <a href="http://elixir.ematia.de/trac/wiki/Documentation">documentation</a></li>
<li>Official SqlAlchemy <a href="http://www.sqlalchemy.org/">website</a></li>
</ul>
<p><strong>This code was tested on the following:</strong></p>
<ul>
<li>Windows 7 Home Premium with Python 2.6.4, SqlAlchemy 0.6.5, Elixir 0.7.1</li>
<li>Windows XP Professional with Python 2.5, SqlAlchemy 0.5.0, Elixir 0.7.0</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/11/25/sqlalchemy-a-simple-tutorial-for-elixir/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>SqlAlchemy and Microsoft Access</title>
		<link>http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/#comments</comments>
		<pubDate>Sun, 10 Oct 2010 13:04:23 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[SqlAlchemy]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[databases]]></category>
		<category><![CDATA[microsoft access]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1291</guid>
		<description><![CDATA[Update (10/12/2010) &#8211; One of my alert readers told me that SqlAlchemy 0.6.x currently does NOT support the Access dialect. Read here for more info. A year or two ago, I was asked to transfer some data from some old Microsoft Access files to our Microsoft SQL Server. Since I enjoy using SqlAlchemy, I decided [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/" data-url="http://bit.ly/sjoTVA" data-text="SqlAlchemy and Microsoft Access" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/";
			reddit_title = "SqlAlchemy and Microsoft Access";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/"></g:plusone></div></div><p><strong>Update (10/12/2010) &#8211; One of my alert readers told me that SqlAlchemy 0.6.x currently does NOT support the Access dialect. Read <a href="http://www.sqlalchemy.org/docs/reference/dialects/index.html">here </a>for more info.</strong></p>
<p>A year or two ago, I was asked to transfer some data from some old Microsoft Access files to our Microsoft SQL Server. Since I enjoy using SqlAlchemy, I decided to see if it supported Access. The documentation at the time was pretty unhelpful in this regard, but it did seem to be possible and I found one thread about it on SqlAlchemy&#8217;s Google group.<span id="more-1291"></span></p>
<p>The code to connect to Microsoft Access is pretty simple. It goes something like this:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine
engine = create_engine<span style="color: black;">&#40;</span>r<span style="color: #483d8b;">'access:///C:/some/path/database.MDB'</span><span style="color: black;">&#41;</span></pre>
<p>See how easy that was? You just tell SqlAlchemy what kind of database to connect to, add three forward slashes and then the path to the file. Once that&#8217;s done, you can do pretty much anything with the Access file that you can do with a normal database:</p>
<pre class="python"><span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> TableName<span style="color: black;">&#40;</span>Base<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    MS Access database
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">&quot;ROW&quot;</span>
    __table_args__ = <span style="color: black;">&#40;</span><span style="color: black;">&#123;</span><span style="color: #483d8b;">&quot;autoload&quot;</span>:<span style="color: #008000;">True</span><span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>  <span style="color: #808080; font-style: italic;"># load the database</span>
    FILENUM = Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;FILE #&quot;</span>, Integer, key=<span style="color: #483d8b;">&quot;FILENUM&quot;</span><span style="color: black;">&#41;</span></pre>
<p>In the code above, I use SqlAlchemy&#8217;s declarative syntax to autoload the database&#8217;s structure. I can&#8217;t recall is this database had its primary key set, but I&#8217;m guessing it didn&#8217;t since I had to add that last line.</p>
<p>Anyway, once you have your connection, you can just run queries as you normally would. In my case, I ended up creating a model file to hold all the table definitions for the Access file and the SQL Server database, then I did a SELECT * on the Access file, looped over the result and inserted each row into the SQL Server one. The only thing you have to watch out for is that Access is a lot more forgiving of NULLS than SQL Server is, so I had to write some special handling around that atrocity.</p>
<p>Well, that&#8217;s really all there is to it. You can check out my other SqlAlchemy tutorials for more general information about using SqlAlchemy to interact with your database.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>SqlAlchemy: Connecting to pre-existing databases</title>
		<link>http://www.blog.pythonlibrary.org/2010/09/10/sqlalchemy-connecting-to-pre-existing-databases/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/09/10/sqlalchemy-connecting-to-pre-existing-databases/#comments</comments>
		<pubDate>Fri, 10 Sep 2010 12:59:59 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SqlAlchemy]]></category>
		<category><![CDATA[databases]]></category>
		<category><![CDATA[sqlite]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1193</guid>
		<description><![CDATA[Accessing databases with Python is a simple process. Python even provides a sqlite database library that&#8217;s built into the main distribution (since 2.5). My favorite way to access databases with Python is to use the 3rd party package, SqlAlchemy. SqlAlchemy is an object-relational mapper (ORM), which means that it takes SQL constructs and makes them [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/09/10/sqlalchemy-connecting-to-pre-existing-databases/" data-url="http://bit.ly/v8M3XK" data-text="SqlAlchemy: Connecting to pre-existing databases" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/09/10/sqlalchemy-connecting-to-pre-existing-databases/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Accessing databases with Python is a simple process. Python even provides a sqlite database library that&#8217;s built into the main distribution (since 2.5). My favorite way to access databases with Python is to use the 3rd party package, SqlAlchemy. SqlAlchemy is an object-relational mapper (ORM), which means that it takes SQL constructs and makes them more like the target language. In this case, you end up using Python syntax to execute SQL rather than straight SQL and you can use the same code to access multiple database backends (if you&#8217;re careful).</p>
<p>In this article, we&#8217;re going to look at how to use SqlAlchemy to connect to pre-existing databases. If my experience is any indication, you&#8217;ll probably be spending more time working with databases that you didn&#8217;t create than with ones that you did. This article will show you how to connect to them.<span id="more-1193"></span></p>
<h2>SqlAlchemy&#8217;s autoload</h2>
<p>SqlAlchemy has two ways to define a databases columns. The first way is the long way, in which you define each and every field along with its type. The easy (or short) way is to use SqlAlchemy&#8217;s <strong>autoload</strong> functionality, which will introspect the table and pull out the field names in a rather magical way. We&#8217;ll start off with the autoload method and then show the long way in the next section.</p>
<p>Before we begin though, it needs to be noted that there are two methods for configuring SqlAlchemy: a long-hand way and a declarative (or &#8220;shorthand&#8221; way. We will go over both ways. Let&#8217;s start out with the long version and then do it &#8220;declaratively&#8221;.</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine, MetaData, Table
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> mapper, sessionmaker
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Bookmarks<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">pass</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> loadSession<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    dbPath = <span style="color: #483d8b;">'places.sqlite'</span>
    engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">'sqlite:///%s'</span> <span style="color: #66cc66;">%</span> dbPath, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
&nbsp;
    metadata = MetaData<span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span>
    moz_bookmarks = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">'moz_bookmarks'</span>, metadata, autoload=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    mapper<span style="color: black;">&#40;</span>Bookmarks, moz_bookmarks<span style="color: black;">&#41;</span>
&nbsp;
    Session = sessionmaker<span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span>
    session = Session<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> session
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    session = loadSession<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    res = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Bookmarks<span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    res<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">title</span></pre>
<p>In this snippet, we import a few handy classes and utilities from sqlalchemy that allow us to define such things as an engine (a type of connection/interface to the database), metadata (a table catalog) and a session (a &#8220;handle&#8221; to the database that allows us to query it). Note that we have a &#8220;places.sqlite&#8221; file. This database comes from Mozilla Firefox. If you have it installed, go looking for it as it makes an excellent testbed for this sort of thing. On my Windows XP machine, it&#8217;s in the following location: &#8220;C:\Documents and Settings\Mike\Application Data\Mozilla\Firefox\Profiles\f7csnzvk.default&#8221;. Just copy that file into the location that you&#8217;ll be using for the scripts in this article. If you try to use it in place and you have Firefox open, you may have issues as your code may interrupt Firefox or vice-versa.</p>
<p>In the <strong>create_engine</strong> call, we set <strong>echo</strong> to <strong>True</strong>. This causes SqlAlchemy to send all the SQL it generates to stdout, which is quite handy for debugging purposes. I would recommend setting it to False when you put your code in production. For our purposes, the most interesting line is as follows:</p>
<pre class="python">moz_bookmarks = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">'moz_bookmarks'</span>, metadata, autoload=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span></pre>
<p>This tells SqlAlchemy to attempt to load the &#8220;moz_bookmarks&#8221; table automatically. If it&#8217;s a proper database with a primary key, this will work great. If the table doesn&#8217;t have a primary key, then you can do this to hack it:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Column, Integer
moz_bookmarks = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">'moz_bookmarks'</span>, metadata,
                      Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;id&quot;</span>, Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>,
                      autoload=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span></pre>
<p>This adds an extra column called &#8220;id&#8221;. It&#8217;s basically monkey-patching the database. I&#8217;ve used this method successfully when I have to use poorly designed databases from vendors. SqlAlchemy will automatically increment it too, if the database supports it. The <strong>mapper</strong> will map the table object to the Bookmarks class. Then we create a session that&#8217;s bound to our engine so we can make queries. The res = <strong>session.query(Bookmarks).all()</strong> basically means <strong>SELECT * FROM moz_bookmarks</strong> and will return the result as a list of Bookmark objects.</p>
<p>Sometimes the bad database will have a field that should obviously be the primary key. If so, you can just use that name instead of &#8220;id&#8221;. Other times, you can create a unique key by setting the primary key to two columns (i.e. fields). You do that by creating two columns and setting &#8220;primary_key&#8221; to True on both of them. This is a whole lot better than having to define an entire table if the table has several dozen fields. </p>
<p>Let&#8217;s move on to the declarative autoload method:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">ext</span>.<span style="color: black;">declarative</span> <span style="color: #ff7700;font-weight:bold;">import</span> declarative_base
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> sessionmaker
&nbsp;
engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">'sqlite:///places.sqlite'</span>, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
Base = declarative_base<span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Bookmarks<span style="color: black;">&#40;</span>Base<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">'moz_bookmarks'</span>
    __table_args__ = <span style="color: black;">&#123;</span><span style="color: #483d8b;">'autoload'</span>:<span style="color: #008000;">True</span><span style="color: black;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> loadSession<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    metadata = Base.<span style="color: black;">metadata</span>
    Session = sessionmaker<span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span>
    session = Session<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> session
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    session = loadSession<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    res = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Bookmarks<span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> res<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">title</span></pre>
<p>The declarative method looks a little different, huh? Let&#8217;s try to unpack the new stuff. First off, we have a new import: <strong>from sqlalchemy.ext.declarative import declarative_base</strong>. We use &#8220;declarative_base&#8221; to create a class using our engine that we then create the Bookmarks subclass from. To specify the table name, we use the magic method, <strong>__tablename__</strong> and to tell it to autoload, we create the <strong>__table_args__</strong> dict. Then in the <strong>loadSession</strong> function, we get the metadata object like this: <strong>metadata = Base.metadata</strong>. The rest of the code is the same. Declarative syntax usually simplifies the code because it puts it all in one class rather than creating a class and a Table object separately. If you like the declarative style, you might also want to look at Elixir, a SqlAlchemy extension that did declarative before they added this style to the main package.</p>
<h2>Defining Your Databases Explicitly</h2>
<p>There are times when you can&#8217;t use autoload or you just want to have complete control over the table definition. SqlAlchemy allows you to do this almost as easily. We&#8217;ll look at the longhand version first and then look at the declarative style.</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine, Column, MetaData, Table
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Integer, String, Text
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> mapper, sessionmaker
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Bookmarks<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">pass</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> loadSession<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    dbPath = <span style="color: #483d8b;">'places.sqlite'</span>
&nbsp;
    engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">'sqlite:///%s'</span> <span style="color: #66cc66;">%</span> dbPath, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
&nbsp;
    metadata = MetaData<span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span>
    moz_bookmarks = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">'moz_bookmarks'</span>, metadata,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'id'</span>, Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'type'</span>, Integer<span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'fk'</span>, Integer<span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'parent'</span>, Integer<span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'position'</span>, Integer<span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'title'</span>, String<span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'keyword_id'</span>, Integer<span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'folder_type'</span>, Text<span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'dateAdded'</span>, Integer<span style="color: black;">&#41;</span>,
                          Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'lastModified'</span>, Integer<span style="color: black;">&#41;</span>
                          <span style="color: black;">&#41;</span>
&nbsp;
    mapper<span style="color: black;">&#40;</span>Bookmarks, moz_bookmarks<span style="color: black;">&#41;</span>
&nbsp;
    Session = sessionmaker<span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span>
    session = Session<span style="color: black;">&#40;</span><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>:
    session = loadSession<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    res = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Bookmarks<span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> res<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">title</span></pre>
<p>This code really isn&#8217;t all that different from the code we&#8217;ve seen. The part we care about most is the Table definition. Here we use the keyword, Column, to define each column. The Column class accepts a name of the column, the type, whether to set it as the primary key and whether or not the column is nullable. It may accept a few other arguments, but those are the ones you&#8217;ll see the most. This example doesn&#8217;t show the nullable bit because I couldn&#8217;t figure out if the Firefox table had those constraints.</p>
<p>Anyway, once you&#8217;ve got the columns defined, the rest of the code is the same as before. Let&#8217;s move on to the declarative style then:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Column, Integer, String, create_engine
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">ext</span>.<span style="color: black;">declarative</span> <span style="color: #ff7700;font-weight:bold;">import</span> declarative_base
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> sessionmaker
&nbsp;
engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">'sqlite:///places.sqlite'</span>, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
Base = declarative_base<span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Places<span style="color: black;">&#40;</span>Base<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">'moz_places'</span>
&nbsp;
    <span style="color: #008000;">id</span> = Column<span style="color: black;">&#40;</span>Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    url = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#41;</span>
    title = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#41;</span>
    rev_host = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#41;</span>
    visit_count = Column<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    hidden = Column<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    typed = Column<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    favicon_id = Column<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    frecency = Column<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
    last_visit_date = Column<span style="color: black;">&#40;</span>Integer<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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>, <span style="color: #008000;">id</span>, url, title, rev_host, visit_count,
                 hidden, typed, favicon_id, frecency, last_visit_date<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: #008000;">id</span> = <span style="color: #008000;">id</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">url</span> = url
        <span style="color: #008000;">self</span>.<span style="color: black;">title</span> = title
        <span style="color: #008000;">self</span>.<span style="color: black;">rev_host</span> = rev_host
        <span style="color: #008000;">self</span>.<span style="color: black;">visit_count</span> = visit_count
        <span style="color: #008000;">self</span>.<span style="color: black;">hidden</span> = hidden
        <span style="color: #008000;">self</span>.<span style="color: black;">typed</span> = typed
        <span style="color: #008000;">self</span>.<span style="color: black;">favicon_id</span> = favicon_id
        <span style="color: #008000;">self</span>.<span style="color: black;">frecency</span> = frecency
        <span style="color: #008000;">self</span>.<span style="color: black;">last_visit_date</span> = last_visit_date
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot;&lt;Places - '%s': '%s' - '%s'&gt;&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: #008000;">id</span>, <span style="color: #008000;">self</span>.<span style="color: black;">title</span>,
                                                 <span style="color: #008000;">self</span>.<span style="color: black;">url</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> loadSession<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    metadata = Base.<span style="color: black;">metadata</span>
    Session = sessionmaker<span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span>
    session = Session<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> session
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    session = loadSession<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    res = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>Places<span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> res<span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>.<span style="color: black;">title</span></pre>
<p>We switched things up a bit with this example by setting it up for a different table: &#8220;moz_places&#8221;. You&#8217;ll notice that you set up the columns here by creating class variables. If you want to access the instance&#8217;s variables, you need to redefine them in the __init__. If you don&#8217;t do this, you&#8217;ll end up with some pretty confusing issues. The __repr__ is there as a &#8220;pretty print&#8221; method. When you print one of the &#8220;Places&#8221; objects, you&#8217;ll get whatever __repr__ returns. Other than that, the code is pretty similar to the other pieces that we&#8217;ve seen.</p>
<h2>Wrapping Up</h2>
<p>As you can see, using SqlAlchemy to connect to databases is a breeze. Most of the time, you will know ahead of time what the database&#8217;s design is, either from documentation, because you built it yourself, or because you have some utility that can tell you. Having that information is helpful when it comes to defining the tables in SqlAlchemy, but now you know what to try even if you don&#8217;t know the table&#8217;s configuration beforehand! Isn&#8217;t learning Python tricks fun? See you next time!</p>
<h2>Further Reading</h2>
<ul>
<li><a href="http://www.sqlalchemy.org/">SqlAlchemy official site</a></li>
<li><a href="http://elixir.ematia.de/trac/wiki">Elixir official site</a></li>
</ul>
<h2>Downloads</h2>
<ul>
<li><a href='http://www.blog.pythonlibrary.org/wp-content/uploads/2010/09/SqlAlchemy_existing_db.tar'>SqlAlchemy_existing_db.tar</a></li>
<li><a href='http://www.blog.pythonlibrary.org/wp-content/uploads/2010/09/SqlAlchemy_existing_db.zip'>SqlAlchemy_existing_db.zip</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/09/10/sqlalchemy-connecting-to-pre-existing-databases/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Another Step-by-Step SqlAlchemy Tutorial (part 2 of 2)</title>
		<link>http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-2-of-2/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-2-of-2/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 01:32:06 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SqlAlchemy]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=517</guid>
		<description><![CDATA[In the first part of this series, we went over what some might call the &#8220;SQL Expression&#8221; method of using SqlAlchemy to interact with your database. The theory behind this is that we should learn the less abstract way of doing things before we get to the higher level (and more abstract) methods. This is [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-2-of-2/" data-url="http://bit.ly/uC7cB1" data-text="Another Step-by-Step SqlAlchemy Tutorial (part 2 of 2)" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-2-of-2/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-2-of-2/";
			reddit_title = "Another Step-by-Step SqlAlchemy Tutorial (part 2 of 2)";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-2-of-2/"></g:plusone></div></div><p>In the first part of this series, we went over what some might call the &#8220;SQL Expression&#8221; method of using SqlAlchemy to interact with your database. The theory behind this is that we should learn the less abstract way of doing things before we get to the higher level (and more abstract) methods. This is true in many math classes, like Calculus where you learn the long way to find the standard deviation of some calulation before you learn about the shortcut.</p>
<p>For the second half, we will be doing what some might say is the easy way to use SqlAlchemy. It is known as the &#8220;Object Relational&#8221; method and the <a href="http://www.sqlalchemy.org/docs/ormtutorial.html">official documentation</a> actually starts with it. This methodology takes a little longer to set up initially, but in many ways, it is also much easier to follow.<span id="more-517"></span></p>
<h2>Getting Used to Data Mapping</h2>
<p>Robin Munn&#8217;s old school <a href="http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html">SqlAlchemy tutorial</a> called this section &#8220;data mapping&#8221; because we&#8217;ll be mapping the data in a database to Python classes. Let&#8217;s get started!</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Column, MetaData, Table
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Integer, String, ForeignKey
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> mapper, sessionmaker
&nbsp;
<span style="color: #808080; font-style: italic;">####################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> User<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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>, name, fullname, password<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">name</span> = name
        <span style="color: #008000;">self</span>.<span style="color: black;">fullname</span> = fullname
        <span style="color: #008000;">self</span>.<span style="color: black;">password</span> = password
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><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;">return</span> <span style="color: #483d8b;">&quot;&lt;User('%s','%s', '%s')&gt;&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">name</span>, <span style="color: #008000;">self</span>.<span style="color: black;">fullname</span>, <span style="color: #008000;">self</span>.<span style="color: black;">password</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># create a connection to a sqlite database</span>
<span style="color: #808080; font-style: italic;"># turn echo on to see the auto-generated SQL</span>
engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sqlite:///tutorial.db&quot;</span>, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># this is used to keep track of tables and their attributes</span>
metadata = MetaData<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
users_table = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">'users'</span>, metadata,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'user_id'</span>, Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'name'</span>, String<span style="color: black;">&#41;</span>,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'fullname'</span>, String<span style="color: black;">&#41;</span>,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'password'</span>, String<span style="color: black;">&#41;</span>
                    <span style="color: black;">&#41;</span>
email_table = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">'email'</span>, metadata,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'email_id'</span>, Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'email_address'</span>, String<span style="color: black;">&#41;</span>,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'user_id'</span>, Integer, ForeignKey<span style="color: black;">&#40;</span><span style="color: #483d8b;">'users.user_id'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
                    <span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># create the table and tell it to create it in the </span>
<span style="color: #808080; font-style: italic;"># database engine that is passed</span>
metadata.<span style="color: black;">create_all</span><span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># create a mapping between the users_table and the User class</span>
mapper<span style="color: black;">&#40;</span>User, users_table<span style="color: black;">&#41;</span></pre>
<p>The first difference to take note of compared to our previous examples is the <em>User</em> class. We have changed our original example (see part one) a little to match what&#8217;s on the official documentation, namely the parameters are now name, full name and password. The rest should look the same until we get to the <em>mapper</em> statement. This handy method allows SqlAlchemy to map the User class to the users_table. This might not seem like a big deal, but this method makes adding users to the database much more straightforward. </p>
<p>However, before we get to that, we need to discuss the <a href="http://www.sqlalchemy.org/docs/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively">Declarative configurational style</a>. While the style above gives us granular control over the table, mapper and class, for the most part we don&#8217;t need it to be that complicated. That is where the Declarative style comes in. It makes configuring everything even easier. The first declarative style that I knew of was an add-on for SqlAlchemy called <a href="http://elixir.ematia.de/trac/wiki">Elixir</a>. This built-in Declarative style isn&#8217;t as full-featured as Elixir, but it&#8217;s handier because you don&#8217;t have the extra dependency. Let&#8217;s see how Declarative is different:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Column, Integer, String, ForeignKey
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">ext</span>.<span style="color: black;">declarative</span> <span style="color: #ff7700;font-weight:bold;">import</span> declarative_base
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> backref, mapper, relation, sessionmaker
&nbsp;
Base = declarative_base<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> User<span style="color: black;">&#40;</span>Base<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">&quot;users&quot;</span>
&nbsp;
    <span style="color: #008000;">id</span> = Column<span style="color: black;">&#40;</span>Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    name = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#41;</span>
    fullname = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#41;</span>
    password = Column<span style="color: black;">&#40;</span>String<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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>, name, fullname, password<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">name</span> = name
        <span style="color: #008000;">self</span>.<span style="color: black;">fullname</span> = fullname
        <span style="color: #008000;">self</span>.<span style="color: black;">password</span> = password
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><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;">return</span> <span style="color: #483d8b;">&quot;&lt;User('%s','%s', '%s')&gt;&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">name</span>, <span style="color: #008000;">self</span>.<span style="color: black;">fullname</span>, <span style="color: #008000;">self</span>.<span style="color: black;">password</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Address<span style="color: black;">&#40;</span>Base<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Address Class
&nbsp;
    Create some class properties before initilization
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">&quot;addresses&quot;</span>
    <span style="color: #008000;">id</span> = Column<span style="color: black;">&#40;</span>Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    email_address = Column<span style="color: black;">&#40;</span>String, nullable=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
    user_id = Column<span style="color: black;">&#40;</span>Integer, ForeignKey<span style="color: black;">&#40;</span><span style="color: #483d8b;">'users.id'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># creates a bidirectional relationship</span>
    <span style="color: #808080; font-style: italic;"># from Address to User it's Many-to-One</span>
    <span style="color: #808080; font-style: italic;"># from User to Address it's One-to-Many</span>
    <span style="color: #dc143c;">user</span> = relation<span style="color: black;">&#40;</span>User, backref=backref<span style="color: black;">&#40;</span><span style="color: #483d8b;">'addresses'</span>, order_by=<span style="color: #008000;">id</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</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>, email_address<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">email_address</span> = email_address
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><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;">return</span> <span style="color: #483d8b;">&quot;&lt;Address('%s')&gt;&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: #008000;">self</span>.<span style="color: black;">email_address</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;"># create a connection to a sqlite database</span>
<span style="color: #808080; font-style: italic;"># turn echo on to see the auto-generated SQL</span>
engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sqlite:///tutorial.db&quot;</span>, echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># get a handle on the table object</span>
users_table = User.__table__
<span style="color: #808080; font-style: italic;"># get a handle on the metadata</span>
metadata = Base.<span style="color: black;">metadata</span>
metadata.<span style="color: black;">create_all</span><span style="color: black;">&#40;</span>engine<span style="color: black;">&#41;</span></pre>
<p>As you can see, almost everything is now created in classes. We create class attributes (which are like global variables for the class) that identify the columns of the table. Then we create the same __init__ that we had in the original class example above. Also, we sub-class <em>declarative_base</em> rather than the basic <em>object</em>. If we need a table object, we have to call the following magic method <em>User.__table__</em>; and to get the metadata, we need to call <em>Base.metadata</em>. That covers the differences that we care about. Now we can look at how to add data to our database.</p>
<h2>Class is now in Session</h2>
<p>The beauty of using the Object Relational method for interacting with our database can be shown in a few quick code snippets. Let&#8217;s see how we can create a row:</p>
<pre class="python">mike_user = User<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;mike&quot;</span>, <span style="color: #483d8b;">&quot;Mike Driscoll&quot;</span>, <span style="color: #483d8b;">&quot;password&quot;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;User name: %s, fullname: %s, password: %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>mike_user.<span style="color: black;">name</span>,
                                                     mike_user.<span style="color: black;">fullname</span>,
                                                     mike_user.<span style="color: black;">password</span><span style="color: black;">&#41;</span></pre>
<p>As you can see, we can create users with the User class. We can use dot-notation to access the attributes, just as we would in any other Python class. We can even use them to update the rows. For example, if we need to change the user object above, we would do the following:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># this is how you would change the name field</span>
mike_user.<span style="color: black;">fullname</span> = <span style="color: #483d8b;">&quot;Mike Dryskull&quot;</span></pre>
<p>Note that none of this will add the row to the database automatically like those insert methods that we looked at in our first article. Instead, we need a Session object to do that. Let&#8217;s run through some of the basics of using a Session:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> sessionmaker
&nbsp;
Session = sessionmaker<span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span>
session = Session<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
mike_user = User<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;mike&quot;</span>, <span style="color: #483d8b;">&quot;Mike Driscoll&quot;</span>, <span style="color: #483d8b;">&quot;password&quot;</span><span style="color: black;">&#41;</span>
session.<span style="color: black;">add</span><span style="color: black;">&#40;</span>mike_user<span style="color: black;">&#41;</span></pre>
<p>We&#8217;ll pause here to explain what&#8217;s going on. First we need to import the <em>sessionmaker</em> from <em>sqlalchemy.orm</em> and bind it to an engine (technically, you can create the session without binding, but to do anything useful, you&#8217;ll need to bind it eventually). Next we create a session instance. Then we instantiate a user object and add it to the session. At this point, no SQL code has been run and the transaction is just pending. To persist this row, we would need to call <em>session.commit()</em> or run a query.</p>
<p>If you need to add multiple users, you do this:</p>
<pre class="python">session.<span style="color: black;">add_all</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>
     User<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Mary'</span>, <span style="color: #483d8b;">'Mary Wonka'</span>, <span style="color: #483d8b;">'foobar'</span><span style="color: black;">&#41;</span>,
     User<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Sue'</span>, <span style="color: #483d8b;">'Sue Lawhead'</span>, <span style="color: #483d8b;">'xxg527'</span><span style="color: black;">&#41;</span>,
     User<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Fay'</span>, <span style="color: #483d8b;">'Fay Ray'</span>, <span style="color: #483d8b;">'blah'</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span></pre>
<p>If you happen to change one of the user&#8217;s attributes after committing it to the database, you can use <em>session.dirty</em> to check which one was modified. If you just need to know what&#8217;s rows are pending, call <em>session.new</em>. Finally, we can use <em>session.rollback()</em> to rollback a transaction. </p>
<p>Now let&#8217;s take a look at some sample queries:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># do a Select all</span>
all_users = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>User<span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># Select just one user by the name of &quot;mike&quot;</span>
our_user = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>User<span style="color: black;">&#41;</span>.<span style="color: black;">filter_by</span><span style="color: black;">&#40;</span>name=<span style="color: #483d8b;">'mike'</span><span style="color: black;">&#41;</span>.<span style="color: black;">first</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> our_user
&nbsp;
<span style="color: #808080; font-style: italic;"># select users that match &quot;Mary&quot; or &quot;Fay&quot;</span>
users = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>User<span style="color: black;">&#41;</span>.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>User.<span style="color: black;">name</span>.<span style="color: black;">in_</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'Mary'</span>, <span style="color: #483d8b;">'Fay'</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> users
&nbsp;
<span style="color: #808080; font-style: italic;"># select all and print out all the results sorted by id</span>
<span style="color: #ff7700;font-weight:bold;">for</span> instance <span style="color: #ff7700;font-weight:bold;">in</span> session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>User<span style="color: black;">&#41;</span>.<span style="color: black;">order_by</span><span style="color: black;">&#40;</span>User.<span style="color: #008000;">id</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> instance.<span style="color: black;">name</span>, instance.<span style="color: black;">fullname</span></pre>
<p>We don&#8217;t need to go over each of these as they all have explanations in the comments. Instead, we&#8217;ll move on to the topic of joins.</p>
<h2>Join in the Fun</h2>
<p>There are joins using the <a href="http://www.sqlalchemy.org/docs/sqlexpression.html#using-joins">SQL Expression syntax </a>that I won&#8217;t be covering here. Rather, we will use the Object Relational methodology. If you look back at either of the beginning examples for creating the tables, you will notice that we have already set up the join with the <em>ForeignKey </em>object. The Declarative format looked like this:</p>
<pre class="python">user_id = Column<span style="color: black;">&#40;</span>Integer, ForeignKey<span style="color: black;">&#40;</span><span style="color: #483d8b;">'users.id'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># creates a bidirectional relationship</span>
<span style="color: #808080; font-style: italic;"># from Address to User it's Many-to-One</span>
<span style="color: #808080; font-style: italic;"># from User to Address it's One-to-Many</span>
<span style="color: #dc143c;">user</span> = relation<span style="color: black;">&#40;</span>User, backref=backref<span style="color: black;">&#40;</span><span style="color: #483d8b;">'addresses'</span>, order_by=<span style="color: #008000;">id</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre>
<p>Let&#8217;s see how this works by creating a new user:</p>
<pre class="python">prof = User<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Prof&quot;</span>, <span style="color: #483d8b;">&quot;Prof. Xavier&quot;</span>, <span style="color: #483d8b;">&quot;fudge&quot;</span><span style="color: black;">&#41;</span>
prof.<span style="color: black;">addresses</span></pre>
<p>Because of the <em>ForeignKey </em>and the <em>backref </em>command, the <em>User </em>object has an <em>addresses</em> attribute. If you run that code, you will see that it is empty. Let&#8217;s add some addresses! (Note: Be sure to add the prof user to the session: session.add(prof) )</p>
<pre class="python">prof.<span style="color: black;">addresses</span> = <span style="color: black;">&#91;</span>Address<span style="color: black;">&#40;</span>email_address=<span style="color: #483d8b;">'profx@dc.com'</span><span style="color: black;">&#41;</span>,
                        Address<span style="color: black;">&#40;</span>email_address=<span style="color: #483d8b;">'xavier@yahoo.com'</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span></pre>
<p>See how easy that was? It&#8217;s even easy to get the information back out. For example, if you wanted to access just the first address, you would just call <em>prof.addresses[0]</em>. Now, say that you need to change one of the addresses (i.e. do an UPDATE). It&#8217;s as easy as pie:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># change the first address</span>
prof.<span style="color: black;">addresses</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>.<span style="color: black;">email_address</span> = <span style="color: #483d8b;">&quot;profx@marvel.com&quot;</span></pre>
<p>Now let&#8217;s move on to doing queries on joins:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">for</span> u, a <span style="color: #ff7700;font-weight:bold;">in</span> session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>User, Address<span style="color: black;">&#41;</span>.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>User.<span style="color: #008000;">id</span>==Address.<span style="color: black;">user_id</span><span style="color: black;">&#41;</span>.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>Address.<span style="color: black;">email_address</span>==<span style="color: #483d8b;">'xavier@yahoo.com'</span><span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> u, a</pre>
<p>That is one long query! I find those hard to follow myself, so I usually do the following to make it easier on my brain:</p>
<pre class="python">sql = session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>User, Address<span style="color: black;">&#41;</span>
sql = sql.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>User.<span style="color: #008000;">id</span>==Address.<span style="color: black;">user_id</span><span style="color: black;">&#41;</span>
sql = sql.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>Address.<span style="color: black;">email_address</span>==<span style="color: #483d8b;">'xavier@yahoo.com'</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> u, a <span style="color: #ff7700;font-weight:bold;">in</span> sql.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> u, a</pre>
<p>Now, for those of you that like the one-liners, there is nothing wrong with the first example. It will produce the exact same results. I just happen to find the longer version easier to debug. Finally, we can also use a real join:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">orm</span> <span style="color: #ff7700;font-weight:bold;">import</span> join
session.<span style="color: black;">query</span><span style="color: black;">&#40;</span>User<span style="color: black;">&#41;</span>.<span style="color: black;">select_from</span><span style="color: black;">&#40;</span>join<span style="color: black;">&#40;</span>User, Address<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>.<span style="color: #008000;">filter</span><span style="color: black;">&#40;</span>Address.<span style="color: black;">email_address</span>==<span style="color: #483d8b;">'xavier@yahoo.com'</span><span style="color: black;">&#41;</span>.<span style="color: black;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>This also does the same as the previous two examples, but in a more explicit manner. For more information on joins using the Object Relational syntax, I recommend the <a href="http://www.sqlalchemy.org/docs/ormtutorial.html">official documentation</a>.</p>
<h2>Wrapping Up</h2>
<p>At this point, you should be able to create your database with tables, populate the tables with data as well as select, update and commit transactions to your database using SqlAlchemy. I hope you found this tutorial helpful in understanding this amazing technology. </p>
<p><em>Note: This tutorial was tested on Windows with Python 2.5 and SqlAlchemy 0.5.8.</em></p>
<p><b>Further Reading</b></p>
<ul>
<li><a href="http://www.sqlalchemy.org/docs/ormtutorial.html">Object Relational Tutorial</a></li>
<li><a href="http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html">Robin Munn&#8217;s SqlAlchemy Tutorial</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-2-of-2/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Another Step-by-Step SqlAlchemy Tutorial (part 1 of 2)</title>
		<link>http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-1-of-2/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-1-of-2/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 01:31:59 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[SqlAlchemy]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=487</guid>
		<description><![CDATA[A long time ago (circa 2007 if Google serves me right), there was a Python programmer named <a href="http://wiki.wxpython.org/Robin%20Munn">Robin Munn</a> who wrote a really nice <a href="http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html">tutorial</a> on <a href="http://www.sqlalchemy.org/">SqlAlchemy</a>. It was originally based on the 0.1 release, but updated for the newer 0.2. Then, Mr. Munn just disappeared and the tutorial was never updated. I having been kicking around the idea of releasing my own version of this tutorial for quite some time and finally decided to just do it. I hope you will find this article helpful as I found the original to be.]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-1-of-2/" data-url="http://bit.ly/uvLTJR" data-text="Another Step-by-Step SqlAlchemy Tutorial (part 1 of 2)" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-1-of-2/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-1-of-2/";
			reddit_title = "Another Step-by-Step SqlAlchemy Tutorial (part 1 of 2)";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-1-of-2/"></g:plusone></div></div><p>A long time ago (circa 2007 if Google serves me right), there was a Python programmer named <a href="http://wiki.wxpython.org/Robin%20Munn">Robin Munn</a> who wrote a really nice <a href="http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html">tutorial</a> on <a href="http://www.sqlalchemy.org/">SqlAlchemy</a>. It was originally based on the 0.1 release, but updated for the newer 0.2. Then, Mr. Munn just disappeared and the tutorial was never updated. I have been kicking around the idea of releasing my own version of this tutorial for quite some time and finally decided to just do it. I hope you will find this article helpful as I found the original to be.<span id="more-487"></span></p>
<h2>Getting Started</h2>
<p>SqlAlchemy is usually referred to as an Object Relational Mapper (ORM), although it is much more full featured than any of the other Python ORMs that I&#8217;ve used, such as SqlObject or the one that&#8217;s built into Django. SqlAlchemy was founded by a fellow named <a href="http://techspot.zzzeek.org/">Michael Bayer</a>. I usually see <a href="http://spyced.blogspot.com/">Jonathan Ellis&#8217;</a> name floating around the project a lot too, especially at <a href="http://www.pycon.org/">PyCon</a>.</p>
<p>This tutorial will be based on the latest released version of SqlAlchemy: 0.5.8. You can check your version by doing the following:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> sqlalchemy
<span style="color: #ff7700;font-weight:bold;">print</span> sqlalchemy.__version__</pre>
<p><em>Note: I&#8217;ll also be using Python 2.5 on Windows for testing. However, this code should work equally well on Mac and Linux. If you need SqlAlchemy to work on Python 3, then you&#8217;ll want the SVN version of 0.6. The website gives instructions on how to do acquire the code.<br />
</em></p>
<p>If you don&#8217;t happen to have SqlAlchemy, you can <a href="http://www.sqlalchemy.org/download.html">download</a> it from their website or use easy_install if you have <a href="http://pypi.python.org/pypi/setuptools">setuptools</a> installed. Let&#8217;s see how:</p>
<p>In the case of downloading the source, you&#8217;ll need to extract it and then open a console window (on Windows, go to Start, Run and type &#8220;cmd&#8221;, without the quotes). Then change directories until you are in the unzipped folder. To install, do this:</p>
<p><code><br />
python setup.py install<br />
</code></p>
<p>You may need to specify the path to your python if it&#8217;s not on the system path. For easy_install, it&#8217;s even easier:</p>
<p><code><br />
easy_install sqlalchemy<br />
</code></p>
<p>This also assumes that you have easy_install on your path. If you do not, then use the full path to use it (i.e. c:\python25\scripts\easy_install or whatever).</p>
<h1>Creating the First Script</h1>
<p>Now we get to create our first example using SqlAlchemy. We will create a simple table to store a user&#8217;s name, their age and their password.</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> MetaData, Column, Table, ForeignKey
<span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> Integer, String
&nbsp;
engine = create_engine<span style="color: black;">&#40;</span><span style="color: #483d8b;">'sqlite:///tutorial.db'</span>,
                       echo=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
&nbsp;
metadata = MetaData<span style="color: black;">&#40;</span>bind=engine<span style="color: black;">&#41;</span>
&nbsp;
users_table = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">'users'</span>, metadata,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'id'</span>, Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'name'</span>, String<span style="color: black;">&#40;</span><span style="color: #ff4500;">40</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'age'</span>, Integer<span style="color: black;">&#41;</span>,
                    Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'password'</span>, String<span style="color: black;">&#41;</span>,
                    <span style="color: black;">&#41;</span>
&nbsp;
addresses_table = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">'addresses'</span>, metadata,
                        Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'id'</span>, Integer, primary_key=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>,
                        Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'user_id'</span>, <span style="color: #008000;">None</span>, ForeignKey<span style="color: black;">&#40;</span><span style="color: #483d8b;">'users.id'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,
                        Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">'email_address'</span>, String, nullable=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
                        <span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># create tables in database</span>
metadata.<span style="color: black;">create_all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<h2>Looking Deeper</h2>
<p>As you can see, we needed to import various bits and pieces from the sqlalchemy package, namely create_engine, MetaData, Column, Table, Integer,  and String. Then we create an &#8220;engine&#8221; which is basically an object that knows how to communicate with the provided database using the credentials you supply. In this case, we are using a Sqlite database that doesn&#8217;t need credentials. There are <a href="http://www.sqlalchemy.org/docs/dbengine.html">in-depth docs</a> on this subject alone where you can read up on for your favorite database flavor. Also notice that we set echo to True. This means that SqlAlchemy will output all the SQL command it is executing to stdout. This is handy for debugging, but should be set to False when you&#8217;re ready to put the code into production.</p>
<p>Next, we create a MetaData object. This cool creation from the SqlAlchemy team holds all the database metadata. It consists of Python objects that hold descriptions of the tables and other schema-level objects of the database. We can bind the metadata object to our database here or in the <em>create_all</em> statement near the end of the code.</p>
<p>The last section is how we create the tables programmatically. This is accomplished by using SqlAlchemy&#8217;s Table and Column objects. Notice that we have various field types available to us, like String and Integer. There are many others too. For this example, we create a database and name it &#8220;users&#8221;, then pass in our metadata object. Next, we put it in the Columns. The &#8220;id&#8221; column is set as our primary key. SqlAlchemy will magically increment this for us as we add users to the database. The &#8220;name&#8221; column is a String type and capped at 40 characters long. The &#8220;age&#8221; column is just a simple Integer and the &#8220;password&#8221; column is just set to String. We didn&#8217;t set its length, but we probably should. The only major difference in the <em>addresses_table</em> is how we set up the Foreign key attribute that connects the two tables. Basically, we point it at the other table by passing the correct field name in a string to the ForeignKey object.</p>
<p>The final line of this snippet actually creates the database and the table. You can call it as often as you like as it will always check for the existence of the specified table before trying to create it. That means you can create additional tables and call create_all and SqlAlchemy will only create the new table.</p>
<p>SqlAlchemy also provides a way to load tables that were previously created:</p>
<pre class="python">someTable = Table<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;users&quot;</span>, metadata, autoload=<span style="color: #008000;">True</span>, schema=<span style="color: #483d8b;">&quot;schemaName&quot;</span><span style="color: black;">&#41;</span></pre>
<p>I&#8217;ve noticed that with this release, SqlAlchemy has gotten pretty picky about having the database schema specified when you autoload a database. Should you have that issue, you&#8217;ll need to add the following to your Table definition: schema=&#8221;some schema&#8221;. For more information, see the <a href="http://www.sqlalchemy.org/docs/metadata.html#specifying-the-schema-name">documentation</a>.</p>
<h2>Inserting</h2>
<p>There are several ways to add and extract information from the database. We&#8217;ll look at the low-level ways first and then in one of the other parts of this series, we&#8217;ll get into Sessions and the Declarative styles which tend to be slightly more abstract. Let&#8217;s take a look at the different ways to Insert data into our database:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># create an Insert object</span>
ins = users_table.<span style="color: black;">insert</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># add values to the Insert object</span>
new_user = ins.<span style="color: black;">values</span><span style="color: black;">&#40;</span>name=<span style="color: #483d8b;">&quot;Joe&quot;</span>, age=<span style="color: #ff4500;">20</span>, password=<span style="color: #483d8b;">&quot;pass&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># create a database connection</span>
conn = engine.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #808080; font-style: italic;"># add user to database by executing SQL</span>
conn.<span style="color: black;">execute</span><span style="color: black;">&#40;</span>new_user<span style="color: black;">&#41;</span></pre>
<p>The code above shows how to use a Connection object to do the insert. First, you need to create the Insert object by calling the table&#8217;s <em>insert </em>method. Then you can use the Insert&#8217;s <em>values</em> method to add the required values for the row. Next, we create the Connection object via the engine&#8217;s <em>connect</em> method. Finally, we call the Connection object&#8217;s <em>execute </em>method on the Insert object. It sounds kind of complicated, but it&#8217;s actually pretty easy. </p>
<p>This next snippet shows a couple ways to do an insert without the Connection object:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># a connectionless way to Insert a user</span>
ins = users_table.<span style="color: black;">insert</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
result = engine.<span style="color: black;">execute</span><span style="color: black;">&#40;</span>ins, name=<span style="color: #483d8b;">&quot;Shinji&quot;</span>, age=<span style="color: #ff4500;">15</span>, password=<span style="color: #483d8b;">&quot;nihongo&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># another connectionless Insert</span>
result = users_table.<span style="color: black;">insert</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">execute</span><span style="color: black;">&#40;</span>name=<span style="color: #483d8b;">&quot;Martha&quot;</span>, age=<span style="color: #ff4500;">45</span>, password=<span style="color: #483d8b;">&quot;dingbat&quot;</span><span style="color: black;">&#41;</span></pre>
<p>In both cases, you will need to call the table object <em>insert</em> method. Basically, you just take the engine out of the picture in the second instance. The last insert method we&#8217;ll look at is how to insert multiple rows:</p>
<pre class="python">conn.<span style="color: black;">execute</span><span style="color: black;">&#40;</span>users_table.<span style="color: black;">insert</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, <span style="color: black;">&#91;</span>
    <span style="color: black;">&#123;</span><span style="color: #483d8b;">&quot;name&quot;</span>: <span style="color: #483d8b;">&quot;Ted&quot;</span>, <span style="color: #483d8b;">&quot;age&quot;</span>:<span style="color: #ff4500;">10</span>, <span style="color: #483d8b;">&quot;password&quot;</span>:<span style="color: #483d8b;">&quot;dink&quot;</span><span style="color: black;">&#125;</span>,
    <span style="color: black;">&#123;</span><span style="color: #483d8b;">&quot;name&quot;</span>: <span style="color: #483d8b;">&quot;Asahina&quot;</span>, <span style="color: #483d8b;">&quot;age&quot;</span>:<span style="color: #ff4500;">25</span>, <span style="color: #483d8b;">&quot;password&quot;</span>:<span style="color: #483d8b;">&quot;nippon&quot;</span><span style="color: black;">&#125;</span>,
    <span style="color: black;">&#123;</span><span style="color: #483d8b;">&quot;name&quot;</span>: <span style="color: #483d8b;">&quot;Evan&quot;</span>, <span style="color: #483d8b;">&quot;age&quot;</span>:<span style="color: #ff4500;">40</span>, <span style="color: #483d8b;">&quot;password&quot;</span>:<span style="color: #483d8b;">&quot;macaca&quot;</span><span style="color: black;">&#125;</span>
<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span></pre>
<p>This is pretty self-explanatory, but the gist is that you need to use the Connection object from earlier and pass it two arguments: the table&#8217;s Insert object and a list of dictionaries which contain column name and value pairs. Please note that by using the <em>execute</em> method, the data is committed to the database in these examples.</p>
<p>Now let&#8217;s move on to doing selects.</p>
<h2>Selecting</h2>
<p>SqlAlchemy provides a robust set of methods to accomplish Selects. We will focus on the simple methods here. For the advanced stuff, I recommend their <a href="http://www.sqlalchemy.org/docs/sqlexpression.html">official documentation</a> and <a href="http://groups.google.com/group/sqlalchemy">mailing list</a>. One of the most common examples is doing a select all, so let&#8217;s start with that:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">sql</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">select</span>
&nbsp;
s = <span style="color: #dc143c;">select</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>users_table<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
result = s.<span style="color: black;">execute</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> row <span style="color: #ff7700;font-weight:bold;">in</span> result:
    <span style="color: #ff7700;font-weight:bold;">print</span> row</pre>
<p>First we have to import the <em>select</em> method from sqlalchemy.sql. Then we pass it the table as a one element list. Finally we call the select object&#8217;s <em>execute</em> method and store the returned data in the <em>result</em> variable. Now that we have all the results, we should probably see if we got what we expected. Thus, we create a <em>for</em> loop to iterate over the result. </p>
<p>If you need all the results in a list of tuples rather than Row object, you can do the following:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># get all the results in a list of tuples</span>
conn = engine.<span style="color: black;">connect</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
res = conn.<span style="color: black;">execute</span><span style="color: black;">&#40;</span>s<span style="color: black;">&#41;</span>
rows = res.<span style="color: black;">fetchall</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>And if you just need the first result back, then you use fetchone() instead of fetchall():</p>
<pre class="python">res = conn.<span style="color: black;">execute</span><span style="color: black;">&#40;</span>s<span style="color: black;">&#41;</span>
row = res.<span style="color: black;">fetchone</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>Now let&#8217;s pretend that we need to get a little bit more granular in our results. In the next example, we just want to return the user&#8217;s name and their age while omitting their password.</p>
<pre class="python">s = <span style="color: #dc143c;">select</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>users_table.<span style="color: black;">c</span>.<span style="color: black;">name</span>, users_table.<span style="color: black;">c</span>.<span style="color: black;">age</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
result = conn.<span style="color: black;">execute</span><span style="color: black;">&#40;</span>s<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> row <span style="color: #ff7700;font-weight:bold;">in</span> result:
    <span style="color: #ff7700;font-weight:bold;">print</span> row</pre>
<p>Well, that was pretty easy. All we had to do was specify the column names in our select statement. The little &#8220;c&#8221; basically means &#8220;column&#8221;, so we do a select on column name and column age. If you had multiple tables, then the select statement would be something like this:</p>
<p>select([tableOne, tableTwo])</p>
<p>Of course, this will probably return duplicate results, so you&#8217;ll want to do something like this to mitigate the issue:</p>
<p>s = select([tableOne, tableTwo], tableOne.c.id==tableTwo.c.user_id)</p>
<p>The SqlAlchemy <a href="http://www.sqlalchemy.org/docs/sqlexpression.html">documentation </a>called the first result a Cartesian product since it caused each row from the first table to be produced against each row of the second table. The second statement above eliminates that annoyance. How? Well, this is the way you do a WHERE clause using this form of a select. In the next part of the series, I&#8217;ll show a different way to do a select and where with sessions.</p>
<p>Here are a couple more examples though with explanations in the comments:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy.<span style="color: black;">sql</span> <span style="color: #ff7700;font-weight:bold;">import</span> and_
&nbsp;
<span style="color: #808080; font-style: italic;"># The following is the equivalent to </span>
<span style="color: #808080; font-style: italic;"># SELECT * FROM users WHERE id &gt; 3</span>
s = <span style="color: #dc143c;">select</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>users_table<span style="color: black;">&#93;</span>, users_table.<span style="color: black;">c</span>.<span style="color: #008000;">id</span> <span style="color: #66cc66;">&gt;</span> <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># You can use the &quot;and_&quot; module to AND multiple fields together</span>
s = <span style="color: #dc143c;">select</span><span style="color: black;">&#40;</span>and_<span style="color: black;">&#40;</span>users_table.<span style="color: black;">c</span>.<span style="color: black;">name</span>==<span style="color: #483d8b;">&quot;Martha&quot;</span>, users_table.<span style="color: black;">c</span>.<span style="color: black;">age</span> <span style="color: #66cc66;">&lt;</span> <span style="color: #ff4500;">25</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre>
<p>The code above illustrates that SqlAlchemy can use operators and conjunctions in their queries as well. I recommend reading their documentation for full details <a href="http://www.sqlalchemy.org/docs/sqlexpression.html">here</a>.</p>
<h2>Wrapping Up</h2>
<p>I think this is a good place for us to stop. We have now learned how to create a database, add rows and select data from our database. In the next part of our series, we will learn the more popular way of doing this using the Object Relation methods. We will also learn about a few other key topics, such as the SqlAlchemy session. We will also look at how joins work in SqlAlchemy. See you then!</p>
<p><b>Further Reading</b></p>
<ul>
<li><a href="http://www.sqlalchemy.org/docs/sqlexpression.html">SQL Expression Tutorial</a></li>
<li><a href="http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html">Robin Munn&#8217;s SqlAlchemy Tutorial</a></li>
</ul>
<p><b>Downloads</b></p>
<ul>
<li><a href='http://www.blog.pythonlibrary.org/wp-content/uploads/2010/01/exampleOne.zip'>SqlAlchemy Demo One.zip</a></li>
<li><a href='http://www.blog.pythonlibrary.org/wp-content/uploads/2010/01/exampleOne.tar'>SqlAlchemy Demo One.tar</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/02/03/another-step-by-step-sqlalchemy-tutorial-part-1-of-2/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
	</channel>
</rss>

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

