Deploy Django Apps with Mod_wsgi

Source: Internet
Author: User
Tags ubuntu package manager install django pip install django virtualenv

Use Mod_wsgi to deploy Django app Chszs, all rights reserved, without consent, not reproduced. Blogger Home: Http://blog.csdn.net/chszs

Django is a free, open-source, Python-based web development framework. The Django framework follows the MVC architecture pattern to quickly create a web app as a target. Currently, the Django Framework has become one of the main choices for creating Web apps. such as popular Instagram services, BitBucket services, and Pinterest services have been developed using the Django framework.

In development mode, Django comes with a development server that is used for testing purposes only. Once you have completed the development of your Web application, you should deploy it to a real production server. If a developer hasn't deployed a real web app yet, you can refer to this article. This article provides detailed steps for deploying a Django application with Mod_wsgi.

First, Mod_wsgi

WSGI, the Web server Gateway Interface,web Server gateways interface, is a Web server Python standard that is defined in THE PEP 333 Standard and implemented by many frameworks. Python is a traditional programming language, so WSGI provides a way for Web servers to serve Python applications so that Python applications can interact with the Web server.
Apache is the most popular?? One of the Web servers, Mod_wsgi is one of the Apache modules that can be used to host Python applications on the Apache server. This approach is a relatively simple way to deploy a Django application.

In Ubuntu version 14.04, Python is included in the default installation. Here's where you start deploying Django apps with Mod_wsgi.

Ii. Creating a Django Application

In this section, we will install the required packages and build a Hello World Django application and provide services through the Mod_wsgi module. This assumes that you are already logged into the newly created virtual machine.

1. Create an Ubuntu virtual machine

Create an operating system for the Ubuntu 14.04 x64 Linux virtual machine, which can also be a physical machine. Step slightly.

2. Install Python Package Manager

Using Ubuntu's Package Manager apt-get, install Python Package Manager. Note that the Ubuntu Package Manager needs to be updated before use.

# sudo apt-get update

Pip is a Python language package Manager that can help us install, modify, and uninstall Python packages. To install Pip is very simple, execute the command:

# sudo apt-get install python-pip

The Apt-get tool comes with the latest stable version of the PIP installation. However, if you want to install the specified version of PIP, you can consider installing from the source.
Reference: https://pip.pypa.io/en/latest/installing.html
You can also use Easy_install instead of PIP, which has similar functionality.

3. Installing Django

To create a project from scratch, you need to install the Django package first. Execute command:

# sudo pip install Django

To specify the installation version of Django, such as version 1.5.5, you can:

# sudo pip install Django==1.5.5

Of course, you can still use Ubuntu's Package Manager apt-get to install Django, but this may not install the latest stable version of Django.

4. Install other dependencies

If you are deploying an existing project, you can run the PIP recursively to install dependencies on the project. Typically, there is a configuration file named Requirements.txt in the source directory of the project, which contains the dependent packages required to run the project:

# pip install -r requirements.txt

If the project also contains other Python projects, there may be different versions of Python packages that can interfere with each other. The workaround is to use virtualenv, which allows each Python project to run in its own virtual Python environment and is isolated from one another.
Here's a virtualenv tutorial: https://www.digitalocean.com/community/tutorials/ Common-python-tools-using-virtualenv-installing-with-pip-and-managing-packages
If you are developing a Django application, you may want to create or update a configuration file to execute the command:

# pip freeze > requirements.txt

The pip freeze command prints the Python package that is already installed in the current environment, and the greater than symbol ">" outputs the execution result of the command to the specified requirements.txt configuration file.

5. Create the Hello World application

To create a Django app named HelloWorld, run the command:

# django-admin.py startproject helloworld

Note that a new directory named HelloWorld is created. To run this project, you can:

# cd helloworld/# django-admin.py startapp helloapp

The output of Hello world can be seen in the browser. Next, add settings.py to the project, locate Installed_apps, and add the following:

INSTALLED_APPS = (    ‘django.contrib.auth‘,    ‘django.contrib.contenttypes‘,    ‘django.contrib.sessions‘,    ‘django.contrib.sites‘,    ‘django.contrib.messages‘,    ‘django.contrib.staticfiles‘,    ‘helloapp‘)

Next, add the URL route pattern in urls.py, which reads:

