mod_wsgi.so_在Ubuntu 14.04上使用mod_wsgi部署Django应用

mod_wsgi.so

Django is a free, open-source, Python-based web framework. Django follows the MVC architectural pattern, with special emphasis on creating your applications rapidly. In recent times, Django has become a popular choice for creating web applications. Popular services like Instagram, Bitbucket and Pinterest were developed using Django.

Django是一个免费的,开源的,基于Python的Web框架。 Django遵循MVC架构模式,特别强调快速创建应用程序。 最近,Django已成为创建Web应用程序的流行选择。 Instagram,Bitbucket和Pinterest等热门服务是使用Django开发的。

In development mode, Django has a development server, which is sufficient for testing purposes. Once you complete a web application and it's ready for production, the process of setting up the application on a server might be overwhelming for some, especially if you're doing it for the first time. This article provides a step-by-step guide on how to deploy Django-based web applications using mod_wsgi.

在开发模式下,Django有一个开发服务器,足以用于测试目的。 一旦完成了Web应用程序并将其准备投入生产,在某些服务器上设置该应用程序的过程可能会有些不堪重负,特别是如果您是第一次进行此操作。 本文提供了有关如何使用mod_wsgi部署基于Django的Web应用程序的分步指南。

mod_wsgi (mod_wsgi)

WSGI, or Web Server Gateway Interface, is a Python standard for web servers. Python was traditionally developed as a programming language, so WSGI provides a way for web servers to serve applications developed in Python. It enables web applications in Python to interact with web servers, acting as a link between the two.

WSGI或Web服务器网关接口,是Web服务器的Python标准。 Python传统上是作为一种编程语言开发的,因此WSGI为Web服务器提供了一种服务以Python开发的应用程序的方式。 它使Python中的Web应用程序可以与Web服务器交互,充当两者之间的链接。

Apache is one of the most popular web servers, and mod_wsgi is an Apache module that's used to host Python applications on Apache. It's also a relatively simple way of deploying a Django application.

Apache是​​最流行的Web服务器之一,而mod_wsgi是一个Apache模块,用于在Apache上托管Python应用程序。 这也是部署Django应用程序的相对简单的方法。

Python comes installed by default in Ubuntu 14.04. Let us now look at the step by step guide to deploy a Django application using mod_wsgi.

Python默认安装在Ubuntu 14.04中。 现在,让我们看一下使用mod_wsgi部署Django应用程序的分步指南。

1.创建Django应用程序 (1. Creating a Django Application)

In this section, we're going to install the required packages and set up a hello world Django application to be served by mod_wsgi. We'll assume that you've logged in to a newly created virtual machine.

在本节中,我们将安装所需的软件包并设置一个由mod_wsgi提供服务的hello world Django应用程序。 我们假设您已经登录到新创建的虚拟机。

1.1创建一个新用户(可选) (1.1 Create a New User (Optional))

If you create a VM using AWS or Microsoft Azure, you're logged in as a user that you specified while creating the VM, so you can skip this step.

如果使用AWS或Microsoft Azure创建VM,则将以创建VM时指定的用户身份登录,因此可以跳过此步骤。

There are some extra steps if you're first logged in as a root user (if you create a new VM with Digital Ocean). Although you can perform all functions using the same user, it's generally advised to create a new user. Here are detailed instructions for creating users and adding them to the sudoers list on Ubuntu 14.04.

如果您首先以root用户身份登录(如果使用Digital Ocean创建新的VM),则还有一些额外的步骤。 尽管您可以使用同一用户执行所有功能,但通常建议创建一个新用户。 以下是在Ubuntu 14.04上创建用户并将其添加到sudoers列表的详细说明

1.2安装Python套件管理员 (1.2 Install a Python Package Manager)

In this tutorial, we're going to use the Ubuntu package manager, apt-get, for installing packages. However, on a fresh VM, you must update packages first by running the following command:

在本教程中,我们将使用Ubuntu软件包管理器apt-get来安装软件包。 但是,在新的VM上,必须首先通过运行以下命令来更新软件包:

sudo apt-get update

Pip is a Python package manager that helps us install, modify or remove Python packages. The easiest way to install pip in Ubuntu is by using the Ubuntu package manager apt-get:

Pip是一个Python软件包管理器,可以帮助我们安装,修改或删除Python软件包。 在Ubuntu中安装pip的最简单方法是使用Ubuntu软件包管理器apt-get

