CSC/ECE 517 Fall 2014/ch1a 8 sn

From Expertiza_Wiki
Revision as of 20:35, 19 September 2014 by Sbastik (talk | contribs)
Jump to navigation Jump to search

Django Framework

Django (2005) is a high level, but heavy, open source Python<ref>http://www.python.org/</ref> web framework used to build a large scale web application. Django is named after Django Reinhardt, a gypsy jazz guitarist from the 1930s to early 1950s. A web framework is necessary to help the developers and the testers to develop highly scalable and efficient large scale web applications. It deals with the most important problem in the domain of Web development – repetition. Even though web development is a really interesting task, there are a lot of things that utilize unnecessary efforts and time to the developers as well as the testers. With an MVT<ref>http://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names</ref> (Model View Template) Framework, Django is very modular and thus very much suitable for highly cohesive<ref><rhttp://en.wikipedia.org/wiki/Cohesion_(computer_science)</ref> and low coupling<ref> http://en.wikipedia.org/wiki/Coupling_(computer_programming)</ref> tasks.


History

In 1998, Python CGI<ref>http://en.wikipedia.org/wiki/CGI</ref> was used to develop web applications from scratch using Python. In order to create a web application using Python CGI, we just have to create a Python script that generates output in the HTML format. We then save the script to a Web server with a “.cgi” extension and visit the page in our Web browser. Following is the sample way of creating a simple website using the script.

#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html\n"
print "<html><head><title>Food items</title></head>"
print "<body>"
print "<h1>Food items</h1>"
print "<ul>"
connection = MySQLdb.connect(user='username', passwd='password', db='food_db')
cursor = connection.cursor()
cursor.execute("SELECT food_item_name FROM food_table ORDER BY rating DESC LIMIT 10")
for row in cursor.fetchall():
	print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()

The above script generates an HTML page which will display a list of all the food items in the descending order of their rating by interacting with the respective table in the database.

Even though the code has several advantages which include such as making a website (with only one page) from the scratch is not difficult. It is readable and understandable to all audiences, etc. But this approach has a lot of disadvantages. The disadvantages include repetition of code (such as database connection, authentication, etc.) for a multi-page web application. Also, if discrete entities, like databases with different configuration, are to be included in the project then we will have to rewrite and reconfigure all the pages in the web application. There are many more disadvantages apart from these. Thus, using CGI for web application development makes it inefficient to build and deploy.

Almost all of the problems posed by Python CGI scripting mentioned above were solved by Django. Django provided a programming infrastructure for large scale web applications, so that the developers can focus on writing clean, maintainable code without worrying about the different aspects of Project Scaffolding<ref>http://en.wikipedia.org/wiki/Scaffold_(programming)</ref>. Based on the DRY<ref>http://en.wikipedia.org/wiki/Don't_repeat_yourself</ref>(Don’t Repeat Yourself) principle. Django aims at reducing repetitive pieces of information of all kinds in software development. Django also supports pluggability of different applications into the web applications that you are developing.

Also, Major websites such as Pinterest, Instagram were developed using Django.

Other Frameworks

  • Flask<ref>http://flask.pocoo.org/</ref>: It is a web framework that only provides the important and skeletal libraries required for basic web-development. Features such as data abstraction, unlike Django, is not provided by Flask.
  • Pyramid<ref>http://www.pylonsproject.org/projects/pyramid/about</ref>: It is a web framework which strictly follows MVC pattern. It has an additional feature, unlike Django, of maintaining a dictionary of View-to-URL-Mapping.
  • web2py<ref>http://www.web2py.com/init/default/what</ref>: It is a web framework which follows the convention of Ruby on Rails.


Architecture

Django's Model-View-Template Achitecture

Most of the web frameworks- such as Ruby on Rails framework- are based on the MVC pattern. MVC, which stands for Model View Controller, is a pattern which provides loose coupling among different parts of the application. In MVC Pattern, Model deals with the direct interaction with the databases. Views deal with the representation of the data on the browser. Controller deals with the user interactions and redirecting each of the user interactions to the respective module responsible for dealing with it.


On the other hand, Django framework does not really fit into the MVC framework. As mentioned earlier, it follows the MTV framework which stands for (Model Template View) Framework. Controller corresponds to the View in Django Framework. In case of the Views in Django, it plays the role of the controller. It fetches the data and decides how the data is to be displayed.








Applications

In Django terminology, an installation of Django is considered as a “Project”.

The smallest logical subset of files/folders that is fairly independent from the rest of the project can be called as an application. These subset of files include (but are not limited to) models, views, templates, static files, URLs, etc. A single Django projects can have multiple applications, each of which contains the files that define an application.

All the applications that must be included inside the main project should be explicitly mentioned inside the variable INSTALLED_APPS inside the settings.py.

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books',
)

Models

In Django, a model is defined as the single source for all the data. It defines how data is accessed, processed and validated. It also contains the structure and relationship of all the data that is used by the application. Models are used to define the structure of your database. Each model is converted into a database table and each attribute inside a model is converted into a column of that table. All this is handled by Django implicitly.

Consider the following example about an application called ‘books’ that contains:

  • Author: which has a first_name and last_name attributes
  • Book: which has title, author and publication date as its attributes

We can write models for the above application like:

class Author(models.Model):
   first_name = models.CharField(max_length=30)
   last_name = models.CharField(max_length=40)

class Book(models.Model):
   title = models.CharField(max_length=100)
   authors = models.ManyToManyField(Author)
   publication_date = models.DateField()

Once all the models for your application have been created, you can validate them by using:

python manage.py validate <app_name>

Django also dynamically generates “Create Table” statements for each of these models. These statement can be viewed using the command:

python manage.py sqlall <app_name>

The above command would give the following output:

BEGIN;
CREATE TABLE "books_author" (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(40) NOT NULL,
)
;
CREATE TABLE "books_book" (
    "id" serial NOT NULL PRIMARY KEY,
    "title" varchar(100) NOT NULL,
    "publication_date" date NOT NULL
)
;
CREATE TABLE "books_book_authors" (
    "id" serial NOT NULL PRIMARY KEY,
    "book_id" integer NOT NULL REFERENCES "books_book" ("id") DEFERRABLE INITIALLY DEFERRED,
    "author_id" integer NOT NULL REFERENCES "books_author" ("id") DEFERRABLE INITIALLY DEFERRED,
    UNIQUE ("book_id", "author_id")
)
;
COMMIT;

and all the tables would be created immediately as soon as you run the command stated below:

python manage.py syncdb

Views

The front-end of the web-application is equally important as the model and the controllers. The basic function of the view is to accept an HTTP request and send a response. Basically Django has two types of views – Generic Views & Class based views. Generic views just take one parameter – “request”. Following is the format of the code to display Hello World.

from django.http import HttpResponse
    	def hello_world(request)
                    	return HttpResponse(“hello world”)

Here, the method class hello_world has a parameter called “request”. This is the parameter that contains all the information of the HttpRequest. After the request has been processed, the HttpResponse object is returned back. This HttpResponse object is initialized with the string “hello world”.

Generic views mostly consist of functions. Maintaining a program with a lot of functions is difficult. This reduces the modularity of the program. In order to support classes, Class based views were introduced. Class based views consist of classes which handle all the functionality in the front end. Classes are extensible and hence reusable. We can inherit different views(classes) and include it in our class. For example, if we want to include a view which displays the contacts, we will write the following code.

from django.views.generic import ListView
from books.models import contacts
class ContactsList(ListView)
    	model = contacts

In the above program, we have imported the ListView from the generic module. As we want to display the contacts from the database, we have imported the database “contacts”. The class ContactsList inherits the ListView class and extracts all the functionality in that class. The “contacts” database is imported and assigned to the model so as to display the contacts in the form of a list view.

Just making the views is not enough. We need to map the views with the URL requests. This is done in the URLConf file – urls.py. It basically acts like a routing table to route the URL requests to the appropriate method call in the view. Suppose we want to make Django aware that the function hello_world() is actually a view function. Just making the views is not enough. We need to map the views with the URL requests. This is done in the URLConf file – urls.py. It basically acts like a routing table to route the URL requests to the appropriate method call in the view. Suppose we want to make Django aware that the function hello_world() is actually a view function. In order to do that, we will have to write the following code:

    	from django.conf.urls.defaults import patterns, include, url
    	from hellworldproject.views import hello
    	urlpatterns = patterns(‘’. url(r’hello_world/$, hello_world)

In the above code, the “pattern” function saves the required URL pattern in the “urlpatters” attribute. So, after everything is set up, we run our web application with a url say [web-address]/hello_world/. Now, Django first goes to the settings.py file in the project directory and searches for the files which handles the URLConf part. Suppose the name of the files is urls.py. It dives into the urls.py files and linearly matches the requested url with the url patterns in the file and checks which method call is responsible to handle the request. After that, when it finds the method(here, hello_world), it passes an HttpRequest object to the method. After the required processing the request, it creates an HttpResponse object and then continues with the further processes the response by converting it into HTML code by adding the necessary formatting to the response in order for it to be displayed as a view on the screen.

Templates

In Django, templates are generally used to define how webpages of the application are supposed to look like. Template defines the structure of the webpage and also has additional elements that help access variables, run python statements and much more.

Data can be passed to templates which can be used by the templates to display to the user or perform actions on the data and create dynamic views based on the data.

Variables

We can access any data passed to the templates and use them as regular python variables. The below lines of code shows how variables can be accessed:

Author: {{author.last_name}}, {{ author.first_name }}

which will just print the author’s name on the webpage.

Tags

Templates also provide the ability to write python code inside them and execute them just like they would run inside a “.py” file. These elements are known as tags and look like {% tag %}

Given below is the example of a “for” loop that is defined inside a template:

{% for book in books_list %}
    <li>{{ book.title }}</li>
{% endfor %}

You can process data (though it is not logical to do so in a template), write conditional statements or just declare variables inside tags and used them later in the template file.

Filters

Filters in templates can be defined as helper functions. They are a very powerful tool that reduces the code needed for basic (or sometimes even complex) post-processing of data.

For example, the title of a book could be added to your application as one of ‘HARRY POTTER’, ‘HaRrY pOtTeR’ or ‘harry potter’. To standardize the format of the book title which you want to show on your website, we can simply write

{{book.title|title }}

which capitalizes the first character of each word and turn all other characters to lower.

Django also provide the ability to write custom filters and make it available to all the templates in your application. Django provides template tags and filters to control internationalization in templates. They allow for granular control of translations, formatting, and time zone conversions.

Admin Site

For a certain class of Web sites, an admin interface is an essential part of the infrastructure.

This is a Web-based interface, limited to trusted site administrators, that enables the adding, editing and deletion of site content. So the admin site has to authenticate users, display and handle forms, validate input, and so on. But the best part about Django is that it does all of this and more for you – in just a few of lines of code. This is also one of the reasons why Django is called a “heavy” web development framework.

To access the Django admin interface, we just have to add /admin to your project url.


Django Admin site login page


We would also have to create a superuser, which can be done by following the steps given below.

$ python manage.py createsuperuser

Enter the admin username and email address:

Username: admin
Email address: admin@example.com

Choose the password for the admin account:

    Password: **********
    Password (again): *********
    Superuser created successfully.


Default admin site home page


Django contains a file called admin.py where you can define models for the admin site and then enable them so that they will appear on the admin site. Using the example of the Author Model described in the sections above, let us add it to the admin site:

    class AuthorAdmin(admin.ModelAdmin):
        pass

    admin.site.register(Author);

These out-of-the-box features of the Django framework is what makes it the perfect option for creating content driven websites in relatively no time at all.

Features

Django has the following features to name a few:

  • It facilitates developers with a template comprising minimal number of classes, modules, packages etc. so that the developers can focus more on the core business logic.
  • It contains an ORM (Object-Relational Mapper) that allows for the use of standard Python language. The developers need not learn any query processing language.
  • It provides with a template framework suitable for making the views.
  • It supports pluggability – that is it supports including other installed applications into your own application.
  • It has a built in administrative interface to manage the web application from an administrative level, thus providing access control.

References

Django Project

Django Book