Django is an open source web framework employed in commercial environments because it is easy to use, stable, and flexible (it takes advantage of the multiple libraries available in Python).
In this chapter, we will focus on the features that we think are crucial for managing and analyzing data in the framework. We also explain the main parts relevant to building an essential web application, but further details and information can be found online at https://docs.djangoproject.com or other sources. We will introduce the main parts of the framework with the basic concepts of a web server application (settings, models, and commands), the basics of HTML and the shell interface, and the general ideas of a REST framework interface and how it is implemented in Django (serializers, REST calls, and swagger). After a brief introduction of the HTTP GET and POST method for transferring data over the Internet, we start installing and creating a new server in Django.
Hypertext Transfer Protocol (HTTP) allows a client (for example, the web browser) to interact with a server (our application). Given a URL of a server web page, the GET method is the way the client queries data from the server, specifying some parameters. This can be explained using the curl
command, as follows:
curl -X GET url_path?name1=value1&name2=value2
After the ?
symbol, the name/value pair specifies which data to query, and they are separated by a &
symbol.
The way a client transfers data to the server is called POST, and the data is in the body of the call:
curl -X POST -d @datafile.txt url_path
Now we can start discussing how to create a new server and an application using Django.
The Django library is installed by typing the following command in the Terminal:
sudo pip instal django
The command should install Django Version 1.7 or above (the author used version 1.7). In order to start a new app, we type the following command:
django-admin startproject test_server
It will generate a new folder test_app
with the following tree of files:
└── test_server ├── manage.py └── test_server ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
We can see that, inside the folder, we have the manage.py
file, which allows the programmer to run various actions, and another subfolder, test_app
, with the following files:
settings.py
: This stores all the parameters' settings to configure the serverurls.py
: This collects all the URL paths available on your web application, and the actual functions behind the web pages are usually written in the views.py
app filewsgi.py
: This is a module to make a server communicate with a web application__init__.py
: This file is used to define every folder as a package, to import modules internallyOn our local machine, the server with a Welcome to Django page is deployed on http://127.0.0
.1:8080/
simply by typing the following command:
python manage.py runserver 8080
Here, 8080
is the port on which the server is started (if no port is specified, by default the server is started on port 8000
). Now that the server is ready, we can create as many applications as we want by simply typing the following command:
python manage.py startapp nameapp
This will create a new folder, nameapp
, inside the test_app
folder at root:
├── manage.py ├── nameapp │ ├── __init__.py │ ├── admin.py │ ├── migrations │ ├── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── test_server ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py
We will discuss the contents of this folder and its functions after we explain the most important settings parameters. Note that for Django Version 1.9, the nameapp
folder contains the apps.py
file in order to configure nameapp
without using the settings.py
file.
The settings.py
file stores all the configurations needed for the Django server to operate. The most important parameters to set are as follows:
INSTALLED_APPS = ( ... 'rest_framework', 'rest_framework_swagger', 'nameapp', )
The REST framework is an application that allows the Django app (nameapp
in this case) to communicate through a REST API, and the REST Framework Swagger is just a web interactive interface to manage the REST APIs. These functionalities will be explained in the following sections. Also, note that each app created needs to be added in this field (in this case, nameapp
).
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase', } }
The web pages are written in HTML, so a folder to store the HTML code is required. The templates
folder is usually used to store the web pages layout:
TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), )
static
, at the same level as the server
folder. Then the settings need to be configured to take the files from the folder:MEDIA_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_URL = '' STATIC_ROOT = '' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )
test_server/urls.py
):ROOT_URLCONF = 'test_server.urls'
logging
library and the following configuration:LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { 'default': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': 'test_server.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter':'standard', }, }, 'loggers': { '': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True }, } }
Here, the test_server.log
file stores all the print statements defined using the logging
library (for example, logging.debug('write something')
).
Now that all the most important settings are configured, we can focus on developing a new app that creates a simple email address book. So we create the app as usual:
python manage.py startapp addresesapp
Now, we add the templates and static folder on the root test_server
directory of the server:
├── addresesapp │ ├── __init__.py │ ├── admin.py │ ├── migrations │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py └── test_server ├── __init__.py ├── __init__.pyc ├── settings.py ├── settings.pyc ├── static ├── templates ├── urls.py └── wsgi.py
Note that the nameapp
on the INSTALLED_APPS
becomes addressesapp
. In the following section, we will discuss the main features of how to implement the app. All the code can be found in the chapter_6
folder of the author's GitHub repository (https://github.com/ai2010/machine_learning_for_the_web/tree/master/chapter_6).
3.145.9.148