"Get your Geek on"

Python Decorators for Djangonauts

Posted: September 3rd, 2010 | Author: BeardyGeek | Filed under: Django, Python, Web Development | Tags: , , | No Comments »

If you’ve used Django for any amount of time then you’ve probably come across decorators.  They’re the things with the @ signs over the top of your view.

The first one you’re likely to see is the @login_required decorator, which requires a user to be logged in before the view will run.  If they are not, django will redirect to the login page.

If you’ve ever wondered what they do and how they work, I’m going to show you how to create your own.

What is a decorator?

A decorator is a function that wraps your decorated function (or view, as they’re functions too) in yet another function, allowing you to run code both before and after the main function.

What?

A simple example

Allow me to explain.  Let’s say we have a view, but we only want it to render if the HTTP_REFERER is www.example.com.  If it’s not, then we want it to redirect to the home page.

So we have our view:

def my_view(request):
    ....
    return render_to_response('myview.html')

We’re going to call the decorator refer_check. The decorator looks like this.

from urlparse import urlparse
from django.http import HttpResponseRedirect

def refer_check(func):
    def decorate(request):
        referer = request.META.get('HTTP_REFERER', '')

        if referer == 'http://www.example.com':
            return func(request)
        else:
            return HttpResponseRedirect('/')
    return decorate

So how does this work? Well, our view (my_view) gets passed to the refer_check function – the func parameter is the view function.

We then create a new function, called decorate, which will wrap around our view function. That’s why it takes the request parameter, just like the view.

Now we get the HTTP_REFERER and check it. If it’s what we’re looking for, we run the view – the line where it says return func(request). If it’s the wrong referer value, we return and http redirect to the root of the domain.

Once all that has finished, we return the decorate function from the refer_check function.

To finish, we put the decorator above the view.

@refer_check
def my_view(request):
    ....
    return render_to_response('myview.html')

Another example

In the above example, we did something before running the view. But you can also do things after the view has run.

Here’s a decorator that lets you time in seconds how long your function takes to run.

from datetime import datetime

def time_it(func):
    def decorator():
        a = datetime.now()
        func()
        b = datetime.now()
        print 'function: %s took %d seconds to run' % (func.__name__, (b-a).seconds)
    return decorator

@time_it
def myfunc():
    for i in range(1,100000):
        print i

We have a function that prints the numbers 1 to 100,000. This is passed into our decorator which notes the time before the function is run. We then run the function using func(), and we note the time again. Then we print out a message with the function name and the number of seconds it took to complete.

Conclusion

As you can see from these examples, the decorators aren’t absolutely necessary. You could code both these examples by putting the code in the view/function itself. But it’s very useful if you like reusing your code, as you can apply your decorator to any function you like.

Bookmark and Share

5 Command Line Tools for Shell Dwellers

Posted: September 2nd, 2010 | Author: BeardyGeek | Filed under: Internet, Software | Tags: , , | 2 Comments »

If you’re anything like me, then you’ll spend a large part of your time working at the command line. I often find it easier to use some things in the shell then as a GUI. Take Subversion for example. While the rest of my team use TortoiseSVN, I’m constantly trying to evangelise the command line version, as I think it makes more sense.

Perhaps that’s just me….or maybe you too.
Read the rest of this entry »

Bookmark and Share

Justin.tv Android app – first broadcast test

Posted: September 1st, 2010 | Author: BeardyGeek | Filed under: Android, Mobile | Tags: , , | No Comments »

I’ve just installed the new Justin.tv Android app on my HTC Hero with Android 2.1 running.  It allows you to broadcast live streaming video from your phone, either over Wifi or 3G.

For this first test I used Wifi, so I can’t vouch for the speed or quality of a 3G connection.

First Impressions

The interface is pretty slick and easy to use.  It gives 3 buttons on the right hand side.  The top one is Chat, the bottom is Share, and the middle one is a big red button to start your broadcast.

Pressing the menu button brings up the account settings where you can either login to an existing account, or create a new one from within the app.

Results

The first few broadcasts I did, I found that it cut off the last 10 seconds of the recording.  I’m assuming this is to do with the lag, and that when you press the stop button on the app, it also stops sending data.  Which means if there is a 10 second lag, it will not send the last 10 seconds of your feed.

The audio was about half a second out of sync with the video, and the video quality was OK.  But overall it was a good experience, and considering I’m broadcasting very quickly from a mobile device, it’s still quite impressive.

The Video

This is what I recorded in the end.

Watch live video from Beardy Geek TV on Justin.tv

Bookmark and Share

JMeter testing from the command line

Posted: August 31st, 2010 | Author: BeardyGeek | Filed under: Testing, Web Development | Tags: , | No Comments »

I recently did a video post about website stress testing using JMeter.  Moving on from this, I’m going to show you how you can run JMeter tests from the command line, without using the GUI.

Why use the command line?

The main reason to use the command line is the most obvious: you don’t have a gui available.  If you want to run stress tests from a server, you’ll need to do it from the shell.

So why would you want to run the tests from a server?  Well one issue I discovered while running some tests on a media server recently, is that testing from your home machine means at some point during the test, you’re going to run out of bandwidth.

Of course you can just let JMeter loose with lots of threads and not record the responses, but it’s useful to know the response results of your pages or media, which means a download of the page or media you’re testing.

Using JMeter without a GUI

