Posts Tagged ‘django’

I Love Python: ZipFile Edition

Wednesday, July 8th, 2009

For a client web project I needed to create a zip file containing a number of generated XML files. This isn’t something I need to do very often, so I briefly considered just writing the XML files to disk and running a zip command. Ugly, but surely trying to dig up a pleasant Python zip library would be more work?

Turns out Python has had a wonderful zip library in its standard library since 1.6! The zipfile module makes creating zip files a breeze:

import os
from zipfile import ZipFile, ZIP_DEFLATED
 
from django.template.defaultfilters import slugify
 
from somewhere_else import render_spam_xml, render_egg_xml
 
ZIP_PATH = "/some/system/path/for/zips"
 
def create_zip(spam):
    spam_slug = slugify(spam.name)
    filename = "%s.zip" % spam_slug
    abspath = os.path.join(ZIP_PATH, filename)
 
    # Create zip
    z = ZipFile(abspath, "w", ZIP_DEFLATED)
 
    # Write spam xml directly to zip
    z.writestr("%s.xml" % spam_slug, render_spam_xml(spam))
 
    # Write xml files to zip
    for egg in spam.egg_set.all():
        egg_slug = slugify(egg.name)
 
        # Renders the egg object to an xml string
        xml = render_egg_xml(egg)
 
        # Note how easy it is to specify paths in the zip file:
        z.writestr("eggs/%s.xml" % egg_slug, xml)
 
    # Zip file must be closed to be valid
    z.close()
    return abspath

(Sorry for the Django bits in there, but they should be easy to replace.)

My favorite part is that you can use either the ZipFile.write method to add files to the zip or the ZipFile.writestr method to write bytes (strings in my case) directly to the zip file.

At any rate, just wanted to blog about it, so when I need to do it again in a few years I don’t do something stupid like running the zip command.

BitBucket Project for Python FusionCharts Code

Wednesday, April 8th, 2009

After my last post on FusionCharts, someone was nice enough to e-mail me some a Django snippet for exporting FusionCharts as images, so I decided I might as well put the code in a public repository.

While I prefer Bazaar out of all the DVCSes, it seems Mercurial has captured the hearts and minds of the Python empire, so I created the python-fusioncharts project on BitBucket.

If you use Python and FusionCharts, I’d love to add more snippets!

2nd OS Bridge Proposal: Django Introduction

Monday, March 30th, 2009

I just posted my second talk proposal for the Open Source Bridge Conference:


Introduction to Django: The Who, What, and When

As with my other talk, Web Server Shootout, I’m not trying to convince anyone of anything. We’re all already inundated with plenty of senseless marketing and fanboyism.

I’d rather present my knowledge, experiences, mistakes, and opinions in an effort to help others make more intelligent decisions about the development platforms they choose to use.*

Let me know what you think!


*If that was dripping with too much sappy altruism, do remember I get into the conference free if either proposal gets selected. ;-)

(Yet Another) Deploying Django with CherryPy Script

Wednesday, February 18th, 2009

Recently I deployed a Django project on an OSX server. I foolishly thought this would be as easy as on Linux until I ran into the mess that is x86_64 Apache + mod_wsgi* + Django + psycopg2 + i386 PostgreSQL. After wasting far too much time googling and recompiling various bits trying to get everything happy, I followed Eric Florenzano’s post on deploying Django using CherryPy’s** wsgiserver.

Here’s my lightly modified version of Eric’s script:

import wsgiserver
import sys
import os
import django.core.handlers.wsgi
 
if __name__ == "__main__":
    # Setup paths - a bit hackish, but works for me.
    # Assumes an absolute path is stored in <project>.local_settings.ROOT
    sys.path.append(os.path.realpath(os.path.dirname(__file__)))
    from foo.local_settings import ROOT
    sys.path.append(ROOT)
 
    # Startup Django
    os.environ['DJANGO_SETTINGS_MODULE'] = 'foo.settings'
    server = wsgiserver.CherryPyWSGIServer(
        ('0.0.0.0', 8888),  # Use '127.0.0.1' to only bind to the localhost
        django.core.handlers.wsgi.WSGIHandler()
    )
    try:
        server.start()
    except KeyboardInterrupt:
        print 'Stopping'
        server.stop()

I also went with the latest stable version of CherryPy’s wsgiserver instead of checking out trunk like Eric’s post suggested.

Then I just enabled mod_proxy in Apache and setup the following VirtualHost:

<Proxy *>
    Order allow,deny
    Allow from all
</Proxy>
<Location "/">
    ProxyPass http://127.0.0.1:8888/
    ProxyPassReverse http://127.0.0.1:8888/
</Location>

If you’re cool you’ll write some sort of system specific script to launch your web app on boot. In a pinch, you can always use a crontab:

@reboot /usr/bin/python /path/to/app.py &

YMMV ;-)


* To mod_wsgi’s credit, it took about 10 seconds to compile, generated a Universal binary, and in general Just Worked.

** I’m already a CherryPy fan thanks to dowski, so it wasn’t a hard decision.

Introducing Hzzah!

Tuesday, July 15th, 2008

from the I-can-haz-a-search-engine department…

Update: Sorry about the tacky donate link all. I tried to hide it from feed readers with WordPress’s <!–more> feature, but evidently that doesn’t apply to feeds. :(

When it comes to market share, Google is to Searching as Microsoft is to Operating Systems. Thankfully Google has won their dominant position by creating a really amazing product (you can find plenty of discussions on why Microsoft is on top elsewhere).

Recently Yahoo! opened up their search APIs for anyone to use along with a handy Python library. In a time when Yahoo’s very existence is being threatened, I felt a pang of nostalgia for the search engine that fed me decent results for “free dos games” throughout the mid-90s.

So last night I whipped up a little search engine called Hzzah!*

 
BSDtastic!

Features:

  • Simple
  • No ads, cookies, or even JavaScript (at the moment at least)
  • Open Source! BSD to be precise.
  • Did I mention simple? That’s really all it has going for it…

(more…)

Common Django Typo in URLconf

Monday, March 10th, 2008

If you’re hacking Django and get this…

ImproperlyConfigured: Error while importing URLconf 'proj.app.urls': 'tuple' object is not callable

…you’re probably missing a comma in your URL configuration as Rajesh Dhawan pointed out.

Django pros can move along, I know you never make typos. ;)