2009 April 25

Pure Genius:

http://lookatthisfuckinghipster.tumblr.com

2009 April 22

This morning we drove the 17 mile drive through the Del Monte Forest, including the famous Lone Cyprus:

Lone Cyprus

2009 April 21

Tawny and I at Big Sur:

Big Sur

2009 April 21

Out here in California, we've been spending a lot of time on the beach:

Carmel Beach

2009 April 19

So I was going to try and blog every day in April, I've failed. But i've got a good reason for skipping the last 2 days. You see, I was busy getting married. I know it's a pretty lame excuse for not posting to a blog to 2 days, but it's all I have. I leave you with this picture and a promise of more to come:

Travel over the rockies

2009 April 15

Because I am getting married this weekend, I don't have a lot of time to spend on blog posts. I especially don't have time to spend on blog posts of a technical nature. So, given what's going on I thought I would share some of the mundane and totally uninteresting to anyone other than me stuff that's been going on over the past week.

One of my main jobs for this evening was to purchase the wine that will be served at the rehearsal dinner. It seems that I have failed even that simple task. Not that I didn't go to the wine store, not that I didn't talk to the gentleman there and hear about some good wines. But rather, said gentleman sent me away with a much smaller purchase than was originally planned. He sent me home with homework. I was given 4 bottles of wine to take home and taste, to come back and report with my findings and thereby choose a case of red and a case of white. I must say that it's been the best homework i've ever had. If this is failure, I could get used to it.

2009 April 14

Tonight Tawny and I worked on a photo diary for the rehearsal dinner. After the wedding I will post it so everyone can enjoy seeing photos of my in jams. You do remember jams don't you

last [time}(/blog/2009/apr/11/django-based-tiny-url-part-2/) we created the model that is going to store the url that we want to redirect to. In this installment we will be working on the views that allow us to use the shorturl app. First up is the redirect view:

from django.http import HttpResponsePermanentRedirect
from django.shortcuts import get_object_or_404
from utilities import string_to_integer
def redirect(request, key):
    primary_key = string_to_integer(key)
    short = get_object_or_404(ShortUrl, id=primary_key)
    return HttpResponsePermanentRedirect(short.url)

As you can see, it's pretty simple. Query the database and do a permanent redirect if the object is found. Not much there, so lets take a look at the view for the form:

from django.forms import ModelForm
from shorturl.models import ShortUrl
class UrlForm(ModelForm):
    class Meta:
        model = ShortUrl

It's purely a model form that exposes a textfield that will can be populated with a url.

Our last installment will go over the whole app and hopefully include a link to the github project where I am going to be hosting my small utility apps that I show on the blog.

2009 April 12

In less than a week I will be married.

I would love to post more, but it's been an exhausting weekend.

In the last post, we learned about a base conversion function, lets take that function and use it with a django model.

First lets create a model:

from django.db import models
from utilities import string_to_integer, id_to_string
class ShortUrl(models.Model):
    url = models.URLField(verify_exists=False,max_length=300)
    def _translate(self):
        return id_to_string(self.id)
    translate = property(_translate)
    def __unicode__(self):
        return "%s" % (self.url)

You might be asking yourself, where is the base_convert function. Well, in this case i've created a little helper function that will use the base_convert function to convert the primary key of our ShortUrl model into a base62 number:

def id_to_string(number):
    return base_convert(number, BASE10, BASE62)

In the next installment, we will take our model and tie it into a view for creating urls.

2009 April 10

Digg created an interesting url shortner. The only problem, it uses frames to wrap any site that it forwards too. What are we, in 1996 or something. Let's face it, frames are bad mmkay.

John Gruber from daringfireball wrote a nice regex that helps block the diggbar. My question was, how would one do such a thing in django? It turns out it's pretty easy.

Create an app:

./manage.py startapp diggbar

Create a middleware module and add the following:

from django.shortcuts import render_to_response
import re
import logging
digg_re = re.compile(r'http://digg.com/\w{1,8}/*(\?.*)?$')
class FckDiggMiddleware(object):
    def process_request(self, request):
        if request.META.has_key('HTTP_REFERER'):
            logging.info(request.META['HTTP_REFERER'])
            if digg_re.search(request.META['HTTP_REFERER']):
                return render_to_response('fck_digg.html')

Add diggbar.middleware.FckDiggMiddleware to your middleware in the settings.py

Add a fck_digg.html template somewhere on your template path.

I've created a django app that can handle this on github, check it out here

2009 April 09

you might have noticed that the site looks weird. That's because it's the annual css naked day

Back tomorrow.

Tiny url services can be very useful, so lets learn an easy way to build one using django and python along with radix.

so using a typical base conversion algorithm: :::python def base_convert(number,fromradix,toradix): x=long(0) for digit in str(number): x = x*len(fromradix) + fromradix.index(digit)

    res=""
    while x>0:
        d = x % len(toradix)
        res = toradix[d] + res
        x /= len(toradix)

    return res

we can convert from one base to another.

So lets create our radix container: BASE2 = "01" BASE10 = "0123456789" BASE16 = "0123456789ABCDEF" BASE62 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"

we can use the function like so:

>>> base_convert(250,BASE10, BASE62)
>>> 'EC'

This is a good start on using a function to convert back and forth between different number systems. In the next post we will see how to start using this within a django app.

Also see here for more on base conversion functions

2009 April 07

