Home >Backend Development >PHP Tutorial >How to use uWSGI and nginx to build a Django project

How to use uWSGI and nginx to build a Django project

WBOY
WBOYOriginal
2016-07-30 13:31:531025browse

Foreword:

nginx and uWSGI are good choices for Django deployment, but they are not the only ones. They are all replaceable and other attempts are welcome.

A brief introduction to background knowledge:

1. WSGI is a Web server gateway interface. It is a specification for communication between web servers (such as nginx) and application servers (such as uWSGI servers).

2. uWSGI It implements WSGI, uwsgi, http and other protocols.

3. Nginx is a high-performance HTTP and reverse proxy server (we use Nginx because of its ability to efficiently handle static file requests)

4. Django is an open source web application framework that adopts the MVC design pattern .

5. Socket is used to implement inter-process communication. In our case, it is used to implement communication between nginx and uWSGI.

After a rough introduction to the components we need to use, let’s explain the construction in detail. Steps (please read carefully and make sure to do it right the first time)

The final work we need to complete is basically this:

Client (make web request) —— Server (nginx is used here) —— socket (Automatically generated communication file) - uwsgi - Django

A lot of the content below comes from http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html#configuring-uwsgi- to-run-with-a-ini-file

uWSGI installation and basic configuration:

We use the pip package management tool to install uWSGI:

sudo pip install uwsgi

If you don’t have pip yet , then install it:

Used in Debian and Ubuntu systems:

sudo apt-get install python-pip
Used in Fedora and CentOS systems:
sudo yum install python-pip
During the pip installation of uwsgi, if it prompts that there are dependencies that are not installed:

Debian and Ubuntu:

apt-get groupinstall "Development Tools"

apt-get install python-devel

Fedora and CentOS:

yum groupinstall " Development Tools"

yum install -y python-devel

Basic test

Create a test file test.py:

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return ["Hello World"] # python2
    #return [b"Hello World"] # python3

Run uWSGI

uwsgi --http :8000 --wsgi-file test.py
The code means Use http protocol, port 8000, to load our test file. If everything is fine, visit:

http://127.0.0.1:8000/ (note that the colon is the English colon)

You will see the familiar and cute Hello World. This also shows that we have opened the bridge between the client-uWSGI-Python.

Replace test.py with your Django project

First make sure that our project itself can run normally, enter your project directory in the terminal, and then type:

python manage.py runserver 0.0.0.0:8000
If it can run normally, stop Remove it and execute the following code, change nidegongchenming to your project name:

uwsgi --http :8000 --module nidegongchenming.wsgi
module *.wsgi means loading the wsgi module, please rest assured that you already have this module.

So now we have opened the bridge between client-uWSGI-Django, congratulations.

If your Django project is called abc, I suggest you copy all its contents to /var/www/. Then the manage.py file of your project is in /var/www/abc/, which can avoid some problems of not being able to provide services due to file permissions.

Okay, you can stop the service, let’s continue.

nginx installation and basic configuration:

Install nginx

Ubuntu and Debian:

sudo apt-get install nginx
sudo /etc/init.d/nginx start
Fedora and CentOS
sudo yum install nginx
sudo service nginx start
In Fedora, service nginx start will be redirected to systemctl start nginx .service.

If everything is normal (the default port 80 is not occupied), when you access 127.0.0.1 in the browser, you will see "Welcome to nginx on XXX"

Then now our bridge becomes: Client - Server (nginx)

If the port is occupied by Apache or something else, it doesn’t matter if the nginx service cannot be started successfully. Below we introduce how to configure nginx to listen to other ports.

Configure nginx

First we need a uwsgi_params file. This file will usually be in your nginx directory, such as mine in /etc/nginx/. Of course, if you don’t find it, you can also go https://github.com/nginx/nginx/blob/master/conf/uwsgi_params, copy a copy, or copy the following content

uwsgi_param  QUERY_STRING       $query_string;
uwsgi_param  REQUEST_METHOD     $request_method;
uwsgi_param  CONTENT_TYPE       $content_type;
uwsgi_param  CONTENT_LENGTH     $content_length;

uwsgi_param  REQUEST_URI        $request_uri;
uwsgi_param  PATH_INFO          $document_uri;
uwsgi_param  DOCUMENT_ROOT      $document_root;
uwsgi_param  SERVER_PROTOCOL    $server_protocol;
uwsgi_param  HTTPS              $https if_not_empty;

uwsgi_param  REMOTE_ADDR        $remote_addr;
uwsgi_param  REMOTE_PORT        $remote_port;
uwsgi_param  SERVER_PORT        $server_port;
uwsgi_param  SERVER_NAME        $server_name;

The file name is uwsgi_params, without suffix. Put it in your Django project, in the same directory as manage.py. Next we configure nginx and tell it to reference the uwsgi_params file.

Enter your Django project directory, create a file mysite_nginx.conf, and type in:

# mysite_nginx.conf

