Brian Wigginton Lab and Nerdery

Django Fixtures: JSON Formatting

Posted on January 8, 2012

Came across an issue with Django Fixtures using the JSON format. Here was my fixture:

{
"pk": 1,
"model": "core.wine",
"fields": {
"name": "Juan Gil",
"vintage": 2009
}
}

Here's the error I was getting:

Problem installing fixture '.../core/fixtures/initial_data.json': Traceback (most recent call last):
  File ".../python2.6/site-packages/django/core/management/commands/loaddata.py", line 169, in handle
    for obj in objects:
  File "...python2.6/site-packages/django/core/serializers/json.py", line 35, in Deserializer
    for obj in PythonDeserializer(simplejson.load(stream), **options):
  File "...python2.6/site-packages/django/core/serializers/python.py", line 84, in Deserializer
    Model = _get_model(d["model"])
TypeError: string indices must be integers
view raw error.txt This Gist brought to you by GitHub.

The fix was simple, wrap the object in an array.

[
{
"pk": 1,
"model": "core.wine",
"fields": {
"name": "Juan Gil",
"vintage": 2009
}
}
]

Found the fix thanks to the following StackOverflow post: http://stackoverflow.com/a/4939147

JavaScript Closures

Posted on December 26, 2011

Javascript closures can be confusing at first. They're not, and hopefully this analogy will help drive home the concept.

A Man's Secret - An Analogy

A man possess a secret book, which he cannot let anyone else know about. He decides the only way to keep the book truly secret is to memorize the entire thing and then bury the book so no one can find it. Later in his years he bears a son. Once his son grows old enough, the father digs up the book and begins having his son commit the entire book to memory. Years later, he has his son rewrite the entire book cover to cover from memory on paper. When the son successfully completes the task, and the father is satisfied that his son truly has the book memorized in it's entirety, the book and the copy of the book the son just wrote are thrown into a fire, completely eliminating any evidence that the book actually existed. A few years later the father dies, leaving the son on his own, with the book committed to memory.

This is similiar to how a javascript closure works. See the following code.

Code Example

var father = new function(){
 
    // this is declared as a private variable
    var secretBook = 'Book of Secrets';
 
    this.bearSon = function(){
        return {
            whatWasTheBookYourFatherTaughtYou: function(){
                alert(secretBook);
            }
        };
    };
};
 
// the father won't tell anyone about the book he has
alert(father.secretBook); // undefined
 
// the father bears a son
son = father.bearSon();
 
// the father dies
father = undefined;
 
// the son still knows the book his father taught him
son.whatWasTheBookYourFatherTaughtYou(); // Book of Secrets

secretBook was declared inside the father function and is a private variable, inaccessible to anything outside the father function. The father function closes around the variables declared inside of it. Anything defined inside the father function has access to it, even once the father function has executed and been undefined. The bearSon method returns a new object that contains a function called whatWasTheBookYourFatherTaughtYou.

AccountManager getAuthToken() authTokenType param

Posted on April 28, 2011

In trying to connect to a Google api using the builtin AccountManager API for android, I could not figure out what values to use for the authTokenType. Then, finally, I found this link...

http://code.google.com/apis/gdata/faq.html#clientlogin

Filed under: Android 1 Comment

Javascript’s new Operator

Posted on January 23, 2011

What is it and how can you use it to create new objects from constructor functions?

What's a constructor function.

There's really no such thing as a constructor function. There are just functions, that's it, no different than any other function, except that you the programmer has made it so that it initializes a keyword called this with methods and properties. Here's the constructor function we will use for the rest of this post.

function Computer(manufacturer, model) {
  this.manufacturer = manufacturer;
  this.model = model;
}

What does new do?

The new operator creates new objects using our constructor function. Let's start by seeing what happens when we DON'T use the new operator.

var dell_inspiron = Computer('Dell', 'Inspiron');
alert(dell_inspiron); // undefined!

So what happened. Our Computer constructor function ran, it applied the manufacturer and model properties to the this keyword, which should have then populated our dell_inspiron variable. So what the hell was this pointing to? Let's see what's happening inside our constructor function:

function Computer(manufacturer, model) {
  alert(this);
  this.manufacturer = manufacturer;
  this.model = model;
}
var dell_inspiron = Computer('Dell', 'Inspiron');
alert(dell_inspiron); // undefined
// notice we now have two additional global objects manufacturer and model... not good
alert(manufacturer); // Dell
alert(model); // Inspiron

So as you can see calling a constructor function without using the new operator, causes our this keyword to point to the global object. Now let's try using our constructor function with the new operator.

var mac_book_pro = new Computer('Apple', 'Mac Book Pro');
alert(mac_book_pro); // [object OBJECT]
alert(mac_book_pro.manufacturer + ' ' + mac_book_pro.model); // Apple Mac Book Pro

This works as expected, and here's how. Using the new operator first creates a new blank object. Then, it invokes our constructor function, passing the newly created blank object as the this keyword. Your constructor function then populated the object pointed to by the this keyword with the manufacturer and model properties. When the constructor function ends, it automagically returns the object referenced by the this keyword to the mac_book_pro variable.

Additional Resources

Here's the example code in jsfiddle you can play with.

http://jsfiddle.net/bawigga/aQb5B/10/

If you want to read more about how the new operator works, I highly recommend the following books:

Filed under: Javascript No Comments

LAMP Stack Optimizations for Small Servers

Posted on January 21, 2011

This WordPress blog is running on a 256MB Slicehost VPS. Here are the settings I have in place to keep Apache and MySQL responsive. Without these settings, the server would often come to a grinding hault and SSH interactions would become very slow and sometimes hang.

Apache - httpd.conf - mpm_prefork_module Settings

<IfModule mpm_prefork_module>
    StartServers          2
    MinSpareServers       2
    MaxSpareServers       4
    MaxClients            50
    MaxRequestsPerChild   500
</IfModule>

I found that I saved a bunch of memory just by using less apache processes. Instead of spawing 8 processes by default I'm only going to spawn one and limit the max spares to 4, which means after some load I should only have 4 processes lingering around waiting to serve pages.

MySQL - my.cnf settings

skip-innodb
skip-bdb
skip-ndbcluster

I dropped mysql's memory useage by about 11M (sitting right under 5M right now) just by disabling innodb support. I've also done some very heavy WordPress caching using wp-supercache. this basically caches every page and post so that I'm just serving up static html content instead of processing the entire WordPress stack for every page load.

Filed under: Apache, MySQL No Comments
Google+