<?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>Perplexed Labs</title>
	<atom:link href="http://blog.perplexedlabs.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.perplexedlabs.com</link>
	<description>web development war stories from the frontlines to the backend</description>
	<lastBuildDate>Sat, 24 Jul 2010 16:27:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Tornado 1.0 Released</title>
		<link>http://blog.perplexedlabs.com/2010/07/24/tornado-1-0-released/</link>
		<comments>http://blog.perplexedlabs.com/2010/07/24/tornado-1-0-released/#comments</comments>
		<pubDate>Sat, 24 Jul 2010 16:27:40 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Random]]></category>
		<category><![CDATA[python tornado]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=459</guid>
		<description><![CDATA[Just a quick note that the Tornado team announced the release of version 1.0 on July 22nd. Here's the changelog. Looks like some nice new features - I'm looking forward to upgrading. Related posts:PHP 5.3.0 Released and Firefox 3.5 jQuery 1.4.2 Released Django 1.1 Released


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/06/30/php-5-3-0-released-and-firefox-3-5/' rel='bookmark' title='Permanent Link: PHP 5.3.0 Released and Firefox 3.5'>PHP 5.3.0 Released and Firefox 3.5</a></li>
<li><a href='http://blog.perplexedlabs.com/2010/02/20/jquery-1-4-2-released/' rel='bookmark' title='Permanent Link: jQuery 1.4.2 Released'>jQuery 1.4.2 Released</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/07/29/django-1-1-released/' rel='bookmark' title='Permanent Link: Django 1.1 Released'>Django 1.1 Released</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Just a quick note that the Tornado team announced the release of version 1.0 on July 22nd.</p>
<p>Here's the <a href="http://groups.google.com/group/python-tornado/browse_thread/thread/6040b860b74444e0">changelog</a>.</p>
<p>Looks like some nice new features - I'm looking forward to upgrading.</p>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/06/30/php-5-3-0-released-and-firefox-3-5/' rel='bookmark' title='Permanent Link: PHP 5.3.0 Released and Firefox 3.5'>PHP 5.3.0 Released and Firefox 3.5</a></li>
<li><a href='http://blog.perplexedlabs.com/2010/02/20/jquery-1-4-2-released/' rel='bookmark' title='Permanent Link: jQuery 1.4.2 Released'>jQuery 1.4.2 Released</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/07/29/django-1-1-released/' rel='bookmark' title='Permanent Link: Django 1.1 Released'>Django 1.1 Released</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/07/24/tornado-1-0-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python&#8217;s Tornado has swept me off my feet</title>
		<link>http://blog.perplexedlabs.com/2010/07/01/pythons-tornado-has-swept-me-off-my-feet/</link>
		<comments>http://blog.perplexedlabs.com/2010/07/01/pythons-tornado-has-swept-me-off-my-feet/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 13:00:37 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Infrastructure]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[asynchronous]]></category>
		<category><![CDATA[non-blocking]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[tornado]]></category>
		<category><![CDATA[web.py]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=457</guid>
		<description><![CDATA[I've been working with Python's Tornado for about 2 months now and I love it. Tornado is a non-blocking web server written in Python. It's structure is similar to web.py so users of that popular Python web framework will feel right at home. This is a structure that lends itself really well to developing RESTful [...]


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2010/03/04/python-data-sharing-in-the-multiprocessing-module/' rel='bookmark' title='Permanent Link: Python data sharing in the multiprocessing module'>Python data sharing in the multiprocessing module</a></li>
<li><a href='http://blog.perplexedlabs.com/2010/07/24/tornado-1-0-released/' rel='bookmark' title='Permanent Link: Tornado 1.0 Released'>Tornado 1.0 Released</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/11/10/setup-python-25-mod_wsgi-and-django-10-on-centos-5-cpanel/' rel='bookmark' title='Permanent Link: Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)'>Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I've been working with Python's <a href="http://www.tornadoweb.org/">Tornado</a> for about 2 months now and I love it.</p>
<p>Tornado is a non-blocking web server written in Python.  It's structure is similar to web.py so users of that popular Python web framework will feel right at home.  This is a structure that lends itself really well to developing RESTful APIs as the methods you write to handle incoming requests are named after the HTTP methods used:</p>
<pre class="brush: python;">
class PlaceHandler(tornado.web.RequestHandler):
    def get(self, id):
        # respond to a GET
        self.write('GETting something')

    def post(self):
        # respond to a POST
        self.write('POSTing something')
</pre>
<p>You match URI paths to "handlers" (the <em>controller</em> for those MVC folk) via a list of regex, handler tuples that instantiate an "application".</p>
<pre class="brush: python;">
application = tornado.web.Application([
    (r&quot;/place&quot;, PlaceHandler),
    (r&quot;/place/([0-9]+)&quot;, PlaceHandler)
])

if __name__ == &quot;__main__&quot;:
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
</pre>
<p>As usual any values that are captured from the regex are passed, in order, to the method that receives the request in the handler.</p>
<p>Because of it's non-blocking nature Tornado bundles an asynchronous HTTP client for use internally.  Additional modules include a command line and config file convenience library, escaping, 3rd party authentication (Facebook, Twitter, etc.), a wrapper around MySQLdb, and templating.  All in all this makes it a formidable web framework in its own right, especially if you're looking for something that's light and <a href="http://www.tornadoweb.org/documentation#performance">FAST</a>.</p>
<p>In production, I'm running 4 Tornado instances per server behind <a href="http://nginx.org/">nginx</a>.</p>
<p>One issue not addressed out of the box was daemonizing the Tornado instance.  I added PID file management and the ability to daemonize as follows (pid.py module follows):</p>
<pre class="brush: python;">
# capture stdout/err in logfile
log_file = 'tornado.%s.log' % options.port
log = open(os.path.join(settings.log_path, log_file), 'a+')

# check pidfile
pidfile_path = settings.PIDFILE_PATH % options.port
pid.check(pidfile_path)

# daemonize
daemon_context = daemon.DaemonContext(stdout=log, stderr=log, working_directory='.')
with daemon_context:
    # write the pidfile
    pid.write(pidfile_path)

    # initialize the application
    http_server = tornado.httpserver.HTTPServer(application.app)
    http_server.listen(options.port, '127.0.0.1')

    try:
        # enter the Tornado IO loop
        tornado.ioloop.IOLoop.instance().start()
    finally:
        # ensure we remove the pidfile
        pid.remove(pidfile_path)
</pre>
<p>And now the pid.py module:</p>
<pre class="brush: python;">
# pid.py - module to help manage PID files
import os
import logging
import fcntl
import errno

def check(path):
    # try to read the pid from the pidfile
    try:
        logging.info(&quot;Checking pidfile '%s'&quot;, path)
        pid = int(open(path).read().strip())
    except IOError, (code, text):
        pid = None
        # re-raise if the error wasn't &quot;No such file or directory&quot;
        if code != errno.ENOENT:
            raise

    # try to kill the process
    try:
        if pid is not None:
            logging.info(&quot;Killing PID %s&quot;, pid)
            os.kill(pid, 9)
    except OSError, (code, text):
        # re-raise if the error wasn't &quot;No such process&quot;
        if code != errno.ESRCH:
            raise

def write(path):
    try:
        pid = os.getpid()
        pidfile = open(path, 'wb')
        # get a non-blocking exclusive lock
        fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        # clear out the file
        pidfile.seek(0)
        pidfile.truncate(0)
        # write the pid
        pidfile.write(str(pid))
        logging.info(&quot;Writing PID %s to '%s'&quot;, pid, path)
    except:
        raise
    finally:
        try:
            pidfile.close()
        except:
            pass

def remove(path):
    try:
        # make sure we delete our pidfile
        logging.info(&quot;Removing pidfile '%s'&quot;, path)
        os.unlink(path)
    except:
        pass
</pre>
<p>I'm going to follow up this post another on how I added a simple concept of "models" and an easy way to perform MySQL transactions.  Let me know if you have any specific questions!</p>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2010/03/04/python-data-sharing-in-the-multiprocessing-module/' rel='bookmark' title='Permanent Link: Python data sharing in the multiprocessing module'>Python data sharing in the multiprocessing module</a></li>
<li><a href='http://blog.perplexedlabs.com/2010/07/24/tornado-1-0-released/' rel='bookmark' title='Permanent Link: Tornado 1.0 Released'>Tornado 1.0 Released</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/11/10/setup-python-25-mod_wsgi-and-django-10-on-centos-5-cpanel/' rel='bookmark' title='Permanent Link: Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)'>Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/07/01/pythons-tornado-has-swept-me-off-my-feet/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>google-define and last-fm plugins released</title>
		<link>http://blog.perplexedlabs.com/2010/05/06/google-define-and-last-fm-plugins-released/</link>
		<comments>http://blog.perplexedlabs.com/2010/05/06/google-define-and-last-fm-plugins-released/#comments</comments>
		<pubDate>Thu, 06 May 2010 16:44:58 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[plugins]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=453</guid>
		<description><![CDATA[Over the last few days I released my first open-source plugins on GitHub. google-define - Extracted from a side project I worked on, it's basically a wrapper class for parsing definitions from Google (define:perplexed). last-fm - This plugin was inspired by a previous gist, which itself was taken from an app I wrote to aggregate [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>Over the last few days I released my first open-source plugins on GitHub.</p>
<ul>
<li><a href="http://github.com/speric/google-define">google-define</a> - Extracted from a side project I worked on, it's basically a wrapper class for parsing definitions from Google (define:perplexed).</li>
<li><a href="http://github.com/speric/last-fm">last-fm</a> - This plugin was inspired by a previous <a href="http://gist.github.com/372629">gist</a>, which itself was taken from an app I wrote to aggregate the last week's movies, books, and music to send to Posterous (example <a href="http://www.ericfarkas.com/the-week-in-review-may-03-2010">here</a>). It's another wrapper class for easily parsing last.fm XML feeds.</li>
</ul>
<p>I hope someone finds these useful.  Any and all feedback is appreciated.</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/05/06/google-define-and-last-fm-plugins-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FormStack API Call Over SSL With Ruby</title>
		<link>http://blog.perplexedlabs.com/2010/04/28/formstack-api-call-over-ssl-with-ruby/</link>
		<comments>http://blog.perplexedlabs.com/2010/04/28/formstack-api-call-over-ssl-with-ruby/#comments</comments>
		<pubDate>Wed, 28 Apr 2010 17:45:44 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[Random]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[FormStack]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=449</guid>
		<description><![CDATA[I recently had to use the FormStack API in the context of a Rails app. You need to make these calls over SSL, and API returns either XML or JSON. I chose JSON because it's much easier to work with in my opinion and I hate XML. Below is a simple example. Check out the [...]


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/01/13/installing-ruby-enterprise-edition-with-phusion-passenger/' rel='bookmark' title='Permanent Link: Installing Ruby Enterprise Edition with Phusion Passenger'>Installing Ruby Enterprise Edition with Phusion Passenger</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/02/26/flickr-rss-and-ruby/' rel='bookmark' title='Permanent Link: Flickr, RSS, and Ruby'>Flickr, RSS, and Ruby</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/02/04/building-a-rails-capable-slice-from-scratch/' rel='bookmark' title='Permanent Link: Ruby On Rails and SliceHost Part 1: Initial Setup'>Ruby On Rails and SliceHost Part 1: Initial Setup</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I recently had to use the <a href="http://support.formstack.com/index.php?pg=kb.book&amp;id=3">FormStack API</a> in the context of a Rails app.  You need to make these calls over SSL, and API returns either XML or JSON.  I chose JSON because it's much easier to work with in my opinion and I hate XML.</p>
<p>Below is a simple example.  Check out the <a href="http://support.formstack.com/index.php?pg=kb.book&amp;id=3">FormStack API documentation</a> for all the other API calls.</p>
<p><script src="http://gist.github.com/372524.js"></script></p>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/01/13/installing-ruby-enterprise-edition-with-phusion-passenger/' rel='bookmark' title='Permanent Link: Installing Ruby Enterprise Edition with Phusion Passenger'>Installing Ruby Enterprise Edition with Phusion Passenger</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/02/26/flickr-rss-and-ruby/' rel='bookmark' title='Permanent Link: Flickr, RSS, and Ruby'>Flickr, RSS, and Ruby</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/02/04/building-a-rails-capable-slice-from-scratch/' rel='bookmark' title='Permanent Link: Ruby On Rails and SliceHost Part 1: Initial Setup'>Ruby On Rails and SliceHost Part 1: Initial Setup</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/04/28/formstack-api-call-over-ssl-with-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Learning vs. Solving</title>
		<link>http://blog.perplexedlabs.com/2010/03/15/learning-vs-solving/</link>
		<comments>http://blog.perplexedlabs.com/2010/03/15/learning-vs-solving/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 13:00:07 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[thoughts]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=443</guid>
		<description><![CDATA[Often times you're tasked with solving a problem you haven't faced before, requiring the use of technologies you haven't previously been exposed to. This is a great thing! These experiences are the stuff of legend - continuing deep into the night as your curiosity peaks. When delivery of the solution makes a difference to somebody's [...]


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/05/04/php-jquery-ajax-javascript-long-polling/' rel='bookmark' title='Permanent Link: PHP jQuery AJAX Javascript Long Polling'>PHP jQuery AJAX Javascript Long Polling</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/02/01/get-it-done/' rel='bookmark' title='Permanent Link: Get It Done'>Get It Done</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Often times you're tasked with solving a problem you haven't faced before, requiring the use of technologies you haven't previously been exposed to.  This is a great thing!  These experiences are the stuff of legend - continuing deep into the night as your curiosity peaks.</p>
<p>When delivery of the solution makes a difference to somebody's bottom line you have to balance the opportunity as a means to learn with your desire to deliver for a customer.</p>
<p>Consider this example.  A client recently wanted a private chat system for internal company communications.  The service they had been using wasn't meeting their needs, was littered with bugs, and sometimes didn't work at all.  The core requirement other than privacy, real-time chat, presence, and multi-user chat was that it had to be compliant (all communications stored).  </p>
<p>The learner in me wanted to dive deep, dig into XMPP, build a server from scratch, and accompany that with a web and desktop client.  I spent a few days investigating the technologies involved and even wrote a quick proof of concept (that didn't use XMPP) in PHP.</p>
<p>What I came to realize is that much of the chat landscape had been "solved".  There were rock solid open-source servers that were full-featured, standards compliant, extensible, performant, and scalable (I'm looking at you ejabberd).  In addition, XMPP being such a universally accepted/supported protocol, there were open-source clients for every major OS and even an AJAX web client.</p>
<p>I really did want to write my own XMPP client and server.  Perhaps I will some day, but only if it solves a problem the business is having that can't be solved through the use of existing tools.  In my opinion this is a reminder to "keep your eye on the prize".  If time and resources are infinite then by all means dig in.  Since in business that's rarely (if ever) the case, it's a good lesson learned.</p>
<p>Ask yourself the question "are we in the business of compliant real-time chat?".  If the answer is no take it off the shelf and solve the problem.</p>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/05/04/php-jquery-ajax-javascript-long-polling/' rel='bookmark' title='Permanent Link: PHP jQuery AJAX Javascript Long Polling'>PHP jQuery AJAX Javascript Long Polling</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/02/01/get-it-done/' rel='bookmark' title='Permanent Link: Get It Done'>Get It Done</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/03/15/learning-vs-solving/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Python data sharing in the multiprocessing module</title>
		<link>http://blog.perplexedlabs.com/2010/03/04/python-data-sharing-in-the-multiprocessing-module/</link>
		<comments>http://blog.perplexedlabs.com/2010/03/04/python-data-sharing-in-the-multiprocessing-module/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 13:00:08 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[multiprocessing]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=430</guid>
		<description><![CDATA[Python's multiprocessing module is a great tool that abstracts the details of forking and managing child processes in an interface inspired by the threading module. The benefit to using processes over threads is that you effectively avoid the issues of the GIL (Global Interpreter Lock). I wanted to share my experience with sharing static data [...]


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2010/07/01/pythons-tornado-has-swept-me-off-my-feet/' rel='bookmark' title='Permanent Link: Python&#8217;s Tornado has swept me off my feet'>Python&#8217;s Tornado has swept me off my feet</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/11/10/setup-python-25-mod_wsgi-and-django-10-on-centos-5-cpanel/' rel='bookmark' title='Permanent Link: Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)'>Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)</a></li>
<li><a href='http://blog.perplexedlabs.com/2010/03/02/php-forking-to-concurrency/' rel='bookmark' title='Permanent Link: PHP Forking to Concurrency with pcntl_fork()'>PHP Forking to Concurrency with pcntl_fork()</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Python's <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> module is a great tool that abstracts the details of forking and managing child processes in an interface inspired by the <a href="http://docs.python.org/library/threading.html">threading</a> module.  The benefit to using processes over threads is that you effectively avoid the issues of the GIL (Global Interpreter Lock).</p>
<p>I wanted to share my experience with sharing static data between the parent and the forked children.  The solution I ultimately went with is trivially implemented and works well.  It takes advantage of the fact that the children import the same modules of the parent.  If you house your data in a shared module, it's accessible in both places.</p>
<p>The directory structure looks like this:</p>
<blockquote>
<pre>
mypackage/
    __init__.py
    mp.py
    myglobals.py
myscript.py
</pre>
</blockquote>
<p>Here's my light wrapper around the multiprocessing module, mp.py:</p>
<pre class="brush: python;">
import multiprocessing

import MySQLdb

import myglobals

# handles each unit of work, in this case a SQL query
def worker_do(sql):
    myglobals.cursor.execute(sql)

# called once upon worker initialization
def worker_init():
    myglobals.conn = MySQLdb.connect(**myglobals.config['db'])
    myglobals.cursor = myglobals.conn.cursor()
    myglobals.cursor.execute('SET AUTOCOMMIT=1')

# wrapper for multiprocessing module
def do_work(queue, num_processes):
    pool = multiprocessing.Pool(num_processes, initializer=worker_init)
    pool.map(worker_do, queue, 1)
    pool.close()
    pool.join()
</pre>
<p>And here's my example script, myscript.py:</p>
<pre class="brush: python;">
import os
import sys

import mp
import myglobals

def main():
   # anything in the myglobals module will be accessible by the child processes
   # we could then programatically retrieve this config info from a file
   # via ConfigParser
   #
   # for simplicity I hard-coded it here
   myglobals.config = {
      'db': {
         'host': 'db1',
         'user': 'dbuser',
         'passwd': 'dbpasswd',
         'db': 'dbase'
      }
   }

   # build a whole bunch of queries to perform via the workers
   queries = build_queries()

   # perform the multiprocessing operation
   mp.do_work(queries, 4)

   return 0

if __name__ == '__main__':
   sys.exit(main())
</pre>
<p>In this example the benefit would be to keep your database configuration code DRY - and share that data with the child processes.</p>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2010/07/01/pythons-tornado-has-swept-me-off-my-feet/' rel='bookmark' title='Permanent Link: Python&#8217;s Tornado has swept me off my feet'>Python&#8217;s Tornado has swept me off my feet</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/11/10/setup-python-25-mod_wsgi-and-django-10-on-centos-5-cpanel/' rel='bookmark' title='Permanent Link: Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)'>Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)</a></li>
<li><a href='http://blog.perplexedlabs.com/2010/03/02/php-forking-to-concurrency/' rel='bookmark' title='Permanent Link: PHP Forking to Concurrency with pcntl_fork()'>PHP Forking to Concurrency with pcntl_fork()</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/03/04/python-data-sharing-in-the-multiprocessing-module/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Django Up In Your CRON</title>
		<link>http://blog.perplexedlabs.com/2010/03/02/django-up-in-your-cron/</link>
		<comments>http://blog.perplexedlabs.com/2010/03/02/django-up-in-your-cron/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 13:00:42 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[cron]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=354</guid>
		<description><![CDATA[For one off scripts for a particular project: #!/usr/bin/env python from django.core.management import setup_environ from myapp import settings setup_environ(settings) # do some stuff Related posts:Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel) Getting Started with Django and Python &#8211; First Impressions Adventures in Django and Python &#8211; Part III


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2008/11/10/setup-python-25-mod_wsgi-and-django-10-on-centos-5-cpanel/' rel='bookmark' title='Permanent Link: Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)'>Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/02/08/getting-started-with-django-and-python-first-impressions/' rel='bookmark' title='Permanent Link: Getting Started with Django and Python &#8211; First Impressions'>Getting Started with Django and Python &#8211; First Impressions</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/08/13/adventures-in-django-and-python-part-iii/' rel='bookmark' title='Permanent Link: Adventures in Django and Python &#8211; Part III'>Adventures in Django and Python &#8211; Part III</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>For one off scripts for a particular project:</p>
<pre class="brush: python;">
#!/usr/bin/env python

from django.core.management import setup_environ
from myapp import settings
setup_environ(settings)

# do some stuff
</pre>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2008/11/10/setup-python-25-mod_wsgi-and-django-10-on-centos-5-cpanel/' rel='bookmark' title='Permanent Link: Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)'>Setup Python 2.5, mod_wsgi, and Django 1.0 on CentOS 5 (cPanel)</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/02/08/getting-started-with-django-and-python-first-impressions/' rel='bookmark' title='Permanent Link: Getting Started with Django and Python &#8211; First Impressions'>Getting Started with Django and Python &#8211; First Impressions</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/08/13/adventures-in-django-and-python-part-iii/' rel='bookmark' title='Permanent Link: Adventures in Django and Python &#8211; Part III'>Adventures in Django and Python &#8211; Part III</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/03/02/django-up-in-your-cron/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>PHP Forking to Concurrency with pcntl_fork()</title>
		<link>http://blog.perplexedlabs.com/2010/03/02/php-forking-to-concurrency/</link>
		<comments>http://blog.perplexedlabs.com/2010/03/02/php-forking-to-concurrency/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 13:00:10 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[fork]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[pcntl]]></category>
		<category><![CDATA[pcntl_fork]]></category>
		<category><![CDATA[pcntl_wait]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[process]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[unix]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=376</guid>
		<description><![CDATA[I find it interesting and challenging to bend PHP in ways it probably shouldn't be bent. Almost always I walk away pleasantly surprised at it's ability to solve a variety of problems. Consider this example. Let's say you want to take advantage of more than one core for a given process. Perhaps it performs many [...]


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/05/04/php-libmemcached-via-memcached-and-igbinary/' rel='bookmark' title='Permanent Link: PHP libmemcached via memcached and igbinary'>PHP libmemcached via memcached and igbinary</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/05/04/php-jquery-ajax-javascript-long-polling/' rel='bookmark' title='Permanent Link: PHP jQuery AJAX Javascript Long Polling'>PHP jQuery AJAX Javascript Long Polling</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/04/09/php-daisy-chain-class-method-calls/' rel='bookmark' title='Permanent Link: PHP Daisy Chain Class Method Calls'>PHP Daisy Chain Class Method Calls</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I find it interesting and challenging to bend PHP in ways it probably shouldn't be bent.  Almost always I walk away pleasantly surprised at it's ability to solve a variety of problems.</p>
<p>Consider this example.  Let's say you want to take advantage of more than one core for a given process.  Perhaps it performs many intensive computations and on a single core would take an hour to run.  Since a PHP process is single threaded you won't optimally take advantage of the available multi-core resources you may have.</p>
<p>Fortunately, via the Process Control (<a href="http://php.net/manual/en/book.pcntl.php">PCNTL</a>) extension, PHP provides a way to fork new child processes.  Forking is the concept of duplicating a thread of execution from the parent to a new child.  <a href="http://www.php.net/manual/en/function.pcntl-fork.php">pcntl_fork()</a> is the function that does this.</p>
<p>The framework for using this extension is as follows:</p>
<pre class="brush: php;">
$maxChildren = 4;
$numChildren = 0;
foreach($unitsOfWork as $unit) {
	$pids[$numChildren] = pcntl_fork();
	if(!$pids[$numChildren]) {
		// do work
		doWork($unit);
		posix_kill(getmypid(), 9);
	} else {
		$numChildren++;
		if($numChildren == $maxChildren) {
			pcntl_wait($status);
			$numChildren--;
		}
	}
}
</pre>
<p>When a new child is forked via pcntl_fork() the pid is returned.  The if statement following the fork allows the child and parent to split their flow of execution based on who they are (i.e. the child does the work and kills itself - the parent tests for hitting the max number of children and waits, otherwise it creates another child).  The pcntl_wait() function is called when we hit $maxChildren, it blocks until a child exits.</p>
<p>Remember, if you want use database connections in your children, they each need to initialize their own connection.  Resources such as database connections are not thread safe.</p>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/05/04/php-libmemcached-via-memcached-and-igbinary/' rel='bookmark' title='Permanent Link: PHP libmemcached via memcached and igbinary'>PHP libmemcached via memcached and igbinary</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/05/04/php-jquery-ajax-javascript-long-polling/' rel='bookmark' title='Permanent Link: PHP jQuery AJAX Javascript Long Polling'>PHP jQuery AJAX Javascript Long Polling</a></li>
<li><a href='http://blog.perplexedlabs.com/2008/04/09/php-daisy-chain-class-method-calls/' rel='bookmark' title='Permanent Link: PHP Daisy Chain Class Method Calls'>PHP Daisy Chain Class Method Calls</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/03/02/php-forking-to-concurrency/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>jQuery 1.4.2 Released</title>
		<link>http://blog.perplexedlabs.com/2010/02/20/jquery-1-4-2-released/</link>
		<comments>http://blog.perplexedlabs.com/2010/02/20/jquery-1-4-2-released/#comments</comments>
		<pubDate>Sat, 20 Feb 2010 17:56:56 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=421</guid>
		<description><![CDATA[Just a quick note alerting everyone to the fact that jQuery has gotten EVEN EASIER AND FASTER. Go check out the release notes. Related posts:jQuery 1.4 Released jQuery 1.3.1 Go For Launch jQuery 1.4 Alpha 1 Released


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2010/01/14/jquery-1-4-released/' rel='bookmark' title='Permanent Link: jQuery 1.4 Released'>jQuery 1.4 Released</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/01/24/jquery-131-go-for-launch/' rel='bookmark' title='Permanent Link: jQuery 1.3.1 Go For Launch'>jQuery 1.3.1 Go For Launch</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/12/05/jquery-1-4-alpha-1-released/' rel='bookmark' title='Permanent Link: jQuery 1.4 Alpha 1 Released'>jQuery 1.4 Alpha 1 Released</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Just a quick note alerting everyone to the fact that jQuery has gotten EVEN EASIER AND FASTER.</p>
<p>Go check out the <a href="http://blog.jquery.com/2010/02/19/jquery-142-released/">release notes</a>.</p>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2010/01/14/jquery-1-4-released/' rel='bookmark' title='Permanent Link: jQuery 1.4 Released'>jQuery 1.4 Released</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/01/24/jquery-131-go-for-launch/' rel='bookmark' title='Permanent Link: jQuery 1.3.1 Go For Launch'>jQuery 1.3.1 Go For Launch</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/12/05/jquery-1-4-alpha-1-released/' rel='bookmark' title='Permanent Link: jQuery 1.4 Alpha 1 Released'>jQuery 1.4 Alpha 1 Released</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/02/20/jquery-1-4-2-released/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Deployment Using Capistrano / Webistrano via Rails / Phusion Passenger</title>
		<link>http://blog.perplexedlabs.com/2010/02/08/deployment-using-capistrano-and-webistrano-via-rails-and-phusion-passenger/</link>
		<comments>http://blog.perplexedlabs.com/2010/02/08/deployment-using-capistrano-and-webistrano-via-rails-and-phusion-passenger/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 13:00:32 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[Infrastructure]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[deployment]]></category>
		<category><![CDATA[mod_wsgi]]></category>
		<category><![CDATA[mongrel]]></category>
		<category><![CDATA[passenger]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[phusion passenger]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[subversion]]></category>

		<guid isPermaLink="false">http://blog.perplexedlabs.com/?p=408</guid>
		<description><![CDATA[I finally got around to setting up a more sophisticated deployment system for some of my apps. These apps include some built on a custom PHP framework and others that are Python / Django apps. I figured I'd share my experience... Why is a high-level deployment infrastructure important? Deployment is something that should be simple, [...]


Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/01/13/installing-ruby-enterprise-edition-with-phusion-passenger/' rel='bookmark' title='Permanent Link: Installing Ruby Enterprise Edition with Phusion Passenger'>Installing Ruby Enterprise Edition with Phusion Passenger</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/11/30/8-books-to-get-a-developer-for-the-holidays/' rel='bookmark' title='Permanent Link: 8 Books To Get A Developer For The Holidays'>8 Books To Get A Developer For The Holidays</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/06/01/be-language-agnostic-solve-the-problem/' rel='bookmark' title='Permanent Link: Be Language Agnostic &#8211; Solve the Problem!'>Be Language Agnostic &#8211; Solve the Problem!</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I finally got around to setting up a more sophisticated deployment system for some of my apps.  These apps include some built on a custom PHP framework and others that are Python / Django apps.  I figured I'd share my experience...</p>
<p>Why is a high-level deployment infrastructure important?  Deployment is something that should be simple, accessible, and repeatable.  It should be as close to a "single click" as possible.  Previously, for me, it was a bash script that exported some SVN branches.  While this worked fine, as projects progress, you want some accountability, history, and the ability to roll back mission critical applications when something goes wrong with a deploy.</p>
<p><a href="http://www.capify.org/">Capistrano</a> is an open source, command line, deployment tool that provides all of these features.  It's written in Ruby.  You leverage a variety of built in "recipes" (Capistrano's term for a deployment script) that execute certain procedures to deploy an app.  Out-of-the-box it's ideally built to deploy a Rails app.  However, after some minor tweaks it can deploy most anything and do it well.  It can restart servers, update symlinks, change permissions - pretty much anything.  It assumes you access your POSIX compliant server via SSH via the same password (or have ssh keys setup).</p>
<p><a href="http://labs.peritor.com/webistrano">Webistrano</a> is an open source web front-end for Capistrano.  It's a convenience layer that abstracts the command line away and provides an interface to perform the same tasks.  This interface shows history as well as providing a convenient GUI for creating new deployment projects, stages, and recipes.  Highly recommended.</p>
<p>Let's get down to business.  This post makes a few assumptions about things you've already installed and used previously.</p>
<ul>
<li><a href="http://www.ruby-lang.org/en/">Ruby 1.8.5</a>+
<li><a href="http://rubyforge.org/projects/rubygems/">RubyGems</a>
<li><a href="http://www.mysql.com/">MySQL 5.0</a>+
<li><a href="http://www.apache.org/">Apache 2</a>+
<li><a href="http://subversion.tigris.org/">Subversion</a> and a repository containing the "production" branch of your app.
</ul>
<h3>Installing Capistrano</h3>
<p>Well, this is an easy one (you probably want to do this as root):</p>
<blockquote><p>
gem install capistrano
</p></blockquote>
<h3>Installing Webistrano</h3>
<p>Also fairly easy, with a little splash of configuration.</p>
<blockquote><p>
# wget http://labs.peritor.com/webistrano/attachment/wiki/Download/webistrano-1.4.zip<br />
# unzip webistrano-1.4.zip<br />
# mv webistrano-1.4 /path/to/where/you/want/webistrano
</p></blockquote>
<p>Setup the database tables and create a new webistrano user (obviously be conscious of your security preferences for access to your database in the host and password portions):</p>
<blockquote><p>
# mysql<br />
mysql> CREATE DATABASE `webistrano`;<br />
mysql> CREATE USER 'webistrano'@'localhost' IDENTIFIED BY 'password';<br />
mysql> GRANT ALL PRIVILEGES ON `webistrano`.* TO 'webistrano'@'localhost' WITH GRANT OPTION;
</p></blockquote>
<p>Now, in the directory where you placed webistrano you're going to want to copy <i>config/database.yml.sample</i> to <i>config/database.yml</i>.  Edit this file, in the production area, to match your database settings.  By default the file expects a socket to connect, you can chase this by specifying <i>host:</i> and <i>port:</i>.  (Keep in mind Webistrano is simply a Rails app).</p>
<p>You should now be able to have Rails migrate the new database you created.  In the webistrano directory:</p>
<blockquote><p>
# RAILS_ENV=production rake db:migrate
</p></blockquote>
<p>Finally, copy <i>config/webistrano_config.rb.sample</i> to <i>config/webistrano_config.rb</i> and edit according to your preferred mail settings.</p>
<p>We can now test to see if webistrano is working properly by serving it via mongrel:</p>
<blockquote><p>
# ruby script/server -d -e production -p 3000
</p></blockquote>
<p>This starts a single mongrel daemon, using the production environment, listening on port 3000.  You should now be able to hit http://127.0.0.1:3000/ and get the Webistrano login prompt.  If this is working, kill that mongrel instance.</p>
<p>For longer term serving I decided to go with Phusion Passenger (essentially mod_rails for Apache).  It's a nearly zero configuration solution for serving a rails app and will feel at home to anyone with experience serving PHP apps via Apache and mod_php.</p>
<h3>Installing Phusion Passenger</h3>
<p>Again, as root:</p>
<blockquote><p>
# gem install passenger<br />
# passenger-install-apache2-module
</p></blockquote>
<p>The second command will invoke an installer which compiled Passenger and provides instructions on integrating it into your Apache config.  Essentially, edit your httpd.conf as follows (<strong>these were specific to my install, make sure to use the ones provide by the installer for you</strong>):</p>
<blockquote><p>
LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-2.2.9/ext/apache2/mod_passenger.so<br />
PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-2.2.9<br />
PassengerRuby /usr/bin/ruby
</p></blockquote>
<p>Now you can simply add VirtualHost entries to your httpd.conf for any of your Rails apps.  Let's add one for Webistrano:</p>
<blockquote><p>
&lt;VirtualHost *:80&gt;<br />
ServerName webistrano.mydomain.com<br />
DocumentRoot /path/to/webistrano/public<br />
&lt;/VirtualHost&gt;
</p></blockquote>
<p>Yes, Passenger makes it that simple.  Add configuration directives as needed for your environment.</p>
<p>Now Webistrano should be serving from the VirtualHost you specified, seamlessly, via Passenger.</p>
<h3>Deploying A Non-Rails App</h3>
<p>Now the fun stuff.</p>
<p>Capistrano breaks things down into projects, stages, and recipes.  Each app you want managed by capistrano should be it's own project.  Each project should have a stage for at least production and optionally staging and development.</p>
<p>Hosts are added globally and form the targets of a deploy for any given project.  Hosts can include web, app, and database servers.</p>
<p>Deployments in Capistrano are done to a child directory under "releases" named via the date and time of the deployment.  By default 5 releases are kept and available to rollback to.  Upon successful deployment a symlink (default is called "current" and can be modified via the <i>current_path</i> configuration variable) is updated to that release directory.  It is this symlink that should be targeted by your webserver (your DocumentRoot in Apache).</p>
<p>Capistrano also creates a "shared" directory that is symlinked to in each release useful for storing logs and other data that should be maintained through each deployment.</p>
<p>For non-rails apps you'll use the "Pure File" project type when creating your new project.  Upon project creation you can add configuration variables specific to your project.  I recommend using <i>:export</i> instead of <i>:checkout</i> for <i>deploy_via</i> for production subversion deployments as this doesn't expose .svn directories.  Use an SSH user that has enough permissions to create directories where your deploy will occur or, specify <i>use_sudo</i> to true and create a new configuration variable <i>admin_runner</i> and set it to the same user as <i>runner</i>.</p>
<p>Add a stage to your new project for "production".  In the "Manage Hosts" page add a new host for each of your application servers.  Then add each host as a target of your "production" stage of your project.</p>
<p>At this point you should be able to execute the "Setup" task for your "production" stage.  This is a one time task that simply creates the directories.</p>
<p>Assuming this went successfully, try doing a "Deploy" and see if that finishes without error.  You might have to play around with permissions and other minor issues - post a comment if you have any specific questions.</p>
<p>For my PHP framework there are a couple specific tasks I wanted to run in addition to the default Capistrano tasks.  You do this by creating custom recipes in the "Manage Recipes" page in Webistrano.  Recipes are simply procedures written in ruby.  Here's what my recipe looks like:</p>
<pre class="brush: ruby;">
namespace :deploy do
	task :setup, :except =&gt; { :no_release =&gt; true } do
		dirs = [deploy_to, releases_path, shared_path]
		dirs += shared_children.map { |d| File.join(shared_path, d) }
		run &quot;#{try_sudo} mkdir -p #{dirs.join(' ')} &amp;&amp; #{try_sudo} chmod g+w #{dirs.join(' ')}&quot;
		run &quot;chmod 777 #{shared_path}/log&quot;
	end

	task :finalize_update, :except =&gt; { :no_release =&gt; true } do
		run &quot;mkdir -p #{latest_release}/app/tmp&quot;
		run &quot;chmod -R 777 #{latest_release}/app/tmp&quot;
		run &quot;rm -rf #{latest_release}/app/logs&quot;
		run &quot;ln -s #{shared_path}/log #{latest_release}/app/logs&quot;
		run &quot;cp #{latest_release}/public_html/.htaccess-production #{latest_release}/public_html/.htaccess&quot;
		run &quot;cp #{latest_release}/app/config/config-production.php #{latest_release}/app/config/config.php&quot;
		run &quot;cp #{latest_release}/app/config/db-default.php #{latest_release}/app/config/db.php&quot;
		run &quot;cp #{latest_release}/app/config/memcache-default.php #{latest_release}/app/config/memcache.php&quot;
	end
end
</pre>
<p>If you're not familiar with Ruby - what this code is essentially doing is overwriting two tasks in the :deploy namespace with my custom code.</p>
<p>The first, :setup, simply duplicates the base :setup functionality discussed above (creating the releases and shared directories) and chmods the shared log directory to be writable.</p>
<p>The second, :finalize_update, performs a variety of configuration tasks for a PHP app built with my framework.  Also, you'll notice that I'm removing my app's logs directory and symlinking to the shared log directory.  This way all releases will log to the same directory, consistently.  </p>
<p>In my case all of these procedures are command line instructions.  Alternatively, you can do a variety of things leveraging the full breadth of the Ruby language and any gem you'd like to introduce.   Things such as accessing your CDN API to clear image, JS, or CSS caching, etc.</p>
<h3>Deploying Django Apps</h3>
<p>First off it's worth noting that I serve my Django apps via mod_wsgi.  To make the deployment process easier here's what my app.wsgi script looks like:</p>
<pre class="brush: python;">
import os
import sys

appdir = os.path.normpath(os.path.join(os.path.realpath(os.path.dirname(__file__)), '..'))
sys.path.insert(0, appdir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(appdir, '.python-eggs')
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</pre>
<p>This code allows us to avoid having to hardcode paths in the wsgi script (and thus avoid having to change them when we deploy).  It assumes the following directory structure:</p>
<blockquote><p>
.python-eggs (egg cache)<br />
apps (apps path is added to python system path in settings.py)<br />
public (where your .wsgi script resides)<br />
site_media<br />
templates<br />
settings.py<br />
settings-production.py (used for deploy)<br />
urls.py<br />
...
</p></blockquote>
<p>If you follow this convention, the following Capistrano recipe works great:</p>
<pre class="brush: ruby;">
namespace :deploy do
	task :setup, :except =&gt; { :no_release =&gt; true } do
		dirs = [deploy_to, releases_path, shared_path]
		dirs += shared_children.map { |d| File.join(shared_path, d) }
		run &quot;#{try_sudo} mkdir -p #{dirs.join(' ')} &amp;&amp; #{try_sudo} chmod g+w #{dirs.join(' ')}&quot;
		run &quot;chmod 777 #{shared_path}/log&quot;
	end

	task :finalize_update, :except =&gt; { :no_release =&gt; true } do
		run &quot;rm -rf #{latest_release}/logs&quot;
		run &quot;ln -s #{shared_path}/log #{latest_release}/logs&quot;
		run &quot;cp #{latest_release}/settings-production.py #{latest_release}/settings.py&quot;
		run &quot;mkdir -p #{latest_release}/.python-eggs&quot;
		run &quot;chmod 777 #{latest_release}/.python-eggs&quot;
	end
end
</pre>
<h3>Fin</h3>
<p>This should give you a nice intro to leveraging Capistrano via Webistrano.  Feel free to comment with questions, suggestions, or anything else!</p>


<p>Related posts:<ol><li><a href='http://blog.perplexedlabs.com/2009/01/13/installing-ruby-enterprise-edition-with-phusion-passenger/' rel='bookmark' title='Permanent Link: Installing Ruby Enterprise Edition with Phusion Passenger'>Installing Ruby Enterprise Edition with Phusion Passenger</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/11/30/8-books-to-get-a-developer-for-the-holidays/' rel='bookmark' title='Permanent Link: 8 Books To Get A Developer For The Holidays'>8 Books To Get A Developer For The Holidays</a></li>
<li><a href='http://blog.perplexedlabs.com/2009/06/01/be-language-agnostic-solve-the-problem/' rel='bookmark' title='Permanent Link: Be Language Agnostic &#8211; Solve the Problem!'>Be Language Agnostic &#8211; Solve the Problem!</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://blog.perplexedlabs.com/2010/02/08/deployment-using-capistrano-and-webistrano-via-rails-and-phusion-passenger/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