sudo apt-get install python-pip

apt-get installs the latest stable version of pip. Alternatively, if you require a specific version of pip, you can install it from the source code. However, for the purposes of deploying a Django application, installing it through the package manager should suffice.

apt-get安装pip的最新稳定版本。 或者,如果您需要特定版本的pip ,则可以从源代码中进行安装 。 但是,出于部署Django应用程序的目的,通过软件包管理器进行安装就足够了。

You can also use easy_install as an alternative to pip. However, in this tutorial, we'll use pip to install packages.

您也可以使用easy_install替代pip 。 但是,在本教程中,我们将使用pip安装软件包。

1.3安装Django (1.3 Install Django)

If you're creating a project form scratch, you just need the Django package. In this example, we wouldn't require any further packages:

如果要从头开始创建项目表单,则只需要Django包。 在此示例中,我们不需要任何其他软件包:

sudo pip install Django

If you want to install a specific version of the package, you can specify it in the command as shown below (in case your application was coded in an older version of Django):

如果要安装该软件包的特定版本,则可以在如下所示的命令中进行指定(如果您的应用程序是在旧版本的Django中编码的):

sudo pip install Django==1.5.5

You can also install Django through the package manager apt-get. Caution must be exercised when following this step as apt-get might not be updated with the latest stable version as compared to pip.

您还可以通过包管理器apt-get安装Django。 遵循此步骤时,必须谨慎,因为与pip相比, apt-get可能不会使用最新的稳定版本进行更新。

1.4安装和冻结其他要求(可选) (1.4 Install and Freeze Other Requirements (Optional))

If you're deploying an existing project, you can recursively run pip to install the dependencies in the project. Generally, there's a file requirements.txt in the source directory of the project, which contains the packages required to run the project:

如果要部署现有项目,则可以递归运行pip在项目中安装依赖项。 通常,项目的源目录中有一个文件requirements.txt ,其中包含运行项目所需的软件包:

pip install -r requirements.txt

If your system has other Python projects, the versions of different Python packages might interfere with one another. A solution to this is to use virtualenv and keep every project in its own virtual Python environment. Here's a tutorial on getting started with virtualenv. Since we're deploying an application on a server, we aren't going to work with virtualenv in this tutorial.

如果您的系统具有其他Python项目,则不同Python软件包的版本可能会相互干扰。 解决方案是使用virtualenv并将每个项目保留在其自己的虚拟Python环境中。 这是有关virtualenv入门的教程。 由于我们要在服务器上部署应用程序,因此本教程中不会使用virtualenv

If you're working on a Django application and you want to create or update the requirements file, you could just run the following:

如果您正在使用Django应用程序,并且想要创建或更新需求文件,则可以运行以下命令:

pip freeze > requirements.txt

pip freeze prints a list of installed Python packages in your current environment, and the > stores the output of the command pip freeze into the file requirements.txt.

pip freeze打印当前环境中已安装的Python软件包的列表,然后>pip freeze命令的输出存储到文件requirements.txt

1.5创建Hello World应用程序 (1.5 Create Hello World Application)

To create a new project in Django named helloworld, run the following:

要在Django中创建一个名为helloworld的新项目,请运行以下命令:

django-admin.py startproject helloworld

You'll notice that a new directory helloworld has been created. Change your directory to helloworld and run the following to start a new app helloapp within the Django project:

您会注意到已经创建了一个新目录helloworld 。 将目录更改为helloworld并运行以下命令以在Django项目中启动新的应用helloapp

cd helloworld/
django-admin.py startapp helloapp

We can now create a sample view that prints Hello World in our browser. First, add the new app to your project's settings.py. Search for INSTALLED_APPS in the file, and add the name of our new app to it. It should look something like the following:

现在,我们可以创建一个示例视图,在我们的浏览器中打印“ Hello World” 。 首先,将新应用添加到项目的settings.py 。 在文件中搜索INSTALLED_APPS ,然后在其中添加新应用的名称。 它看起来应该如下所示:

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

Next, we add a URL pattern to the urls.py of the project. It looks something like this:

接下来,我们将URL模式添加到项目的urls.py 看起来像这样:

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

This instructs Django to look for the function home_view within the views.py of the app helloapp. Therefore, we edit the views.py file to look like the following:

这指示Django的查找功能home_view的内views.py应用HELLOAPP的。 因此,我们将views.py文件编辑为如下所示:

