CSC/ECE 517 Fall 2014/ch1a 8 sn

From Expertiza_Wiki
Revision as of 19:06, 17 September 2014 by Njosyab (talk | contribs)
Jump to navigation Jump to search

Django Framework

Django is a high level, but heavy, Python based web framework used to build a large scale web application. 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 effort and time of the developers as well as the testers. Django provides high-level abstractions of common Web development patterns, shortcuts for frequent programming tasks, and clear conventions to solve problems. With an MVT Framework, Django is very modular and thus very much suitable for highly cohesive and low coupling tasks.


History

In 1998, Python CGI 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 your 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:

  • Writing from the scratch doesn't seem like a bad idea for a script like this.
  • This code is easy to understand even for the novice developers to read and modify.
  • Easy to deploy as we just have to save the file with "*.cgi" extension, upload it to a web server of your choice and host it. You will be able to access the web page from your browser.

But even though it seems simple, there are numerous disadvantages to this approach. To name a few:

  • When we have a multi-page web application, which is very common these days, all of these pages might want to access the database. Replicating the database connecting code in every page is not a good practice.
  • Accessing the different databases with different credentials located spatially far away will create a mess in using the CGI script approach because that needs some environment specific configuration.
  • There are several important tasks associated with the web applications such as closing the database connection, including necessary tags in each of the files etc. which is a very repetitive and time consuming task.

Django had a solution to all of these and many other problems that the developers and the testers face during the different phases of web development. It is a Web framework that provides a programming infrastructure for your applications, so that the developers can focus on writing clean, maintainable code without worrying about the different aspects of Project Scaffolding. Django is DRY (Don't Repeat Yourself). DRY aims at reducing repetitive pieces of information of all kinds in software development.

Other Frameworks

  • Flask: An open source micro web framework that provides only the core libraries of web development. It does not provide database abstraction, form validation or any other component that can be provided a third-party component.
  • Pyramid: An open source minimalistic web framework inspired by Zope, Pylons and Django. It strictly adheres to the MVC (Model-View-Controller) pattern and persistence agnostic.
  • web2py: An open source macro web framework inspired by Ruby-on-Rails. It follows Ruby-on-Rails' convention over configuration approach and provides sensible defaults for various components and libraries.


Architecture

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',
    'polls',
)

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

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);

ImageURL: Add an image here

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 sum it all:

  • It contains the basic modules, classes, and tools to quickly develop and deploy web apps
  • It contains an ORM (Object-Relational Mapper) that allows for the use of standard Python language syntax when interfacing with a back-end database.
  • Developer need not learn SQL, DDL, etc!
  • It provides a template framework that allows HTML, XML, and other “documents” to be converted into “templates”, which can then be converted to “output” via a wide range of substitution techniques.
  • It is Fast and easy to use, robust, flexible, and lots of contributed components available.
  • It has built in administrative interface to manage data models.
  • It has built-in authentication/access control components
  • It has contributed geospatial support components (GeoDjango)
  • It is Extensible.