urlpatterns = patterns(‘‘,    # Examples:    # url(r‘^$‘, ‘helloworld.views.home‘, name=‘home‘),    url(r‘^‘, ‘helloapp.views.home_view‘),)

It instructs Django to look for the Home_view function in views.py. Therefore, the contents of the modified views.py are as follows:

from django.http import HttpResponsedef home_view(request):    return HttpResponse(‘Hello World‘)

Below, we can run the development server:

# python manage.py runserver

On GitHub There is the source code for this project: Https://github.com/sdaityari/django-hello-world

Iii. running Django applications using Apache and MOD_WSGI modules

The following is a description of the Django project's directory structure, which requires the installation and configuration of the Apache server.

1, installation Apache2

Complete the installation of Apache2 using the Apt-get command.

# sudo apt-get install apache2
2. Installing the Mod_wsgi module

You can still install the Mod_wsgi module using the Apt-get command.

# sudo apt-get install libapache2-mod-wsgi

Note that if you are using Python3, the command should look like this:

# sudo apt-get install libapache2-mod-wsgi-py3

The detailed installation process can be consulted as follows:
https://www.digitalocean.com/community/tutorials/installing-mod_wsgi-on-ubuntu-12-04

3. Modify the directory structure

To enable the Django application to serve through the Mod_wsgi module, we also need to write a WSGI script that uses this script to complete the connection between the Apache server and the Django application. The directory structure of the Django app is as follows:

mysite/    manage.py    mysite/        __init__.py        settings.py        urls.py    myapp/        models.py        views.py

We need to make a little change so that the MySite directory contains three files:

mysite/    manage.py    mysite/        __init__.py        settings.py        urls.py        apache/            __init__.py            override.py            wsgi.py    myapp/        models.py        views.py

In this case, the logic is not quite clear.

Note that if you use a source control tool such as Git, you can add the Apache directory to the Ignore list.

4. Create a WSGI script

The empty file init. PY will tell Python to treat this directory as a package. override.py will import all settings and overwrite any settings that are used for production status.
For example, the production status of the database settings and debug settings may be different from the development status, to distinguish between the source code, it is necessary:

# override.pyfrom mysite.settings import *DEBUG = TrueALLOWED_HOSTS = [‘www.mydomain.com‘, ‘mydomain.com‘]

Finally, the wsgi.py file contains the settings for WSGI. Assume that the root directory is/home/myuser/:

#wsgi.pyimport os, sys# Calculate the path based on the location of the WSGI script.apache_configuration= os.path.dirname(__file__)project = os.path.dirname(apache_configuration)workspace = os.path.dirname(project)sys.path.append(workspace)sys.path.append(project)# Add the path to 3rd party django application and to django itself.sys.path.append(‘/home/myuser‘)os.environ[‘DJANGO_SETTINGS_MODULE‘] = ‘mysite.apache.override‘import django.core.handlers.wsgiapplication = django.core.handlers.wsgi.WSGIHandler()

You also need to assign ownership of the root directory to the Apache server's default user Www-data so that the Apache server has access to this directory:

# sudo chown www-data:www-data apache/
5. Configure Apache

To configure Apache to use the Wsgi script just now, you need to edit the configuration file:

# sudo vi /etc/apache2/sites-enabled/000-default.conf

Add the following content:

<VirtualHost *:80>    WSGIScriptAlias /mypath/ /home/myuser/mysite/apache/wsgi.py    <Directory "/home/myuser/mysite/apache/">      Require all granted    </Directory></VirtualHost>

The first behavior of the Django Web directory is to add a mypath alias so that the project can be accessed through url:http://www.mydomain.com/mypath/.
If you want to use domain name access directly, for example: http://www.mydomain.com/, you can point directly to the Django application. The code block indicates that access to the specified directory has all permissions.

If you want to customize the robots.txt and icons, you can add the following:

Alias /robots.txt /home/myuser/mysite/robots.txtAlias /favicon.ico /home/myuser/mysite/favicon.ico

To provide a static file and media file service, you need to configure this separately:

Alias /media/ /home/myuser/mysite/media/Alias /static/ /home/myuser/mysite/static/<Directory /path/to/mysite.com/static>Require all granted</Directory><Directory /path/to/mysite.com/media>Require all granted</Directory>

Finally, save the configuration file and restart Apache:

# sudo service apache2 restart

Note the Apache version: for versions prior to Apache 2.4, the above configuration is slightly different.

Copyright NOTICE: This article for Bo Master Chszs original article, without Bo Master permission not reproduced.

Deploy Django Apps with Mod_wsgi

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.