from django.http import HttpResponse

def home_view(request):
    return HttpResponse('Hello World')

Next, we run the development server by running the following:

接下来,我们通过运行以下命令来运行开发服务器:

python manage.py runserver

The code for the hello world Django application is available on GitHub.

GitHub上提供了hello world Django应用程序的代码。

2.通过Apache和mod_wsgi服务Django应用程序 (2. Serving a Django Application Through Apache and mod_wsgi)

Now that we've created a hello world application, this section explores how you can configure different settings in order to serve the application through Apache and mod_wsgi.

现在,我们已经创建了一个hello world应用程序,本节将探讨如何配置不同的设置,以便通过Apache和mod_wsgi为该应用程序提供服务。

2.1安装Apache2 (2.1 Install Apache2)

Using the apt-get command, installing Apache is also a one step process. Run the following command:

使用apt-get命令,安装Apache也是一个一步的过程。 运行以下命令:

sudo apt-get install apache2

2.2安装mod_wsgi (2.2 Install mod_wsgi)

The mod_wsgi module for Apache can be installed on Ubuntu 14.04 using apt-get:

可以使用apt-get在Ubuntu 14.04上安装Apache的mod_wsgi模块:

sudo apt-get install libapache2-mod-wsgi

If you're using Python 3 instead of Python 2, run the following:

如果您使用的是Python 3而不是Python 2,请运行以下命令:

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

Here's a tutorial with detailed instructions on installing mod_wsgi on Ubuntu.

这是一个教程,其中包含在Ubuntu安装mod_wsgi详细说明。

2.3修改目录结构 (2.3 Modifying Directory Structure)

To serve the Django application through mod_wsgi, we need to write a WSGI script that serves as a connection between Apache and Django. The Django file structure by default is something like this:

要通过mod_wsgi为Django应用程序提供服务,我们需要编写一个WSGI脚本,该脚本用作Apache和Django之间的连接。 默认情况下,Django文件结构是这样的:

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

We're going to change it a bit and add an apache directory within mysite to contain three files:

我们将对其进行一些更改,并在mysite添加一个apache目录以包含三个文件:

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

This helps separate the logic, and you could also ignore the directory as a whole in your version control system.

这有助于分离逻辑,并且您也可以在版本控制系统中忽略整个目录。

Note: if you're using a version control software (VCS) like Git, you can add the apache directory to the ignore list of the VCS.

注意:如果您使用的是Git之类的版本控制软件(VCS),则可以将apache目录添加到VCS的忽略列表中。

2.4创建WSGI脚本 (2.4 Create WSGI Script)

The empty __init__.py file tells Python to treat the directory as a package. The override.py imports all settings and overrides any settings for production. For instance, databases and debug settings for production might be different from those of development, and you may want to separate them from the source code:

空的__init__.py文件告诉Python将目录视为程序包。 override.py导入所有设置,并覆盖用于生产的所有设置。 例如,用于生产的数据库和调试设置可能与用于开发的数据库和调试设置不同,您可能希望将其与源代码分开:

# override.py

from mysite.settings import *

DEBUG = True
ALLOWED_HOSTS = ['www.mydomain.com', 'mydomain.com']

Finally, the wsgi.py file contains the WSGI settings. We're assuming that the root directory shown above is contained in the home directory of the user (/home/myuser/):

最后, wsgi.py文件包含WSGI设置。 我们假设上面显示的根目录包含在用户的主目录( /home/myuser/ )中:

#wsgi.py
import 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.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

You also need to transfer the ownership of the apache directory to Apache's default user www-data in order to allow it to access the directory:

您还需要将apache目录的所有权转移到Apache的默认用户www-data ,以便允许它访问目录:

sudo chown www-data:www-data apache/

Note: Thanks to Scott Taggart in the comments for pointing out that the wsgi.py script shown above will throw an error in Django 1.8 (Django 1.7 was used for this article). As noted by Scott, for the script to work with Django 1.8, the last two lines need to be replaced with:

注意:感谢Scott Taggart在评论中指出,上面显示的wsgi.py脚本将在Django 1.8中引发错误(本文使用Django 1.7)。 正如Scott所指出的,要使脚本与Django 1.8一起使用,最后两行需要替换为:

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

2.5配置Apache设置 (2.5 Configure Apache Settings)

To configure Apache to use your WSGI script, you need to edit the configuration file as shown below (using a text editor, in this case VIM):

