A great web application framework; Django

Posted: December 11th, 2008 | Author: | Filed under: Interesting, Programming | Tags: , , , | No Comments »

 I have just tried Django.  Here what wikipedia says; Django (pronunciation: /ˈdʒæŋgoː/, JANG-oh[1]) is an open source web application framework, written in Python, which loosely follows the model-view-controller design pattern.

Having the power of such a web framework makes you really fast if you want to develop a modern web application. I suggest you to give a shot with it. While python is becoming popular, I think django will show up more. Here is a bit of idea how a simple poll application is implemented;

 

Following blocks includes only the code you have to write, but it is not enough for the application. Rest can be generated whit django utility python files. They are just bunch of simple commands. You can read the tutorial here.

This is structure of my web application which is called "mysite".

mysite/
    __init__.py
    manage.py
    settings.py
    urls.py
    polls/
        detail.html
        index.html
        __init__.py
        admin.py
        models.py
        views.py

Here is view.py; this file contains functions which handles requests. For example index function ( def index(request): ) is called by django framework when index uri of my web application is called. It list all available polls in my database. I used SQLite as data base in this example. It was all simple that I just defined models and it was done. You don't have to deal with any sql or with an application to desing your db schema, just define your model classes and define thier properties and relations between them. After then you just run a command line utility which generates all the needed sql queries according to database engine you use, and django supports Oracle, MSSQL, mySQL, postegreSQL, SQLLite and more…

from django.template import Context, loader
from mysite.polls.models import Poll
from django.http import HttpResponse
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
 
 
#def index(request):
#    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
#    output = ', '.join([p.question for p in latest_poll_list])
#    return HttpResponse(output)
 
def index(request):
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    t = loader.get_template('polls/index.html')
    c = Context({
        'latest_poll_list': latest_poll_list,
    })
    return HttpResponse(t.render(c))
 
#def index(request):
#    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
#    return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
#def detail(request, poll_id):
#    return HttpResponse("You're looking at poll %s." % poll_id)
 
def detail(request, poll_id):
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/detail.html', {'poll': p})

 

Here is model.py where the entity classes lays in. You don't have deal with designing a db schema when you define your classes properly. Here we set just two classes which will be two tables in db. Since we set a relationship between these two classes a foreign key constraint will be created in db regardless of data base engine.

 

from django.db import models
 
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
 
class Choice(models.Model):
    poll = models.ForeignKey(Poll) # here is how defined the relationship
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()

 

And here is template example django has;

{% if latest_poll_list %}
    <ul>
    {% for poll in latest_poll_list %}
        <li>{{ poll.question }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

One last thing I liked at django is its extensive ORM support. Here is an example how a data is fetched from database;

>>> p = Entry.objects.filter(
...     headline__startswith='What'
... ).exclude(
...     pub_date__gte=datetime.now()
... ).filter(
...     pub_date__gte=datetime(2005, 1, 1)
... )

>>> print p

 
Since QuerySets are lazy in django database will be hit only once although different filters are chained. Database is only hit at "print p" line. For more information about QuerySets in django follow this link.
 
To see what Django offers (auto generated admin panel, url mapping with regexes, ….) take a look at comparison of it with different web app. frameworks, here.

Handle ASP.NET Ajax call Time-Outs

Posted: December 2nd, 2008 | Author: | Filed under: Programming | Tags: , , , | No Comments »

 
You can use the following code as an http module.
It detects if the request is an ajax request and checks for validity of session and redirects to login page if session has timed out.
 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;

namespace myWeb.Library
{
    public class AjaxTimeOutHandler : IHttpModule
    {

        #region IHttpModule Members

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += context_BeginRequest;
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            var httpApp = (HttpApplication)sender;
            var context = httpApp.Context;

            bool isTimeout = false;
            HttpCookie authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket authTicket = null;

            if (authCookie == null)
            {
                isTimeout = true;
            }
            else
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                if (authTicket.Expired)
                {
                    isTimeout = true;
                }
            }

            if (context.Request.IsAjaxCallBack() && isTimeout)
            {
                context.Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(context.Request.RawUrl));
            }
        }

        #endregion
    }
}