It's always interesting to see how folks deploy their django apps. So in the spirit of sharing, I thought I would post an example of the fabric script I use, with a little explanation afterwards:

config.fab_hosts = ['domain.example.com']
config.deploy_to = '/path/to/$(project)'

def push_local():
    "push release branch to remote repo"
    local('git push origin release')

def update_remote():
    "update remote repo to newest release"
    run('cd /path/to/project;git co release;git pull origin;')

def restart_app():
    "touch the wsgi file to restart application"
    run('touch /path/to/project/wsgi.py')

def deploy():
    "deply awesomeness"
    push_local()
    update_remote()
    restart_app()

As you can see from the recipe above, my fabric script depends on git. It's a bit of a hack in that I have to have a remote repository on my production machine, but it works. So here are the steps with a little more detailed explanation:

  1. merge release ready code into my local release branch
  2. push that release branch to my remote repository
  3. update the remote production repository
  4. restart my application by touching the wsgi.py
  5. rinse and repeat when I realize I've forgotten something

Seeing that this blog is an effort by me to post technically minded content, there are times where I would like to post code samples. I know that I could use the ever ubiquitous code tag, however that just left me wanting. I am too used to seeing code with colors, in other words I am addicted to syntax coloring.

Wait, python has a package you say, a package called pygments. It's so easy it might just work. And actually it did. So below I will regale you with tales of dragons and princesses. Or just tell you how I got pygments and markdown playing well together.

First step, install pygments and markdown:

sudo easy_install pygments
sudo easy_install markdown

Find a copy of mdx_codehilite.py. There are many places that have links to a gitorious.org repository. That didn't work for me. Make sure that module is on your path somewhere.

I then followed the directions here for creating a markdown override filter for use in my django templates.

Now, use pygments to create a stylesheet:

 pygmentize -f html -S default -a .codehilite >> style.css

Finally, wherever you have a markdown filter reference:

{{content|markdown}

use this syntax instead:

{{content|markdown:"codehilite"|safe}}

I know that this is a bit lacking, but it's all I have energy for right now. I am planning on coming back to it later on and fleshing out some more steps

2009 April 05

I'm lazy and tired. But I promise, this will be the only time I fall back to posting rolcats

2009 April 04

Tonight I just added a comment notification module to itybits. I'd like to say that I wrote it because it was an interesting problem domain that I just had to sink my teeth into. That would be a lie. I wrote it because of the second best reason for a developer to write something, I'm lazy. Last week I realized that some people had left comments on a couple of posts. However, the only way I knew was from logging on and checking the built in admin app. That will not do. I want instant gratification, so I built a comment notification mailer.

One of the things I love about django is the signals framework. That combined with the built in comments app made things pretty easy.

First up were the imports:

from django.core.mail import send_mail
from django.contrib.comments.signals import comment_was_posted

Next was the method:

def comment_notification(sender, **kwargs):
    comment = kwargs['comment']
    post = comment.content_object
    link = post.get_absolute_url()
    user_name = comment.user_name
    send_mail('A Comment has been posted by %s' % user_name, 'See the post here %s' % link, 'server@example.com',
        ['to@example.com'], fail_silently=False)

And finally the signal registration:

comment_was_posted.connect(comment_notification)

One thing to remember is that in order for the registration to happen, you must import the module somewhere where it will be run, preferably at startup. I cheated a little this time and added it to one of my models.py files.

Now I get an email whenever someone comments. Laziness FTW!

2009 April 03

I want to learn a new language.

So far I have whittled it down to Scala vs. Erlang. Right now I am leaning towards Erlang because of the movie: http://www.youtube.com/watch?v=uKfKtXYLG78

That's all for today.

Why would I choose to build my own blogging platform? Seriously, who does that in the age of wordpress.com, wordpress.org or even blogger.com?

I'll tell you why my system is better than those. It's because I wrote it. Well that was simple, next topic. Actually, it really is simple. For me, the application that runs itybits is the best out there because I wrote it. So if I want to add some cool new feature, say to automatically post insults via lolcats, I can do that. Of course, it also means that if something breaks, I can only blame me. It's not that technically it's better. In all probability it's not. It's most likely the worst amalgamation of crap ideas in the history of programming, well no that award goes to Micorsoft Bob. However, given that I do know what's going on under the hood, it's easier for me to make changes and it's actually quite fun.

One quick sidenote, at some point I did try to modify wordpress to suit my personal style. All I remember is opening up the first file in vi, I blacked out and next thing I know I was in a hut in Thailand wearing an Elvis impersonator outfitter. It was very scary.

So what have we learned from all this. If all you want is the standard fare, seriously don't build your own blog. All it will get you is torment and heartache. But if you want something that you are familiar with, something that you can wield like excalibur, then give it a whirl.

2009 March 31

I GOT FIRST POST, OMGWTFBBQ!

It's not hard to have first post on your own blog, that you just created. But hey, first post is still first post, just ask cwood. Hopefully, this will be the first in at least 30 posts. At work we decided to have a blogging challenge for the month of April and this is my submission into the foray. Besides trying to complete the challenge, I also wanted a reason to try and polish some more technical writing and have a place to post some stuff that I've learned with python, django and other technologies. Let's hope this lives up to my expectations and doesn't devolve into a reposting of lolcat pictures.

2009 March 30

Coming soon for the April blogging challenge

© Matt George