要将Apache配置为使用WSGI脚本,您需要编辑配置文件,如下所示(使用文本编辑器,在本例中为VIM):

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

Add the following lines to the file:

将以下行添加到文件中:

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

The first line adds an alias of /mypath to the root of your web application. Your web application would now run on your domain—http://www.mydomain.com/mypath/. Replace /mypath/ above with / if you want your domain, http://www.mydomain.com/ , to directly point to the Django application. The <Directory> block is to allow requests to the directory that contains the WSGI script.

第一行将/mypath的别名添加到Web应用程序的根目录。 您的Web应用程序现在将在您的域上运行-http http://www.mydomain.com/mypath/ //www.mydomain.com/mypath/。 更换/mypath/以上/如果你希望你的域名, http://www.mydomain.com/ ,直接指向Django应用程序。 <Directory>块用于允许请求包含WSGI脚本的目录。

If you have a custom robots.txt and favicon, you may add an alias as follows:

如果您有自定义的robots.txt和favicon,则可以添加别名,如下所示:

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

In each of the lines above, the first argument after the keyword Alias signifies the URL pattern, and the second argument shows the path to the file to be served. This example assumes that your files robots.txt and favicon.ico are saved in the mysite directory.

在上面的每一行中,关键字Alias之后的第一个参数表示URL模式,第二个参数显示要提供服务的文件的路径。 本示例假定您的文件robots.txtfavicon.ico保存在mysite目录中。

To serve static and media files, you need to create their alias entries 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 and close the file and restart Apache to see the changes:

最后,保存并关闭文件,然后重新启动Apache以查看更改:

sudo service apache2 restart
有关旧版本Apache的注释 (Note for older versions of Apache)

For Apache versions older than 2.4 (like the one in Ubuntu 12.04), you need to replace Require all granted by Allow from all after adding the line Order deny,allow above it.

对于Apache早于2.4的版本(如Ubuntu 12.04中的版本),您需要在添加Order deny,allow在其上面Order deny,allow行之后,替换Require all grantedAllow from all Require all granted

Django包提供的静态文件注意事项 (Note for static files being served by Django packages)

Some Django packages have their own static and media files. In the development version, it's taken care of by Django, but it doesn't work that way when serving through Apache (including the Django admin static files). The static files are usually located in the same place where packages are installed.

一些Django软件包具有自己的静态文件和媒体文件。 在开发版本中,它由Django处理,但是在通过Apache提供服务(包括Django管理静态文件)时,这种方式无法正常工作。 静态文件通常位于安装软件包的同一位置。

An easy way to override them is to copy their static files to your static directory (and commit them), which is a rather messy solution. A better way would be to create an alias for the particular set of static files, just like you created alias entries for static and media roots.

覆盖它们的一种简单方法是将其静态文件复制到您的静态目录中(并提交它们),这是一个非常麻烦的解决方案。 更好的方法是为特定的静态文件集创建别名,就像您为静态和媒体根目录创建别名条目一样。

A discussion on StackOverflow gives an example of how to take care of the Django admin static and media files. You need to follow the same pattern for every other package that uses static and media files.

关于StackOverflow的讨论提供了有关如何处理Django admin静态和媒体文件的示例。 您需要为使用静态文件和媒体文件的其他所有软件包遵循相同的模式。

结论 (Conclusion)

In recent years, Django has become the first choice among many programmers. Although many accuse Python of being slow, websites like Instagram and Disqus—which run on Django—have scaled to millions of users. If you're interested, you may want to read how HackerEarth scaled their Django-based web application using mod_wsgi.

近年来,Django已成为许多程序员的首选。 尽管许多人指责Python的运行速度很慢,但可以在Django上运行的Instagram和Disqus等网站已扩展到数百万用户。 如果您有兴趣,则可能需要阅读HackerEarth如何使用mod_wsgi扩展其基于Django的Web应用程序

I hope this tutorial has helped you in deploying your Django-based web application on the server using Apache and mod_wsgi. If you faced any difficulties, let me know in the comments below.

我希望本教程可以帮助您使用Apache和mod_wsgi在服务器上部署基于Django的Web应用程序。 如果您遇到任何困难,请在下面的评论中告诉我。

翻译自: https://www.sitepoint.com/deploying-a-django-app-with-mod_wsgi-on-ubuntu-14-04/

mod_wsgi.so

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值