Use Nginx + uWsgi to implement static/dynamic separation of Python Django framework sites

Source: Internet
Author: User
This article describes how to use Nginx + uWsgi to implement the deployment instance of the Django framework site static and dynamic separation of Python, that is, static processing by Nginx and Python page processing by Django's built-in HTTP server, for more information, see:

Django is not very friendly in processing static files;
Php or other resource requests may need to be processed in the future;

Therefore, we should consider using nginx to make it a good route distribution function. Meanwhile, static and dynamic separation means that Http requests are uniformly distributed by Nginx and static files are processed by Nginx and returned to the client; dynamic requests are distributed to uWsgi, which is then distributed to Django for processing. That is, the client <-> nginx <-> socket <-> uwsgi <-> Django

I. Environment

System: centOS 6

  • Python: 2.7 (Note: Django must be python 2.7 or later)
  • Nginx
  • Uswgi

Therefore, before installation, enter python-version in the console to view the current default version of python. If it is earlier than 2.7, modify the default version. (See appendix for details)

Ii. Install nginx and uWsgi

Install

nginxsudo yum install nginx

Install

pipsudo yum install python-pip

Install

uWsgisudo pip uwsgi


Iii. Testing nginx and uWsgi
1. Test nginx startup and test nginx. Check whether the installation is successful and start sudo service nginx start. Then, enter the IP address in the browser to check whether the nginx welcome page is displayed. If yes, the installation is successful.
2. test uWsgi to create a test. py directory on the server (usually in a directory under home), as shown in the following code:

# test.pydef application(env, start_response):    start_response('200 OK', [('Content-Type','text/html')])    return "Hello World"

Start uWsgi accessed in Http mode. in the same directory of test. py, enter the following command line (8001 is the listening port and can be changed to the desired port)

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

Enter the IP address 8001 in the browser to check whether the system responds to hello world. If yes, the installation is successful.
P.S. at the beginning, uwsgi was installed with the wrong python version. Therefore, on my server, the correct executable command of uwsgi is: /usr/src/download/uwsgi-2.0.10/uwsgi that is the complete command line is (all uwsgi commands in this article are the same as this):/usr/src/download/uwsgi-2.0.10/uwsgi -- http: 8001 -- wsgi-file test. py
-- Http: 8001 -- wsgi-file test. py so far, uwsgi and nginx are successfully installed. Next, associate nginx, uwsgi, and django. With their collaboration, we can achieve what we want.

4. Connect Django and uWsgi
As tested in uWsgi, uWsgi listens to port 8001 and distributes requests to test. py, python will execute this file, if we put test. if py is assigned to the Django entry file, the connection between Django and uWsgi is realized. Therefore, there are two steps to do:

Create the wsgi. py file in the project directory
Start uWsgi and use its wsgi-file to point to wsgi. py

The content of wsgi. py is as follows:

"""WSGI config for WHPAIWechat project.It exposes the WSGI callable as a module-level variable named ``application``.For more information on 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()

Enable Http access to uWsgiuwsgi -- http: 8000 -- chdir/home/jiayandev/whw.wechat/-- wsgi-file whw.wechat/wsgi. py
Browser access IP Address: 8000, with the necessary routes, you can access the previously written python program, for example, [http: // 112.74.73.31: 8000/wechat/call]
P.S. Have you noticed that you can start uwsgi without starting Django?

5. Connect uWsgi and nginx
Next, connect uWsgi to nginx through socket. Section 4 links swgi and Django. We can get the correct response through browser access, indicating that the connection is successful. Then, you only need to implement certain rules on nginx to forward the frontend requests to this port. You can simply configure the nginx configuration file, usually in/etc/nginx/conf. d/default. conf. Here, I only set a few simple rules

Urlpack contains. CSS,. js, and other server-specific directories, and set the root directory
If none of the above matched access requests are distributed to uwsgi, nginx forwards them to uswgi for processing.

More rules can be configured based on business conditions. The complete configuration is as follows:

Upstream django {server 127.0.0.1: 8000; # note that 8000 is the port of the uwsgi listener} server {listen 80 default_server; 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 500 502 503 5 04/50 x.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;} # The above unmatched access is distributed to uwsgi location/{include/etc/nginx/uwsgi_params; # For details, see the following uwsgi_pass django;} * # allocate PHP to port 9000 ** # 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, the uswgi_param content is as follows, just copy it

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, restart or reload nginx configuration to take effect.
Restart:

sudo service nginx restart

Reload:

sudo service nginx reload

Then, access it directly to see what is different:
Http: // youIP/front/index.html
Http: // youIP/statics/index.html
Http: // youIP/(with route information), for example, http: // 112.74.73.31/wechat/call
Here, we mainly focus on accessing django. If the returned information of http: // 112.74.73.31/wechat/call is the same as that of Section 4, nginx and uwsgi are connected, nginx, uwsgi, and django are successfully connected.

6. Optimize uwsgi startup
When starting the uwsgi service, we use the command line method to start and set parameters. This is not easy to remember and may forget the parameters. Here we will introduce another way to set parameters, that is, using the configuration file to record uwsgi parameters, loading parameters from the configuration file at startup. The parameters are as follows:

# WHPAIWechat_uwsgi.ini [uwsgi] socket = 127.0.0.1: 8000 chdir =/home/jiayandev/whevery WeChat/wsgi-file = whevery WeChat/wsgi. pyprocesses = 4 threads = 2 master = True # Set this parameter, there is a master process pidfile = pidfile/project-master.pid # master process id written to the file vacuum = True # exit, clean up the environment daemonize = uwsgi. log # Run as a daemon. log logs exist in this log file.

Run the uwsgi command to convert it to uwsgi WHPAIWechat_uwsgi.ini.

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.