A Simple Django Profile Middleware

Last night I was looking for a simple middleware for Django that I can use to profile function calls and render them to the browser as plain text. I have found a few examples here and there but either they were introducing too much complexity (some of them were Django apps with their own models and such) or only implemented for process_view case which is not good when the request is only handled by a middleware.

So, I have ended up having a fresh implementation. Feel free to use and modify it according to your needs.

Continue reading

Dojo Memory and Observable Classes

I’m new in Dojo. However, I’m very lucky that the new 1.6 version introduces Memory and Observable classes.

Memory is part of the dojo.store namespace and it provides a data store that is implemented to store data in runtime. Together with Observable class (dojo.store.Observable) you can have a nice implementation of MVC.

<html>
<head>
    <script
       src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js"
       type="text/javascript"></script>
    <script>
        dojo.require("dojo.store.Memory");
        dojo.require("dojo.store.Observable");
        dojo.ready(function() {
            memory = new dojo.store.Memory();
            observer = new dojo.store.Observable(memory);
            // We define an attribute to sort the query results
            query = observer.query(null, {sort: [{attribute: "order"}]});
            query.observe(function(item, removedFrom, insertedInto) {
                console.log(arguments);
                if(removedFrom > -1){ // existing object removed
                    // Unfortunately, there is a bug in 1.6
                    // that sets removedFrom to the wrong index
                    // So, we use the item.id to find the node to
                    // remove
                    var node = dojo.byId("item" + item.id);
                    dojo.destroy(node);
                }
                if(insertedInto > -1){ // new or updated object inserted
                    dojo.place('<div id="item' + item.id + '">' + item.text + "</div>",
                               "container", insertedInto);
                }
            }, true);
            // Adding "true" to observe method is very important
            // to also observe object changes

            // Put items (The order will determine how they
            // are added to the DOM structure)
            memory.put({id: 1, order: 1, text: "Test 1"});
            memory.put({id: 2, order: 2, text: "Test 2"});
            memory.put({id: 3, order: 4, text: "Test 3"});
            memory.put({id: 4, order: 3, text: "Test 4"});
            memory.put({id: 5, order: 5, text: "Test 5"});
            // Removing item
            memory.remove(4);
            // Updating the order of an item
            var item = memory.get(3);
            item.order = 6;
            memory.put(item);
            // Changing the text of an item
            var item = memory.get(2);
            item.text = "Test 2 Changed";
            memory.put(item);
        });
    </script>
</head>
<body>
    <div id="container"></div>
</body>
</html>

The code block above shows an example usage of Memory and Observable to add new div elements to #container div when a new item is added to the memory store. Thanks to the listener function defined in query.observe call, any alteration to memory store is reflected in the #container div.

Beside making it much easier to deal with data changes, if you define query conditions (see “… observe.query(null,…” part) for the query call, when a new item is added to the memory store, if the query conditions are not met for this item, it won’t trigger the listener function call.

You can find more details at http://dojotoolkit.org/reference-guide/dojo/store/Memory.html.

Installing Node on AWS Linux AMI

Here are the steps to install node, npm and express on Amazon 32 bit Linux AMI:

  1. sudo yum install gcc-c++ make
  2. sudo yum install openssl-devel
  3. wget http://nodejs.org/dist/node-v0.4.7.tar.gz (Pick the latest stable version available)
  4. tar -zxvf node-v0.4.7.tar.gz
  5. cd node-v0.4.7
  6. export JOBS=2
  7. ./configure
  8. make
  9. sudo make install
  10. sudo su
  11. vi /etc/sudoers (We add node to the path of the sudo)
  12. Find and edit the line “Defaults secure_path …” and add “:/usr/local/bin” to the end of the path
  13. curl http://npmjs.org/install.sh | sudo sh

References:
http://www.embracingthecloud.com/2010/12/05/InstallingNodejsOnAmazonEC2.aspx
https://github.com/joyent/node/wiki/Installation

Layout of my Node.js + Express Project

One thing I like about Express is that it provides the most important features for web development with a very smooth learning curve. (Of course a lot of credit should also go to Connect middleware on top of which Express runs) This is possible thanks to Express having very few conventions about how to layout your files in your project. Express leaves the decision to you.
Continue reading

Doing partial updates with Mongoose

I use Mongoose on top of mongodb native driver for Node.js. With Mongoose you can create ORM like objects in Javascript. However, Mongoose is in development stage, that is, not all functions documented are available, yet. One of these functions that does not seem to be ready is the Model::update() static function.

If you want to update part of a record in the database directly, without loading the whole document, the update function is very handy. Although update() function is not available as described in the documentation, with some workaround it works as follows:

var ObjectID = require('mongodb').ObjectID;
...
var recordid = ObjectID.createFromHexString(str_recordid);
UserGoal._collection.update({_id: recordid},
      {'$set': {key: value}}, function(err, data) { ... });

Javascript Everywhere

Decided to use/learn nodejs + express and mongodb in my toy project, I enjoy using Javascript in every level of my code. I program with Javascript in frontend, webserver and database logics. All my data is either a JS object or a JSON/BSON data. This way I don’t need to switch context and don’t need to rewrite the same functions for each language from scratch. I still copy functions for frontend and and backend, but may start playing with libraries that make it possible to reuse the same javascript code in frontend and backend. However, I’m not sure if it’s practical.

Use nave to install/update node

Maybe I’m getting lazier or there is something good about projects that are easy to deploy. One of the things I like about nodejs is that it’s really easy to download and install. (Similar things could be said for MongoDB and Riak Search)

Thanks to npm, it’s also very easy to install packages developed for node. Although it’s already very easy to update node, I was looking for a tool to make node updates/installs much easier so that I won’t mess the npm installation each time when I forget how it arranges the folders. (I know it’s very simple and intuitive but as I said I’m lazy)

Isaac, the author of npm, also has a tool called nave.  nave is not only making it easy to install node, it also makes it easy to have multiple versions of the node installed on your system. By the use command it provides, you can create a temporary environment where you run a certain version of node. I guess it is a very handy feature for package developers to test their projects under different versions. It will also help to test if upgrading your servers is going to be a problem or not.

Node.js + MongoDB = Mongoose

Mongoose is a ORM like library that helps a lot when you want to access your collections defined on MongoDB from Node.js. You can use it without schemas but by defining ORM objects the code becomes much easier to read.

After you install Mongoose by npm install mongoose you can do the following to start playing with:

var mongoose = require('mongoose').Mongoose;
var db = mongoose.connect('mongodb://localhost/goaljuice');

Continue reading

Vim, Textmate, Emacs and Butterflies

Real Programmers: http://xkcd.com/378/

This comic becomes really true when you try to learn different editors.

I have some experience on Emacs and was using TextMate for a while. However, after making an evaluation between them recently TextMate became my favorite. The nice part about TextMate is it’s very easy to learn how to extend it. The bad part is that it does not have split windows and note good to edit big files.

I always had Vim in my mind to give it a try. Although it looks far complex than say TextMate after the vimtutor and some practice you realize that Vim basically consists of a set of keys. In addition to that it has split windows. It works very well and somehow I liked it more than the split windows of Emacs.

One keybinding I was looking for was autocomplete like in TextMate. In TextMate you use ESC for this purpose which becomes very addictive after a while. I’ve found that Vim has CTRL+N or CTRL+P for this purpose and it looks much more powerful. I may only find a better key combination for my taste.

By the way, when you learn more about Vim you realize that TextMate get a lot of ideas from Vim in terms of writing your small extensions. Hm hm…

Finally, if we go back to “Real Programmer” comic, while looking for some tips about Vim, one guy in his blog says that he uses Vim for Perl programming and that “it’s sometimes faster than using sed to change words in lines”. Is this also my end?

Mockups…

In my spare time, I’m working for the mockups of my toy project, goaljuice.com. I try to make it as if it’s functional.

Mockups help you to understand the requirements you need on both the frontend and backend. In that respect, although they take a lot of time mockups are very informative.

Besides that I always like to play with HTML, CSS and JS. What I don’t like to work on is cross browser compatibility. I try to make the mockups and also the final HTMLs W3 complaint. I won’t spend too much time on bad behaving browsers. The mockups are not in their final stage; both the design and HTML/CSS are work-in-progress. However, I thought that it would be great to share to get your feedbacks.

By the way, here is the source code of the app.js file for node:

require.paths.unshift(__dirname);

var express = require('express');

var app = express.createServer(
	express.logger(),
	express.staticProvider(__dirname + '/mockups')
	);

app.get("/",function(req, res) {
	res.redirect("/mockups");
})
app.listen(80);
process.setuid("node");
console.log("Ready to serve requests. Enjoy...");