samirmamude

Web Programming and lifestyle...
April 23, 2009 @ 18:04 PM

Off-Topic: It's time to move on

Blog

Hi, my blog is not dead! At the middle of last month I had a serious health problem, I had to do a surgical procedure (intestine infection). BUT thank God I'm feeling healty and back to my normal life.

In the subject of this post, I'm pretend to explain a little of my experience about a huge project that I worked for over one year based on Ruby on Rails.

Definitely I could tell that was a big experience for my career as programmer and person. I had a chance to know smart people, new friendships, improve my English (I still think it's bad), learn more about Ruby and other cool stuff. Of course there were bad things, but was a big learning curve.

Anyway, my contract was ended, now I have two options: find another remote job with Ruby on Rails, even though worldwide crisis, or I should give more attention to my studies, as improving more my knowlegde in Python, dedicate more time to my company developing some product and get some customers.

March 02, 2009 @ 01:17 AM

Goodbye PC, finally I got a Macbook!

Blog

As been for a while, I was thinking to buy a Mac, but as it is very expensive here in Brazil, I was waiting for a big reason to spend my hard money.

Last Saturday (Feb 21) my old PC stopped working, don't know what happened, anyway...As I don't like to losing my time fighting with a machine, on Sunday I went to buy my Macbook.

After one week using it, I can say that has been an amazing experience. Everything works properly and my current environment of work is so much better.

Some tools that I'm using. More suggestion are welcome!

One thing I don't like about Django is that you always needs to write things like that:

from django.shortcuts import render_to_response
from django.template import RequestContext

def index(request):
     render_to_response('index.html', context_instance=RequestContext(request))

def products(request):
     render_to_response('products.html', context_instance=RequestContext(request))

But thanks to Python, Django has a great flexibility to handle different things without making any kind of bizarre code and I guess sometimes is much better and easier than Ruby on Rails (my current environment). So, to resolve this issue, I made a research to find some ideas.

First you should create a new Middleware call ThreadLocals [1].

# /yourproject/middleware/threadlocals.py
try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()

def get_request():
    return getattr(_thread_locals, 'request', None)

class ThreadLocals(object):
    def process_request(self, request):
        _thread_locals.request = request

The big trick here, is get an instance of the object HttpRequest [2], with this, you can create a lot of useful things to deal in your project.

After created the Middleware, now create a new module (http.py) with some methods.

#  yourproject/utils/http.py

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import simplejson
from yourproject.middleware import threadlocals as tl

def render(template_name, dictionary=None):    
    dictionary = dictionary or dict()
    return render_to_response(template_name + ".html", dictionary,
            context_instance=RequestContext(tl.get_request()))

def render_json(json):
    return HttpResponse(simplejson.dumps(json), mimetype='application/json')

def httprr(url, message=""):
    if message:
        tl.get_current_user().message_set.create(message=message)
    return HttpResponseRedirect(url)

In settings.py, don't forget to append the line 5 in the tuple MIDDLEWARE_CLASSES.

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'yourproject.middleware.threadlocals.ThreadLocals',
)

As you can see, in the file views.py we have less code to deal and more DRY if you know what I mean :)

from yourproject.utils.http import render, httprr

def index(request):
     render('index')

def products(request):
     products = Product.objects.all()
     render('products', dict(products=products))

Pretty cool isn't ?

References:
February 03, 2009 @ 23:17 PM

Log system for Django

Programming

I really like the log system of Ruby on Rails, it's very powerful to find bugs and understand how works HTTP requests.

To get the same idea, I wrote this middleware to register all HTTP and SQL requests to a file (development.txt) and tracking this file from a terminal.

# middleware.py
from django.db import connection
from django.conf import settings
from datetime import datetime

class EnforceLogger(object):
  
  def process_response(self, request, response):
    file = open('log/development.txt','a')
    if not request.path_info.startswith('/media/'):
      # Http request
      text = '-' * 120
      text += '\nProcessing URL %s (for %s at %s)' % (request.path, request.META.get('REMOTE_ADDR'), datetime.now())
      text += '\n Session ID: %s' % request.COOKIES.get('sessionid')
      text += '\n Parameters: [%s] %s %s' % (request.method, request.raw_post_data, request.META.get('QUERY_STRING'))
      
      # SQL Queries
      for q in connection.queries:
        sql, time = q['sql'], q['time']
        text += ' > %s\n DB Time: %s\n' % (sql, time)
          
      print >> file, text    
    file.close()
    return response

Maybe I'm reinventing the wheel, there are many solutions for log on Django, but this particular trick works pretty good to me.

To use, just add this new line at MIDDLEWARE_CLASSES in settings.py.

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
    'middleware.EnforceLogger',
)

Feel free to use, modify, etc...

January 26, 2009 @ 20:45 PM

My environment for Rails

Programming

I spent some months to get the right environment for work with Rails, I worked with NetBeans, Aptana, Jedit and Komodo but any of this tools I can really say "Finally a good environment for work!". They are too heavy!

I think the most of programmers that are using Linux or Mac, like to use simple things like a terminal and a text-editor. As I'm using Ubuntu Linux on my environment, I decided spend some hours to configure properly some tools.

You can see a preview of my desktop right here.

As you can see, I'm using GVim with some plugins, a terminal for tracking the log files, ssh for remote connections, Git for control version and other common tasks. For databases, I like use Squirrel, it's a good tool and when I have to deal with HTML I like to use Firebug, it's very useful.

I had some difficult to handle the shortcuts of GVim at the beginning, but was just a matter of time how to deal with it.

I made a conclusion that you don't need to use a IDE for programming in Ruby, since the language doesn't need to be compiled, but I have to admit that can be useful for debugging and other issues.

Samir Mamude

A happy programmer with your job, who likes to spend time with your frieds. In your free time, likes to play drums or playstation 3.

Recommendations

Recommend Me View Samir Mamude's profile on LinkedIn


Sections