jBoxer

Icon

My name is Jake Boxer. I change the directions of small pieces of metal for a living.

Django Middleware vs. Context Processors

This may be old news to many people, but it’s something I just recently learned (after doing it wrong for about nine months), so I figured someone else may be able to benefit from my mistakes.

For a long time, when I needed to access the currently logged-in user in one of my Django views, they would follow this pattern:

from django.template import RequestContext

# some other view code

def my_view (request, obj_id):
    context = RequestContext(request)
    obj     = get_object_or_404(SomeModel, pk=int(obj_id))

    # do some stuff, including:
    some_function(context["user"])

    return render_to_response("some_url_name", {"some_var": some_val},
        context_instance=context)

Now, seasoned Django vets (why are you reading this post, by the way?) are probably laughing, but this seemed perfectly fine to me. Luckily, my ignorance was revealed to me while asking on IRC about a problem which, while didn’t seem so at the time, was completely tied to my misuse of RequestContext.

To put it simply, context processors are made to be used in templates. The only time they should ever be instantiated is at the very end of a view, like so:

return render_to_response("some_url_name", {"some_var": some_val},
    context_instance=RequestContext(request))

I was using them all over views, and even in a few of my decorators. What’s wrong with this? The main thing is, certain mutation functions are sometimes performed when a RequestContext is instantiated (such as user.get_and_delete_messages(), which gets all of a user’s messages from the database and then deletes them), and performing them multiple times before loading the template can cause unexpected results. In my example, I was instantiating a RequestContext in a bunch of decorators, which meant that by the time my template was loaded, all of the user’s messages were deleted (and stored in an earlier instance of RequestContext), making it look to me as if my auth messages were being thrown out.

What’s the solution? Middleware. Middleware allows the programmer to attach variables to the request object before it reaches the view. With this (and the provided django.contrib.auth.middleware.AuthenticationMiddleware), I can still achieve my original goal (accessing the logged-in user from a view), but now I can do it without creating a RequestContext and potentially running mutation functions multiple times:

from django.template import RequestContext

# some other view code

def my_view (request, obj_id):
    obj     = get_object_or_404(SomeModel, pk=int(obj_id))

    # do some stuff, including:
    some_function(request.user)

    return render_to_response("some_url_name", {"some_var": some_val},
        context_instance=RequestContext(request))

I’ve removed all the references to RequestContext from my decorators, and made sure to only instantiate it at the very end of views. Now, messages work perfectly. I’ve even written my own middleware (which you can learn how to do here) to load instances of a few of my own models into the request.

To reiterate, I’m aware that this is common knowledge for many people, but it took me 9 months of moderate Django use and embarrassment on IRC to discover it for myself. Hopefully, this will help someone else in a similar position.

Are you a better programmer than you were two years ago?

Two years ago, I was working on a fairly complicated (for my level of experience) web app for posting news articles. Quite a few times, I ran into situations where I was about to create tight coupling between two somewhat unrelated parts of my app. Sometimes, I wouldn’t even recognize this as a problem. Other times, I would, but not be able to think of an easy fix, so I’d continue on.

Today, I find myself fixing tightly-coupled situations almost instinctively. I use design patterns that I was barely aware of two years ago, and I do it without straying into “design pattern fever” territory. This isn’t to say I’m an expert at software design; it still takes a lot of thought to actually think of the best fix, and I’m sure I still make plenty of mistakes. My point is, my growth as a programmer is very obvious to me in these situations.

How about you? If you’ve been programming for more than two years, you’re probably a better programmer than you were two years ago, but can you tell? If so, how can you tell? Can you give any good examples of moments when you realized it?

Non-painful email on Django development servers

I’ve been actively learning and using Django since August 2008, and I’ve loved almost every bit of it. There are plenty of places to read all about the virtues of Django, so I’ll leave that out for now.

One thing that’s always bugged me about web development in general is the sending of emails. I do development on my local computer (with a badly set up Apache / MySQL / PHP / Python / whatever else stack), and I’ve never felt like dealing with the headache of setting up a mail server. This means, when I add something that’s supposed to send an email (like an activation email after registration), I have to get very hacky to test and debug it (making sure the email text is being produced correctly, making sure it’s being sent to and from the right people, etc.).