The JMeter binary allows you to run in GUI-less mode, using the -n option.

  1. Create your test in the JMeter UI as usual.
  2. Upload the JMX file to the server.  This contains all the configurations for your test that you just setup.
  3. Run the jmeter command:
    jmeter -n -t mytest.jmx -l log.jtl
  4. The test will run, and save the output in the log.jtl file.
  5. Download this file, and open it inside the JMeter UI.

If you need to change elements of the test, you can edit the JMX file directly.  It’s stored in an xml type format, so it’s fairly easy to see what you need to change.

Bookmark and Share

Organising your Django code

Posted: August 30th, 2010 | Author: BeardyGeek | Filed under: Django, Web Development | Tags: | 2 Comments »

There are several options when it comes to organising your code in a Django project.  There isn’t a ‘correct’ way, and it will depend on the size of the project, if it is a team development, or purely the preference of the developer.

Templates

Django gives you the ability to put your templates anywhere, either in single or multiple locations.  You can add a path to your TEMPLATE_DIRS setting, and Django will look at each path in turn to try and find your template to render.

Option 1

Have a single template directory, which contains all the templates for all your project apps.  The benefit here is that everything is in one place.  If your project is split up into a lot of apps, and there is crossover between apps, you may struggle to find where you put a template further down the line.

Another advantage is if you have a dedicated content team who just work on templates, and you either don’t want to bother them with python code, or you just don’t want them to go near it, you can keep it separate.  I’ve used this method, and the templates were kept in a separate source repository to the code.

The disadvantage is that if you don’t have a good system for arranging the directories within your templates directory, you’ll still struggle to find things.  So have a good strategy for file naming conventions if you go this route.

Option 2

Have a template directory in each of your installed apps.  If your apps are self contained, this is a good option, as it will be easy to organise.  Email templates in your email app, user profile templates in your user profile app.

The only problems you get here is when you have an app whose functionality spans more than one app, or more than one app accesses the same template.  You then have to decided where best to put it.

Media

Media really has to be in a single location so that it can be served by whichever webserver you choose.  But you still have the option of having the media stored somewhere within the project, or external to the project.  Again, when working within a team that has graphic designers, it can be beneficial to keep media outside the project.  It also makes sense if you want to re-use the media in another project.

Template Tags

Your template tags need to be inside a directory named templatetags, which has to reside inside an app.  If you have multiple apps, with multiple template tag directories, it can be an issue finding the correct app where the template tag lives.

If you want to put all your template tags in one place, and use them across your project, you can create an app specifically for your template tags.  Create your app, place a templatetags directory in it, with an __init__.py file, and remember to add the app to the INSTALLED_APPS setting.

Do you have any tips when it comes to organising your code?  Anything here you agree or don’t agree with? Have your say and leave a comment below.

Bookmark and Share

A new blog for Excel Geeks

Posted: August 25th, 2010 | Author: BeardyGeek | Filed under: General | Tags: , | No Comments »

My friend and fellow web developer Andrew Walker has just started a new blog all about advanced Excel and VBA techniques, called Excel Geek.  If you want to find out how to do all sorts of stuff you didn’t know Excel could do, this is the place to go.

Years ago, Andy took over from me in my role as a performance analyst.  I trained him well, but it seems that the student has become the Master.

Keep up the good work young Padawan.

Bookmark and Share

Django Training in the UK

Posted: July 30th, 2010 | Author: BeardyGeek | Filed under: Django | Tags: , | 4 Comments »

Update: I’ve decided not run the live training sessions due to interested parties being to geographically dispersed. Instead I’ll release the training materials via a series of screencasts and tools for users. Watch the blog for updates.

In Autumn 2010 I will be running several Django courses throughout the UK.

There will be 2 different types of courses:

  • Django template design – 1 day – for html/css coders who need to be able to fashion a template around the data being passed through by Django
  • Django introduction for programmers – 2 days – for those with web development experience who want to hit the ground running.

The cost will be around the £200 per day mark.  I’ll publish more firm details soon.

Bookmark and Share

New Django Site – Blog Twin

Posted: May 18th, 2010 | Author: BeardyGeek | Filed under: Django, Web Development | Tags: , , | 3 Comments »

I created Blog Twin after reading a blog post by Viper Chill entitled The Secret to growing your blog twice as fast with half the effort, I decided to create a site that would help people find a blogging partner.

Blog Twin is written in Django (naturally!).  You register, add details of your blog, and wait for someone else to come along and find you.  Or you can browse through and try and find a site in  a similar niche with similar stats to you.

There’s also the ability to tag entries, and filter by the tags.

It’s still a very early beta (I only started doing it 2 days ago), so any feedback, or bug reports, are most welcome.

Enjoy!

Bookmark and Share

Using Mind Maps to Create Blog Posts

Posted: May 17th, 2010 | Author: BeardyGeek | Filed under: General | Tags: | No Comments »

If you’ve ever wanted to find an easier, more structured way to plan your blog posts and articles, using mind maps is a great way to go.

Creating blog posts using mind maps

(This links to my new blog, which has a less technical, more business oriented slant.)

Bookmark and Share

Website Stress testing using JMeter

Posted: March 31st, 2010 | Author: BeardyGeek | Filed under: Software | Tags: , , , | 1 Comment »

Here’s my latest screencast, showing you how to stress test your website and web applications using JMeter.

Bookmark and Share