Tagged: Python Toggle Comment Threads | Keyboard Shortcuts

  • steve918 11:14 pm on March 17, 2009 Permalink | Reply
    Tags: , jquery, Python   

    Expandable Textareas in Django 

    I’m probably not the first one to think of this, but when your writing long posts (like this one) it’s nice to have an expandable text area. This little hack makes use of the jQuery Textarea Resizer plugin. You’ll need to download it along with jQuery and put them somewhere in your media directory.

    Make a copy of the base_site.html template in django/contrib/admin/templates/admin/base_site.html and put it in your apps local template path.

    Add the following template block to /admin/base_site.html

    {% block extrahead %}
        div.grippie {
            background:#EEEEEE url({{ MEDIA_URL }}js/textarea_resize/grippie.png) no-repeat scroll center 2px;
            border-width:0pt 1px 1px;
            margin-left: 106px;
        textarea {
            height: 20%;
        $(document).ready(function() {
    {% endblock %}

    And now you should have nice expandable text-areas that look like this one:

    Expandable Textarea

  • steve918 8:15 am on March 17, 2009 Permalink | Reply
    Tags: , Python, star-rating   

    Spent some time last night playing with … 

    Spent some time last night playing with star ratings in Django, thanks to Ryan Kanno and Leah Culver’s hard work, because it made my job incredibly easy.

  • steve918 2:25 am on January 1, 2009 Permalink | Reply
    Tags: new years, , Python, resolutions   

    New Years Hacking 

    Things I enjoyed hacking on/with most in 2008:

    • Android – I lost count a long time ago of the hundreds of hours wasted hacking on mobile applications for Android.
    • Python – I’ve used Python in the past, but I’ve had the opportunity to write some really applications with it recently and it’s been quite a pleasure.
    • Paver – This is a really great tool for creating administrative task scripts for you applications.
    • Django – Finally reached v 1.0 on my birthday and became the framework with magical pony powers.
    • Amazon Web Services – Seriously could [almost] kiss Jeff Bezos
    • App Engine – Not sure when I’ll ever build a real applications on top of AppEngine, but it was fun

    2008 Hacking Pains:

    • Android – We have a love-hate relationship.
    • PostgreSQL replication
    • Google Doc’s API limitations
    • PHP session garbage collection – Lets roll some dice to see if the next web request is going to be really slow.

    In no particular order, things to learn (more of) in 2009:

    • Erlang
    • Stackless Python
    • Twisted
    • Cocoa, iPhone Development, ObjC
    • Dynamic Programming
    • OpenGL
    • Protobuffers/Thrift
    • Hadoop, CouchDB, Drizzle, Cassandra– Still waiting for an excuse to build something fun using a bleeding-edge database engine.

    If this list seems completely random to you, welcome to the way my mind works. There’s nothing more enjoyable to me than hacking on something I’ve barely heard of before.

  • steve918 8:38 am on April 11, 2008 Permalink | Reply
    Tags: , Error pages, , , Goolge App Engine, Python   

    Custom error pages in GAE/Django 

    To allow for custom error pages (404,500) in Django/Google App Engine all you need is this bit of middle-ware that stubs out the request class for you so that it doesn’t blow up.

    Add your custom templates to your template directory and name them 404.html, 500.html etc.

    Paste the following into middleware/errorpages.py

    class DummyUser(object):
        def get_and_delete_messages(self):
    class NeedsUserObject(object):
        def process_request(self, request):
            request.user = DummyUser()

    In your settings.py add the NeedsUserObject middleware

    • foo 2:53 pm on September 18, 2009 Permalink | Reply

      Thanks:) works great.

  • steve918 11:54 pm on April 10, 2008 Permalink | Reply
    Tags: , , , Python   

    Django manage.py wrapper script for Google App Engine 

    I’m used to running mange.py in my Django apps and I kept forgetting the name of the Google App Engine equivalents. My script only knows how to do two things at the moment, “runserver” and “publish” but now I can manage everything the way I’m accustomed to.

    Update: Aprill 11 – Added toggle_debug, automatically switches debug off when publishing and back on for development.

    #!/usr/bin/env python
    # Simple convience script for common publishing and develop tasks
    # This script expects dev_appserver.py to be in your $PATH
    import os, sys, re
    def main(argv):
        command = ""
            command = argv[1]
        if command == 'publish':
        elif command == 'publish-debug':
        elif command == 'runserver':
        elif command == "--help" or command == "-h":
    def usage():
        print """
        Usage: python manage.py [command] 
            publish - 'updates' Google App Engine with your current version
            publish-debug - 'updates' Goolge App Engine with debug turned on
            runserver - launches the development server on port 8080
            --help, -h - Prints this screen
        For more information on a particular command, run [command] --help
    def get_gae_dir():
        """ Locate dev_appserver.py and return the directory is in. """
        # There's probably a smarter way to do this...
        script = 'dev_appserver.py'
        stdin, stdout = os.popen2('which %s'%script)
        xpath = stdout.read().strip()
        # If the file is a symlink, find out where the actual file lives.
            tmpdir = os.readlink(xpath)
        except OSError:
            tmpdir = xpath
        return os.path.abspath(os.path.dirname(tmpdir))
    def toggle_debug(status):
        st = 'False'
        if status:
            st = 'True'
        orig = open('settings.py.bak').read()
        p = re.compile('DEBUG\s=\s(True|False)')
        n = p.sub('DEBUG = %s'%st,orig)
        nw = open('settings.py','w')
    def gae_parent(script):
        DIR_PATH = get_gae_dir()
        DEV_APPSERVER_PATH = os.path.join(DIR_PATH,'google/appengine/tools/%s'%script)
        EXTRA_PATHS = [
          os.path.join(DIR_PATH, 'lib', 'django'),
          os.path.join(DIR_PATH, 'lib', 'webob'),
          os.path.join(DIR_PATH, 'lib', 'yaml', 'lib'),
        sys.path = EXTRA_PATHS + sys.path
        execfile(DEV_APPSERVER_PATH, globals())
    def publish(debug=False):
        sys.argv[1] = "update"
            sys.argv[2] = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
        except IndexError:
    def runserver():
        sys.argv[1] = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
    if __name__ == '__main__':
  • steve918 6:57 pm on April 9, 2008 Permalink | Reply
    Tags: , , , Python   

    Google App Engine Limitations 

    I’m really digging the concept that is Google App Engine, but I think they a little bit of work to do before I would be willing to put any effort into porting to their platform. Their marketing points for this include the fact that it allows you to build, deploy and iterate your application quickly, but the fact that I have to now port just about every Python library out there to use BigTable and URL fetcher is a serious productivity loss.

    • Python Only – This doesn’t bother me, but is still a deal breaker for a lot of people.
    • No way to schedule tasks. (cron)
    • No way to dynamically route subdomains. You can’t point *.yourdomain.com at a single script. So your urls have to look like example.com/tulsa and not tulsa.example.com
    • You can’t use any existing libraries that make network fetches. Google forces you to use their URL Fetcher class. Which is broken in several ways:
      • No way to set timeout
      • No HTTP Auth Support
      • Does not follow redirects
    • You have to user BigTable for your Database Layer, so you have to port any existing database code you have. There is also no ORM for Django to use BigTable yet, which means Django Admin interface will not work.

    On the bright side, their publishing and versioning process is outstanding. The administration interface is pretty sexy so I’ve take quite a few screen shots for anyone who didn’t get an invite and would like to see it.

    Picture 1

  • steve918 12:59 am on April 8, 2008 Permalink | Reply
    Tags: cloud computing, , , Python   

    Google App Engine SDK 

    I just learned about Google App Engine a couple of hours ago and I have to say I’m pretty excited about what their doing. I really like the fact that they didn’t go out and try to invent their own IDE and scripting language. I’m still really reluctant to move toward cloud computing services. I still want to cling on to my hardware and OS.

    Some cool points:

  • steve918 1:15 pm on February 3, 2008 Permalink | Reply
    Tags: , Php, , Python, Rails, Ruby, Zend Framework   

    Framework Envy 

    I’m typically a PHP guy. I wrote my first web page using PHP3 and have created some pretty robust websites since then and for the most part it’s been a pleasure to work with. I also have a bit of experience using Zend Framework which among other things has a really strong MVC implementation, but I can’t help but feel a bit left behind when I look at features of some other modern frameworks. I’ve been playing around with Django for a few days and a few things have occurred to me.

    Validation logic should be part of the model

    Take a look at this bit of code from Django.

    # in visitor/models.py
    class Visitor(models.Model):
        name = models.CharField(maxlength=30)
        email = models.EmailField(maxlength=200,blank=true)
        website = models.URLField()
        donated = models.DecimalField(max_digits=5, decimal_places=2, blank=true)

    In the Zend_Validator is much more complex, typically happens in the controller and has no direct relationship with the data model your validating for.

    $nameValidator = new Zend_Validate_StringLength(1,30);
    $emailValidator = new Zend_Validate();
    $emailValidator->addValidator(new Zend_Validate_StringLength(0, 200))
                   ->addValidator(new Zend_Validate_EmailAddress());
    // Zend doesn't have a URL validation class, so we would have to
    // create a custom validator that extends Zend_Validate
    $website = new Custom_Validator();
    // This only validates that the number is a floating point number,
    // in reality we would probably have to write another custom validator
    // to validate monetary values.
    $donated = new Zend_Validate_Float();

    The nice thing about Django is the actual database tables are created from the model. So when you declare a name field with the maxlength of 30, your validation rules knows your fields max length because it’s based from the same one line of code the database field was created from! I’m not sure I believe building database tables from your model code is the only way to do things, but I am sure complex validation logic for models belongs in their implementation, not in the controller.

    Template inheritance rocks.

    This is sadly something I had never seen before. Instead of having half a dozen include statements in each of your views you can just have on that says that it extends your base template. The nice thing about this is the child view/template can override what ever portions of the base template it wants, or it can just go with what the parent has. Django’s documentation has a really good example of template inheritance in action.

    An auto generated admin interface is more valuable than gold.

    Before playing with Django I watched a few screen casts to get a feel for what it was all about. Then Django seemed like a one trick pony to me and the one trick seemed a bit lame. I mean, auto generated administration interface… who cares. Since then I’ve learned Django certainly has more than one trick up it’s sleeve and their main act is really beautiful in person. It is honestly as robust (or more so) as any administration interface I’ve built in the past. I expected something clunky and extremely _not_ user friendly. I really expected it to generate an admin interface that made it somewhat more convenient for programmers, but wouldn’t work for the average Joe. Well, when they say it’s “production ready” that’s exactly what they mean. The number of hours this saves (that can be spent developing fun stuff) is extremely valuable.

    Admin scripts

    I know this will sound a bit lazy, but I don’t like having to manually create half a dozen empty folders every time I set up a new project, controller etc. Rails and Django both do a good job of generating framework skeletons for you so you can plug away without missing a beat.

    Shell to poke at objects

    This is really a language feature and not a framework feature, but you can do some really sexy stuff inside the Django shell like insert a new visitor:

    >>> p = Visitor(name="Steven", website="http://steven.bitsetters.com")
    >>> p.save()

    Or select the last five blog posts

    >>> recent = BlogPosts.all()[:5]

    This makes it possible to stay in Python land forever if you wish. No bouncing around between SQL and Python.

    Built-in development servers make getting started fun

    There is nothing like spending half an hour setting up Apache and mod_* before writing your first line of code. Django and Rails bundle a lightweight web server who’s sole purpose is to make development easy and convenient. Unfortunately you won’t be seeing a bundled PHP based web server with your favorite PHP framework anytime soon. Try writing one and see how far you get without things like thread support. PHP is really more of a template language itself than a general purpose programming language. Projects like PHP-GTK make me giggle. Single threaded GUI applications are awsome! </sarcasm>

Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc