Powering the Web with Python Web Frameworks

Greg Bates
Share

Introduction

Web frameworks are primarily server-side technologies that are designed to accomplish a series of specialized tasks. As it relates, Python Web frameworks are module and package collections that enable developers to build Web applications without concern for certain details. These details, handled by the chosen framework, eliminate complexities such as performance bottlenecks.

As such, developers are free to focus on Web development responsibilities, particularly application logic. Lastly, there are a number of Web frameworks that have been developed to facilitate Pythonic Web development, including Zope, CherryPy, and Django.

Developing a Web Application with Django

Django is a Python Web framework that is designed to support Rapid Application Development (RAD). Through its strict adherence to the Don’t Repeat Yourself (DRY) principle, Django facilitates the development of high-level, high-performing Web applications without the expense of time spent reinventing the wheel. Writing complete dynamic, data-driven Web sites and applications with Django is, therefore, a remarkably simple task with only two requisite steps:

  • Ensure that Python is installed.
  • Download and install Django.

Consider, for example, building a data-driven Web site.

From the terminal, navigate to the desired location of the new Web site and launch the Python interactive shell by typing python at the prompt. Then, enter the following code:

django-admin.py startproject my_new_web_site[code]

Here, the built-in command, <code>django-admin.py</code>, is used to create an on-the-fly project named “my_new_web_site”; the name may be any desired name.

Used to manage Django applications, the <code>django-admin.py</code> executable shell supplies a project with a list of Django subcommands. In this example, the <code>startproject</code> subcommand is used to create a Django project tree with the following structure: 

[code]my_new_web_site/
	manage.py
  	my_new_web_site/
		__init__.py
		settings.py
		urls.py
		wsgi.py

my_new_web_site represents the parent directory of the “my_new_web_site “ project. To avoid confusion, it is a good idea to rename this directory since Django, by default, uses the same name for the Python package.

manage.py is a multi-purpose utility that is used to communicate with the project.

my_new_web_site/my_new_web_site represents the actual location of the project’s Python package.

settings.py is where the project’s various configurations are set and stored.

urls.py is an important file that serves various functions such as decoupling URLs from Python code and mapping between URL functions and Python callbacks (Django “views”).

wsgi.py is employed given the presence of a WSGI-compatible Web server.

Running the Application

At this point, the project is developed and may be viewed in a Web browser by issuing the following command:

$ python manage.py runserver

This command will return to terminal, output similar to the following:

Validating models...

0 errors found
November 09, 2013 - 17:57:17
Django version 1.6, using settings 'my_new_web_site.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Simply direct a Web browser to the address: http://127.0.0.1:8000/ where the following message will be displayed:

It worked!
Congratulations on your first Django-powered page.

This completes the most rudimentary steps in creating a Web project and application powered by Python and the Django framework. However, the project is not very practical. To make the project a dynamic, data-driven application, a database—which will also eliminate much of the tedium and inefficiency of writing content—should be added.

Adding Database Functionality

By design, Django houses the contents of an application in a SQLite database without requiring any further action. And, while SQLite is sufficient for database novices or in instances where application growth is not a concern, it may otherwise be best to use a database such as MySQL.

As an example, and given that MySQL is already installed, create a MySQL database by running the following commands at the mysql prompt:

mysql> CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
mysql> CREATE DATABASE my_new_web_site;
mysql> GRANT ALL ON my_new_web_site.* TO 'username'@'localhost';

Upon successfully creating a new database, modify the configuration settings in settings.py by adding the following:

DATABASES = {
	'default': {
		'ENGINE': 'django.db.backends.mysql',
		'NAME': 'my_new_web_site',
		'USER': 'username',
		'PASSWORD': 'password',
		# localhost: leave “HOST” empty for domain sockets or use “127.0.0.1” for TCP.
		'HOST': '',
		# Leave the port number empty if using the default port, 8000.
		'PORT': '',
	}
}

This creates a new MySQL database that may be used across the entire application, but it neither initializes the database or creates an application “superuser” (administrator). To create a “superuser,” run the syncdb command and follow the on-screen prompts:

$ python manage.py syncdb

Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

…

Username (leave blank to use 'myusername'):
Email address:
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

The application now has a complete MySQL-powered back end, accessible via manage.py:

$ python manage.py shell
>>> from django.contrib.auth.models import User
>>> User.objects.all()
[<User: myusername>]

At this point, the project is fully developed and ready for its intended use: running a Web application.

Conclusion

Python Web frameworks are designed for matching incoming HTTP requests to specific Python code or to provide response and request objects. Additionally, these frameworks work in the development of large-scale Web applications such as Content Management Systems (CMSs), concept prototyping, and more. There are a number of Python Web frameworks that are geared towards object-oriented Web application development.

And, as illustrated by this introductory tutorial, some frameworks are full-stack applications that may be used to create fully functional, extensible, data-driven applications.