Using NGINX+UWSGI to implement Python's Django frame site static and dynamic separation

Source: Internet
Author: User
Tags log log
Because:

Django processing static files is not very friendly;
Requests for PHP or other resources may need to be processed in the future;

So consider the combination of Nginx, using NIGNX to do its good route distribution function, while doing static and dynamic separation, that is, the HTTP request is uniformly distributed by Nginx, static files are processed by Nginx and returned to the client, while the dynamic request is distributed to the UWSGI, The UWSGI is then distributed to Django for processing. Client <-> nginx <-> socket <-> Uwsgi <-> Django

First, the environment

System: CentOS 6

    • python:2.7 (Note: Django needs to be in the 2.7 version or above in Python)
    • Nginx
    • Uswgi

So, before installing, check the default version of the current Python in the console input python-version, and if it is below 2.7, modify the default version. (See appendix)

Second, install Nginx, UWSGI

Installation

Nginxsudo Yum Install Nginx

Installation

Pipsudo Yum Install Python-pip

Installation

Uwsgisudo Pip Uwsgi


Third, test Nginx, Uwsgi
1. Test nginx start test Nginx, see if the installation successfully started Sudo service Nginx start and then in the browser, enter the IP address to see if the Nginx Welcome page appears, the installation is successful
2. Test Uwsgi in any directory on the server (usually in a directory under Home), create a new test.py, as follows:

# TEST.PYDEF Application (env, start_response):    start_response (' OK ', [(' Content-type ', ' text/html ')])    Return "Hello World"

Start the HTTP access Uwsgi, in the test.py same directory, enter the following command line (8001 is the listening port, can be changed to the port you want)

Uwsgi--http:8001--wsgi-file test.py

Then in the browser, enter the IP address: 8001, to see if the response to Hello World, is the installation success
P.S. Since the installation of UWSGI was using the wrong Python version at the beginning, on my server, the Uwsgi correctly executable command is temporarily:/usr/src/download/uwsgi-2.0.10/ UWSGI is the complete command line (all UWSGI commands in this article are the same):/usr/src/download/uwsgi-2.0.10/uwsgi--http:8001--wsgi-file test.py
--http:8001--wsgi-file test.py to this, Uwsgi and Nginx installation success. Next, connect Nginx, Uwsgi, and Django. In their collaboration, achieve the goal we want.

Iv. connecting Django and Uwsgi
As in the Uwsgi test, Uwsgi listens on port 8001 and sends the request to Test.py,python to execute the file, and if we give the test.py to the Django Portal file, the Django and UWSGI connections are implemented. So, there are two steps to doing things:

Create a wsgi.py file under the project directory
Start Uwsgi, use its wsgi-file to point to wsgi.py

wsgi.py content is as follows:

"" "WSGI config for Whpaiwechat project. It exposes the WSGI callable as a module-level variable named ' Application '. For more information on the this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/"" "Import Osfrom Django.core.wsgi Import Get_wsgi_applicationos.environ.setdefault ("Django_settings_module", "whpaiwechat.settings ") application = Get_wsgi_application ()

Start HTTP access to Uwsgiuwsgi--http:8000--chdir/home/jiayandev/whpaiwechat/--wsgi-file whpaiwechat/wsgi.py
Browser Access IP address: 8000, plus the necessary routes to access the previously written Python program: for example [Http://112.74.73.31:8000/wechat/call]
P.S. Are you concerned that starting the UWSGI can be done without having to start Django again?

V. Connecting UWSGI and Nginx
Next, get through the connection between Uwsgi and Nginx, they are connected through a socket. In the fourth section of the link SWGI and Django, we use the browser access is able to get the correct response, indicating that the connection was successful. So as long as the nginx, implement some rules, the front-end request to forward to this port. The thing to do is very simple, that is, configure the Nginx configuration file, generally in the/etc/nginx/conf.d/default.conf. Here, I only set a few simple rules

URL contains. css,. js and other server-specific directories, setting the root directory
Above are not matched to the access distribution to UWSGI, Nginx forwarded to USWGI processing

More rules are available depending on the business situation, and the complete configuration is as follows:

Upstream Django {server 127.0.0.1:8000; # Note 8000 is the above Uwsgi listening port}server {listen;  server_name _;  #charset Koi8-r;  #access_log Logs/host.access.log Main;  # Load configuration files for the default server block.  include/etc/nginx/default.d/*.conf;  Location =/404.html {root/usr/share/nginx/html;  } # REDIRECT Server error pages to the static page/50x.html # Error_page 502 503 504/50x.html;  Location =/50x.html {root/usr/share/nginx/html;        } location ~ \.html$ {Root/usr/share/nginx/html/front;  Index index.html index.htm; } location ~ \.  (PNG|JPG|JPEG|CSS|IMG|JS|FLV|SWF|DOWNLOAD|EOT|SVG|TTF|WOFF|WOFF2|OTF) $ {root/usr/share/nginx/html/front;  } # None of the above matches the access distribution to UWSGI on location/{include/etc/nginx/uwsgi_params; #详细看下文 uwsgi_pass Django;  } * # PHP is divided into 9000 ports * * # #location ~ \.php$ {# root HTML;  # Fastcgi_pass 127.0.0.1:9000;  # Fastcgi_index index.php; # Fastcgi_param Script_filename/Scripts$fastcgi_script_name;  # include Fastcgi_params; #}*}

At the same time, Uswgi_param content as follows, copy can

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 remote_addr    $remote _addr;uwsgi_param remote_port    $remote _port;uwsgi_ Param server_port    $server _port;uwsgi_param server_name    $server _name;

After the configuration is complete, reboot or reload Nginx configuration can take effect
Restart:

sudo service nginx restart

Reload

sudo service Nginx Reload

Then direct access to see what's different:
Http://youIP/front/index.html
Http://youIP/statics/index.html
http://youIP/(plus routing information), such as Http://112.74.73.31/wechat/call
Our main focus here is to visit Django, if the information returned by Http://112.74.73.31/wechat/call is the same as in section fourth, the Nginx and Uwsgi are also connected, so Nginx, Uwsgi, Django successfully connected to completion.

Six, optimize the start of UWSGI
In the third and fourth sections, when we start the UWSGI service, we use the command line to start and set parameters, so that it is not easy to remember, it is possible to forget the parameters and so on. Here's another way to set the parameters, which is to use the configuration file to record the parameters of the UWSGI, and load the parameters from the configuration file when you start. The parameters are as follows

#WHPAIWechat_uwsgi. Ini[uwsgi]socket = 127.0.0.1:8000chdir =/home/jiayandev/whpaiwechat/wsgi-file = whpaiwechat/ wsgi.pyprocesses = 4threads = 2master=true #设置此参数, there is a main process pidfile= pidfile/project-master.pid #主进程id写入文件里vacuum =true # When exiting, clean environment daemonize = uwsgi.log #守护进程的方式运行, log log is stored in this log file

Start Uwsgi command into Uwsgi Whpaiwechat_uwsgi.ini

  • 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.