Deploy Django applications using mod_wsgi

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

Deploy Django applications using mod_wsgi

Django is a free, open-source, Python-based Web development framework. The Django framework follows the MVC Architecture Pattern to quickly create Web applications. Currently, the Django framework has become one of the main choices for creating Web applications. For example, popular Instagram services, Bitbucket services, and Pinterest services are all developed using the Django framework.

In development mode, Django comes with a development server, which is only used for testing purposes. Digitalocean django nginx ubuntu 18 Once Web application development is completed, it should be deployed to the real production server. If the developer has not deployed a real Web application, refer to this article. This document provides detailed steps for deploying a Django application using mod_wsgi.

Django ubuntu nginx

I. mod_wsgi

WSGI, namely, Web Server Gateway Interface and Web Server Gateway Interface, is a Python standard for Web servers. It 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 Web servers.
Apache is one of the most popular Web servers. mod_wsgi is one of Apache modules and can be used to host Python applications on Apache servers. This method is relatively simple for deploying Django applications.

In Ubuntu 14.04, Python is installed by default. Next, deploy the Django application using mod_wsgi.

2. Create a Django Application

In this section, we will install the required software package, build a Hello World Django application, and provide services through the mod_wsgi module. Assume that you have logged on to the newly created virtual machine.

1. Create a Ubuntu Virtual Machine

Create a Linux virtual machine with the operating system Ubuntu 14.04 x64. The physical machine can also be used. Steps are omitted.

502 bad gateway nginx 1.10 3 ubuntu django

2. Install Python Package Manager

Use the Ubuntu Package Manager apt-get to install the Python Package Manager. Note: You must update the Ubuntu package manager before using it.

# sudo apt-get update

Pip is the Python package manager. It can help us install, modify, and uninstall Python packages. To install pip, run the following command:

# sudo apt-get install python-pip

The apt-get tool will install the latest stable version of pip. However, if you want to install a specified version of pip, you can install it from the source code.
Reference: https://pip.pypa.io/en/latest/installing.html
You can also use easy_install to replace pip, which has similar functions.

3. Install Django

To create a project from scratch, you must first install the Django software package. Run the following command:

# sudo pip install Django

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

# sudo pip install Django==1.5.5

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

4. install other Dependencies

To deploy an existing project, run pip recursively to install the project dependency. Normally, there is a configuration file named requirements.txt in the source code directory of the project, which contains the dependency packages required for running the project:

# pip install -r requirements.txt

If the project contains other Python projects, different versions of Python Packages may interfere with each other. The solution is to use virtualenv, which allows each Python project to run in its own virtual Python environment and is isolated from each other.
Here is 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 and want to create or update the configuration file, run the following command:

# pip freeze > requirements.txt

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

5. Create a Hello World Application

To create a Django application named helloworld, run the following 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 is displayed in the browser. Next, add settings. py to the project, locate INSTALLED_APPS, and add the following content:

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

Then, add the URL routing mode in urls. py. The content is as follows:

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

It instructs Django to find the home_view function in views. py. Therefore, modify views. py as follows:

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

Now we can run the Development Server:

# python manage.py runserver

Source code for this project on GitHub: https://github.com/sdaityari/django-hello-world

Iii. Use Apache and mod_wsgi modules to run Django applications

The directory structure of the Django project is described later. The following describes how to install and configure the Apache server.

1. Install Apache2

Use the apt-get command to install Apache2.

# sudo apt-get install apache2
2. Install the mod_wsgi Module

You can still use the apt-get command to install the mod_wsgi module.

# sudo apt-get install libapache2-mod-wsgi

Note that if Python3 is used, the command should be as follows:

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

For detailed installation process, refer:
Https://www.digitalocean.com/community/tutorials/installing-mod_wsgi-on-ubuntu-12-04

3. Modify the directory structure

To enable the Django application to provide services through the mod_wsgi module, we also need to write WSGI scripts to use this script to connect the Apache server to the Django application. The directory structure of the Django application is as follows:

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

We need to make some modifications 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 clear.

Note: If you use source code control tools 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 imports all settings and overwrites any settings for production status.
For example, the database settings and Debug settings in the production status may be different from those in the development status. To distinguish them from those in the source code, you need:

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

Finally, the wsgi. py file contains the WSGI settings. 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 the root directory ownership to the default user www-data of the Apache server so that the Apache server has the permission to access this directory:

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

To configure Apache to use the WSGI script, 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>

First, add a mypath alias to the Django Web directory so that the project can be accessed through URL: http://www.mydomain.com/mypath.
If you want to directly use a domain name for access, such as http://www.mydomain.com/, you can directly direct the application to django. The code block indicates that all permissions are granted to access the specified directory.

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

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

To provide the static file and media file services, you also need to configure them as follows:

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: For versions earlier than Apache 2.4, the configuration above is slightly different.

Django1.8 returns the json string and the content of the json string that receives the post.

How to Use Docker components to develop a Django project?

Install Nginx + uWSGI + Django on Ubuntu Server 12.04

Deployment of Django + Nginx + uWSGI

Django tutorial

Build a Django Python MySQL Linux development environment

Django details: click here
Django's: click here

This article permanently updates the link address:


Related Article

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.