This was one of the few web development pains that I thought Django didn’t solve. Whenever I’d test a bit of code that was supposed to send email, I’d get a “Connection refused” error page (meaning my computer has no mail server to send the email with). I would usually add in a bit of printf debugging to make sure the subject and body had the correct text, but beyond that, I’d usually wait to test the email portions until I uploaded to a server that could send email (usually the production server, unfortunately).

Yesterday, I bumped into a little section in the Django documentation that explains how to get around this. As usual, Python has all the solutions. First, set this code in your settings.py file:

EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025 # replace this with some free port number on your machine

Then, assuming you’re on a Unix system (I’m on a Mac), run the following on the command line to start a “dumb” Python mailserver:

python -m smtpd -n -c DebuggingServer localhost:1025

Make sure to replace 1025 with whatever you filled in for EMAIL_PORT.

Now, try running the email-sending code in your Python application. Voila! No error pages (or at least, none related to email), and the full text of the email (headers and all) appears in whatever command line prompt you ran the dumb mailserver on. This allows you to the see senders, recipients, subject, and body of the email being sent out, all without getting hacky or sending to an email account you own.

Taking this a step further, I created a small bash script called “dumbmail” in /usr/local/bin that looks like the following:

#!/usr/bin/env bash
if [ -z $1 ]
then port=1025
else port=$1
fi

echo "Starting dumb mail server on localhost:$port"
python -m smtpd -n -c DebuggingServer localhost:$port

Now, when I’m testing a Django application and I get to a section that is going to send an email, I just run “dumbmail” (or “dumbmail some_number” if I need to use a different port, for some reason I can’t image), and I’m ready to go.

Hope this helps people. The documentation was always there - I just never noticed that part until yesterday.

Round Rectangles (or Why Steve Jobs is a Visionary)

A story was posted on Folklore.org (a site full of old stories about the creation and initial development of Apple computers) about the addition of rounded rectangles to an old drawing program, and Steve Jobs’s involvement in them. This section in particular struck me:

Bill fired up his demo and it quickly filled the Lisa screen with randomly-sized ovals, faster than you thought was possible. But something was bothering Steve Jobs. “Well, circles and ovals are good, but how about drawing rectangles with rounded corners? Can we do that now, too?”

“No, there’s no way to do that. In fact it would be really hard to do, and I don’t think we really need it”. I think Bill was a little miffed that Steve wasn’t raving over the fast ovals and still wanted more.

Steve suddenly got more intense. “Rectangles with rounded corners are everywhere! Just look around this room!”. And sure enough, there were lots of them, like the whiteboard and some of the desks and tables. Then he pointed out the window. “And look outside, there’s even more, practically everywhere you look!”. He even persuaded Bill to take a quick walk around the block with him, pointing out every rectangle with rounded corners that he could find.

When Steve and Bill passed a no-parking sign with rounded corners, it did the trick. “OK, I give up”, Bill pleaded. “I’ll see if it’s as hard as I thought.” He went back home to work on it.

I think this is a fantastic example of what makes Steve Jobs one of the few true visionaries in the world. In the face of a big advancement like fast ovals (yes, it was definitely a big deal at the time), I would’ve been more than satisfied. I may have asked for rounded rectangles in a second iteration, but it would’ve been a simple feature idea. I believe most people would’ve reacted the same way.

What makes Steve Jobs special is his ability to quickly identify what’s really important. It seems so obvious after the fact. Of course people would like computers with translucent colored cases! Of course minimalist controls would make for a more accessible and desirable MP3 player! Of course rounded rectangles are an extremely common shape, and are really important to have in a drawing program! These ideas (and more) are all obvious now. But a year before Apple did them, other companies were struggling to innovate in these fields, and they were only “obvious” to Steve Jobs.

Of course, anyone can have a great idea that turns out to be the right way of doing things. This is why I distinguish between “true” and regular (false?) visionaries. People called M. Night Shyamalan a visionary after “The Sixth Sense” and “Unbreakable”. He then went on to make one more pretty good but decidedly un-visionary movie (Signs), an arguably good but decidedly un-visionary movie (The Village, which I loved, but I understand why others didn’t), and two duds (my apologies to the three people who liked them). The visionary label was applied to Shyamalan before he’d reached first base, and he got thrown out at second. This happens all the time, and these people are certainly not true visionaries.

True visionaries come up with visionary ideas so consistently, that it becomes expected of them. And no one (off the top of my head) has a more consistent history of this than Steve Jobs.

A response to “The Extreme Google Brain”

A blogger named Joe Clark just made a post called The Extreme Google Brain. In it, he takes a side on the recent tiff between lead designer Douglas Bowman and Google, where the former left the latter out of frustration at having to prove every design decision with real-world test data.

Joe Clark whole-heartedly agrees with Bowman, as many others do (I myself am somewhat torn). However, I find Clark’s article to be a ridiculous rant, full of stereotyping, fact-inventing, name-calling, and other marks of awful opinion pieces.

One frequently-used tactic in his piece is the inventing of a fact, followed by a single related fact that’s supposed to prove it. Case in point:

Some of these boys and men exhibit extreme-male-brain tendencies, including an ability to focus obsessively for long periods of time, often on inanimate objects or abstractions (hence male domination of engineering and high-end law).

Yes, males dominate engineering and high-end law. However, the cause is the topic of endless debates, and yet Clark claims it’s due to “extreme-male-brain tendencies” like he read it in a science textbook. This “here’s a fact I made up (hence an already-known, tangentially-related fact)” pattern repeats itself a few times.

When he’s not making up facts, he’s stereotyping a group of tens of thousands of people based on the few he knows.

Apart from Bowman, I can think of only two Google employees I could stand to be around for longer than an elevator ride. My impression of “Googlers,” which I concede is based on little direct knowledge and is prejudicial on its face [note: apologizing in advance does not make it okay to say something idiotic], is one of undersocialized, uncultured, pampered, arrogant faux-savants who have cultivated an arrested adolescence that the Google working environment further nurtures. Their computer-programming skills, the sole skills valued by the company, camouflage the flaws of their neuroanatomy. Their brains are beautifully suited to the genteel eugenics program that is the Google hiring process but are broken for real-world use.

You get the picture. Throughout the rest of the article, he:

  • Contends that A/B testing has no value.
  • Makes up scenarios that he believes (and “speculate[s] that Bowman would not disagree”) accurately represent Google meetings.
  • Tells us that we can’t disagree with Bowman and still feel that technology juggernauts are becoming better at visual design.
  • Says that when a company uses anti-design (extremely minimal and not-necessarily-beautiful designs such as Google or Craigslist) and succeeds, they’re succeeding despite the anti-design. He then concedes that can’t prove it, but assures that if you’re “visually literate” (which Adobe defines as the “ability to construct meaning from visual images”, which anyone older than an infant can consistently do), you “just know it”.

There isn’t really much else to say about this. I’ve read quite a few articles that side with Bowman, and quite a few that side with Google, and many of them on each side were great articles with great points. This was not one of them. I’ve never heard of Joe Clark before, and based on this, I hope I never do again.

Facebook causes me to facepalm

I looked at the “New Layout Vote” app on Facebook today. The wall is full of complaints about the new layout. While reading through them, I ran into this gem:

I don't like how my picture is already next to every comment box on every facebook page... it's like facebook is forcing me to participate and comment on things that I don't want to. Please stop taking my profile picture and putting it everywhere without my permission.

Ugh… honestly, how can she think that, without commenting, her picture is visible to everyone else looking at a page? Doesn’t she wonder why she can’t see everyone else’s picture there as well?

And, as a side note, if she agreed to the Terms of Service (which she did if she has an account, which she does), then she definitely gave them permission to put her picture everywhere.

Cooking like my Mom - Part 1

Every single holiday since I can remember, my mom has made a dish called Lokshen Kugel. She makes it with egg noodles, cottage cheese, sour cream, and a bunch of sugar, vanilla, and cinnamon (as well as the standard eggs and stuff).

Today, after getting the recipe from her, I made it myself. The weirdest feeling was opening the oven halfway through. There was a dish I’d seen dozens of times before, but for the first time, it wasn’t in the oven at my house (the one I grew up in), and it was made by me instead of my mom. It was very surreal.

I haven’t tasted it yet. But when I do, I’ll post about it again. I also took some pictures, so I’ll be sure to put them up (once I find the cord for my camera).

What is the best makeshift ice scraper?

Tic Tacs

TicTac container. Seriously, it saved my life this morning.

How to export a 1024 x 768 screencast from Adobe Premiere Pro CS4 to Youtube

Over spring break, I made some screencasts for the website I maintain for my job. We used a free, open-source screen recorder called CamStudio. Our plan was to upload them to YouTube and embed the videos into our site from there. The one problem: the Export Media dialog on Adobe Premiere Pro CS4 (the software I used to edit the screencasts) only has a setting for low-definition (320×240) videos. My screencasts were 1024×768, and shrinking them to 320×240 would make the video part pretty much useless.

So, I set about trying to find a setting that would work for a 1024×768 screencast. The majority of settings produced some weird-quality results, even with the quality settings turned up as high as possible, which makes me think it had something to do with a faulty interlacing/deinterlacing setting somewhere. When I changed the one interlacing setting I was able to find, the exported videos would work fine in QuickTime, but look completely messed up in VLC and, more importantly, YouTube.

Exporting to F4V actually did work in every media player I tried it in, but for some reason, YouTube was unable to convert it to a playable format.

Finally, after about 9 hours of fiddling with Adobe Premiere Pro’s Export Media dialog, I found a setting of acceptable quality that worked on YouTube. I doubt many other people will need this, but since I was unable to find any information about the problem I was having online, maybe I’ll save another person 9 hours of work. Here are the settings I used:

Export Settings
Format: QuickTime

Filters
No Changes

Video
Video Codec: H.264
Quality: 100
Width: 1,024
Height: 768
(Width and Height are unlinked)
Frame Rate: 30
Field Type: Lower First (this was the setting that deals with interlacing I believe)
Aspect: Square Pixels (1.0)
Render at Maximum Depth: Checked
Set Key Frame Distance: Unchecked
Optimize Stills: Checked
Frame Reordering: Unchecked
Set Bitrate: Unchecked

Audio
No Changes

Others
No Changes

I’m sure there are some optimizations to be made in these settings; things that are causing me to produce unnecessarily large files, things that make rendering slower, or things that, if I tweaked, would give me even better quality. However, after 9 hours, I don’t care; this works, so for now, I’m done. Hope this helps someone.

My greatest beer-related discovery

Before college, I didn’t drink at all, and even in college, I don’t drink very much; once every couple weeks during the school year, maybe once or twice a week during vacations. During this short time, I’d never been able to get myself to like beer. I always wanted to, but I just never could. The taste always reminded me of garbage (or at least, what I imagine garbage would taste like). I spent a fair bit of time on Google trying to find what beers other people really like, and every one I tried had the same garbage-y taste.

One day, with the prospect of playing a drinking game while watching Independence Day (drink every time there’s an explosion… ughhh…), I decided I’d try a lite beer, so I wouldn’t feel like I’d eaten an entire loaf of bread after my third bottle. I did a little research, and found that people had great things to say about Sam Adams Light. I got a six-pack, and to my surprise, I didn’t hate it as much as I hated other beers. $9.00 for a six-pack of somewhat-tolerable liquid is pushing it, but at least I could play drinking games with my friends without resorting to Mike’s Hard Lemonade.

The important part was this: instead of tasting like beer (and, by association, garbage), it tasted like water with a slight aftertaste of beer/garbage. This made me wonder: is there a beer that really just tastes like water? I asked my friend Trenton. The answer? Natty Light.

I’d been looking in all the wrong places. The people who had been telling me the “best beers” were people who loved beer and think it tastes like the nectar of the gods. I hate beer and think it tastes like the nectar that drips from a leaky garbage bag, so of course, the best beer for me is the one that tastes as little like anything as possible. And as fortune would have it, the best beer for me is also the cheapest beer. For less than the cost of two six-packs of Sam Adams light, I can buy a 30-rack of Natty Light.

Don’t get me wrong, it still tastes gross. In the end, I really just don’t like the taste of alcohol very much, and beer is no exception. But unlike with “good” beer, I can drink a few cans of Natty Light without dreading the taste of garbage each sip. And that’s something I think we can all drink to.

SEO Powered by Platinum SEO from Techblissonline