# the upstream component nginx needs to connect to
upstream django {
    # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
    server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# configuration of the server
server {
    # the port your site will be served on
    listen      8000;
    # the domain name it will serve for
    server_name .example.com; # substitute your machine's IP address or FQDN
    charset     utf-8;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /path/to/your/mysite/media;  # your Django project's media files - amend as required
    }

    location /static {
        alias /path/to/your/mysite/static; # your Django project's static files - amend as required
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed
    }
}
这个文件中的内容我保留了英文文档中的注释,比较详细,可能会对你有一些意外的帮助。

server{}中的server_name可以接IP地址,比如:server_name  219.242.174.48,测试的话用你本机的吧,搭好了之后方便在同网段内使用其它机器测试。

这份配置文件告诉nginx从文件系统中建立媒体和静态文件服务,同时也处理Django应用中的请求。对于大型的部署而言,让一个服务器处理静态/媒体文件,另一个处理Django应用,会有很好的表现。不过现在,我们这么做也没问题。

然后执行下面的命令,让nginx知道有这么一个配置文件:

sudo ln -s mysite_nginx.conf /etc/nginx/sites-enabled/

部署静态文件

在运行nginx之前,必须把所有的Django静态文件收集到一个静态文件夹中,首先在settings.py中写入:

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

然后运行

python manage.py collectstatic

基本nginx测试

重启nginx服务

Ubuntu,Debian:

sudo /etc/init.d/nginx restart
Fedora,CentOS:
sudo service nginx restart
或者
systemctl restart nginx.service

为了测试我们是不是可以提供访问媒体文件的服务,找张图片比如"abc.png",放到你的Django工程中的媒体目录下,比如/var/www/project/project/media。然后访问http://127.0.0.1:8000/media/abc.png,如果有问题,需要先停止nginx(上面命令中restart改成stop),再启动。这样我们能得到一些提示信息,以便找出问题在哪。

nginx和uWSGI以及test.py的沟通

uwsgi --socket :8001 --wsgi-file test.py
前面nginx已经被设置好在8001端口与uWSGI通信,同时在外界服务被布置在8000端口,访问:http://127.0.0.1:8000/

如果能看到Hell World,说明我们打通的桥梁变成:

客户端(浏览器)——服务器(nginx)——socket——uWSGI——python

同时你也可以访问http://127.0.0.1:8001/,看看uWSGI的反应,暂不剧透……

到现在我们都是在使用TCP port socket,这样开始的时候会容易些,不过实际上使用Unix sockets 会更好些,会有较小的开销。

编辑我们刚才的nginx配置文件mysite_nginx.conf,做以下更改:

server unix:///path/to/your/mysite/mysite.sock; # for a file socket
# server 127.0.0.1:8001; # for a web port socket (we'll use this first)
重启nginx,

停下刚才的uWSGI服务,输入以下命令重新开启:

uwsgi --socket mysite.sock --wsgi-file test.py
mysite.sock文件会被自动建立,用做通信,你可以当它是个临时文件。当然不喜欢这个文件名,你也可以更改。用浏览器再访问一次8000端口,看看结果。

如果服务没能正常运行,查看一次啊nginx的错误日志,在/var/log/nginx/error.log。如果错误日志像是这样:

connect() to unix:///path/to/your/mysite/mysite.sock failed (13: Permission
denied)
那可能需要更改socket的权限,以便nginx可以使用它。

试一下:

uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=666 # (very permissive)
或者:
uwsgi --socket mysite.sock --wsgi-file test.py --chmod-socket=664 # (more sensible)
可能你还需要把当前用户加入nginx用户组,反之也需要把nginx加入你当前用户的用户组。这样nginx应该就有权限访问socket文件了。

激动人心的时候要到了

现在我们可以尝试一下用uwsgi和nginx来运行我们的Django应用了。

在工程目录下运行:

uwsgi --socket mysite.sock --module mysite.wsgi --chmod-socket=664
注意mysite.wsgi要改成你的工程名。

现在应该在浏览器中能看到你的工程了。

用ini文件来配置uWSGI

创建一个文件命名为'mysite_uwsgi.ini'

# mysite_uwsgi.ini file
[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /path/to/your/project
# Django's wsgi file
module          = project.wsgi
# the virtualenv (full path)
# home            = /path/to/virtualenv

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 10
# the socket (use the full path to be safe
socket          = /path/to/your/project/mysite.sock
# ... with appropriate permissions - may be needed
# chmod-socket    = 664
# clear environment on exit
vacuum          = true
如果你使用了virtualenv,home那个位置就不能注释掉。

以后再运行 uswgi就可以使用:

uwsgi --ini mysite_uwsgi.ini
进一步我们还可以让uWSGI运行在上帝模式,设置开机自动启动以及限制最大访问,工程文件大小之类的配置。

去吃饭了

这些内容我可能会在下一篇博客里写,想先了解的同学请移步:http://uwsgi-docs.readthedocs.org/en/latest/tutorials/Django_and_nginx.html#configuring-uwsgi-to-run-with-a-ini-file
这个文档相当全面,而且重要的是没有拼写错误这种情况。







版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了如何用uWSGI和nginx来搭建Django工程,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn