Usage uWSGI and Django and Nginx to set up your Web server] --2019-08-06 16:01:12

Original link: http://106.13.73.98/__/101/

@
***

supplement

Pip check all installed packages:

pip3.6 list

The current environment in all Python packages introduced into the file:

pip3.6 freeze > test.txt

All files are installed Python package within the current environment:

pip3.6 install -r test.txt

It called the WSGI
.
The WSGI Gateway Interface is a Web server, which is a specification that describes how a Web server and Web application communication, and how to link Web application with a processing request (request reception, processing request, in response to the request).
.
there Bottle, Django, Flask framework based wsgi run for parsing dynamic HTTP request.
.
--------- ⬇️
support WSGI server
.
wsgiref
Python comes with the server.
.
Gunicorn
for Linux python wsgi Http server , commonly used in various Django, Flask combined with the deployment server.
.
mode_wsgi
realized the combination of Apache and wsgi application.
. C language development, rapid, self-healing, developer-friendly WSGI server for Python Web application deployment and professional development. --------- ⬆️ . when Python Web application deployment program, according to performance requirements, select the appropriate wsgi server, a different server wsgi difference lies in the concurrent support, there are single-threaded, multi distinction process, multithreading, coroutine, its function is similar to simply request routing, perform the corresponding function, returns the processing result.
uWSGI



About wsgi.py file Django environment
Here Insert Picture Description
on the map is Django environment wsgi.pyfile.
.
The main deployment platform Django is WSGI, Python standard for Web servers and applications.
.
Django's startproject management command to set up a simple default WSGI settings can be based on demand for our project adjustment, and indicate any WSGI compliant application server to use.
.
applicationusing WSGI deployment of key concepts is an application server for communicating with a code that applicationcan be called, it is usually accessible server Python module named as applicationproviding the object.
.
startprojectcommand created include such applicationfiles can be called:
<project_name>/wsgi.pyit was Django development server deployment and production use WSGI, WSGI server to obtain its configuration applicationpath can be invoked. Django built servers, i.e. runservercommand from WSGI_APPLICATIONthe reading it is provided.

Why Nginx, uWSGI
.
First, nginx is an external service interface, an external browser via url to access nginx.
.
Then, nginx receives the http request sent by the browser, the packet parsing and analyzing the url. If it is a static file requests access to a static file directory user to nginx configuration, direct return static file requested by the user, if not a static file requests (ie, dynamic request), then nginx will forward the request to uwsgi, uwsgi a request is received after the packet processing into a form that can receive wsgi, and sent wsgi. The wsgi a file request to invoke an application or a file in a function, the return value of the last processed to wsgi again, the return value wsgi package, packaged into a format which can be received uwsgi, receiving uwsgi wsgi send a request and forward it to nginx, nginx will eventually return value back to the browser.
.
Finally, we know that the first stage of nginx is not necessary, uwsgi can complete the entire process and interact with the browser, but to Taking into account the following three cases.
.
1.安全问题
can not be directly accessed by the browser, but by nginx, nginx only develop an interface.
uwsgi itself is a network interface, so that operation and maintenance personnel with security restrictions in the nginx, saver as you can reach.
.
2.负载均衡问题
a uwsgi it might not be enough, even if more work is not open, after all, a machine cpu and memory is limited.
the use nginx agent, a nginx proxy multiple uwsgi can complete uwsgi load balancing.
.
3.静态文件问题
By Django or uwsgi be responsible for handling static files is very wasteful behavior, their own processing of the file is not as nginx, so the entire process is completed static files directly from nginx, access to static files completely and go through their uwsgi logic behind.

nginx official website: HTTP: //nginx.org/en/
nginx introduction to uwsgi modules: HTTP: //nginx.org/en/docs/http/ngx_http_uwsgi_module.html
***

The following will Nginx, the relationship between the WSGI, uwsgi, uWSGI, Django sort out.
.
--------- ⬇️
wsgi
full name of the web server gateway interface, wsgi not a server, nor Python module, but a communication protocol
which is used to describe how to communicate with the web server web file application.
running on a web frame wsgi there Bottle, the Flask, the Django.
.
uwsgi
and wsgi as the communication protocol, the protocol uWSGI separate server, transmitting information for defining type.
.
uWSGI
is a web server, implements WSGI protocol, uwsgi agreement.
.
Nginx
web server, more secure and better deal with static resources, caching capabilities, load balancing.
strong performance of nginx, with my WSGI server will be more secure, performance is guaranteed.
.
Django
advanced Python framework for rapid development, web development to solve most of the problems, programmers can focus on business logic, disorderly re-create the wheel.
--------- ⬆️
.
logic FIG:
Here Insert Picture Description
--------- ⬇️
web服务器
conventional C / S architecture, the request is process:
client> server
server> client
server is: 1. 2. the process receives a request to return a request response 3
.
web框架层
the HT TP dynamic web data to the frame, e.g. MTV Django follow mode process request.
Url locate resources using the HTTP protocol, the urls.py views to the view route request processing, and then returns a result, complete a request.
Web users only need to process the frame to the business logic.
--------- ⬆️
.
If a communication into a "dialogue" process:
Nginx: "WSGI the Hello, I have just received a request, the next you're ready, then let Django handle it."
WSGI: "good, Nginx, I immediately set environment variables, and then request to Django. "
Django:" Thank you WSGI, I'll give you processed the request in response to the results. "
WSGI:" well, I'm waiting. "
Django:" get it, the trouble WSGI response results passed to Nginx. "
WSGI:" Very good Nginx, please respond to the results of a good income, have been delivered to you as requested. "
Nginx:." Okay, I'll put the results in response to the customer and pleasant cooperation "

***

Installation uWSGI

Installation uWSGI

# 进入虚拟环境,安装uWSGI
(venv) [root@master ~]# pip3.6 install uwsgi

# 检查uWSGI版本
(venv) [root@master ~]# uwsgi --version
2.0.17.1

# 检查uWSGI Python版本
(venv) [root@master ~]# uwsgi --python-version
3.6.7

Run a simple uWSGI

test.py file as follows:

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

Run the following command:

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

"""参数详解:
--http :8000  -> 使用http协议,端口8000
--wsgi-file test.py  -> 加载test.py文件
"""

After the run, can be accessed from the browser:
Here Insert Picture Description
***

uWSGI run Django environment
.
----------------------------------
run Django environment command

# 在项目根目录下执行如下命令
uwsgi --http :8000 --module project.wsgi

"""参数详解:
--http :8000  -> 使用http协议,端口8000
----module  -> 加载project项目下的wsgi模块
"""

.
----------------------------------
使用脚本运行Django环境
.
uWSGI支持inixml等多种配置方式.
这里将以ini为例,在/etc/目录下新建uwsgi_nginx.ini配置文件,如下:

# 项目配置文件
[uwsgi]

# 项目的绝对路径 定位到第一层
chdir = /root/project

# 指定项目的wsgi文件路径(从项目的根路径开始)
module = project.wsgi

# 指定虚拟解释器的第一层路径
home = /root/Envs/project

# 指定通过uwsgi启动多少个进程,默认2个
processes = 4

# 如果你已经配置了nginx,请使用这个socket连接
socket = 127.0.0.1:9999

# 如果你没有配置nginx,想通过uwsgi直接启动web服务,请使用这个http连接,指明http协议
# http = 127.0.0.1:9999

# 结合上面的 http 与 socket 配置项,都可以访问
http-socket 0.0.0.0:9999

# 在退出/重启uwsgi环境后清空环境变量
vacuum = true

指定配置文件启动命令:

uwsgi --ini /etc/uwsgi_nginx.ini

uWSGI热加载Python程序
.
在启动命令的后面加上--py-autoreload=1即可

# 命令启动
uwsgi --http :8000 --module mysite.wsgi --py-autoreload=1

# 配置文件启动
uwsgi --ini uwsgi.ini --py-autoreload=1

此时修改Django代码,uWSGI会自动加载Django程序,页面生效.
***

配置Nginx结合uWSGI

这里我们只讲解Nginx配置文件部分

worker_processes 1;
events {
    worker_connections 1024;
}
http {
    include mime.types;
    default_type application/octet-stream;
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    access_log logs/access.log  main;
    sendfile        on; 
    keepalive_timeout  65;   
    # 负载集群
    upstream load {
         server 192.168.1.100:9999;
         server 192.168.1.200:9999;
         server 192.168.1.300:9999;
    }
    server {
        listen 80; 
        server_name 192.168.43.149;
        location / { 
            # nginx自带的ngx_http_uwsgi_module模块,起到nginx和uwsgi交互的作用
            # 通过uwsgi_pass指定服务器地址和协议,将动态请求转发给uwsgi处理
            uwsgi_pass load;  # load是上面定义的负载集群
            # 指定uwsgi_params
            include /usr/local/nginx1.12/conf/uwsgi_params;
        }   
        # nginx处理静态页面资源
        location /static {
            alias /data/static/;
        }   
        # nginx处理媒体资源
        location /media {
            alias/data/media/;
        }   
    }   
} 

配置完后重启Nginx,即可实现其功能.
***

supervisor

supervisor是基于Python的任务管理工具,用于自动运行各种后台任务。当然我们也能直接使用Linux的nohup命令是任务自动后台运行,但如果要重启任务,就得手动去kill掉任务进程。这样很繁琐,而且一旦程序错误导致进程退出的话,系统也无法自动重载任务。

下载

# 由于supervisor在python3下无法使用,因此只能用python2去下载
yum install python-setuptools
easy_install supervisor

通过下面的命令生成supervisor的配置文件

echo_supervisord_conf > /etc/supervisord.conf

然后在/etc/supervisord.conf末尾添加如下代码

[program:django_test]  # [program:项目名称]
command=/root/Envs/djang1.11.11/bin/uwsgi --ini /root/django_test/uwsgi.ini  
# 程序启动命令

autostart=true  
# 在supervisord启动的时候也自动启动,可使uWSGI程序被杀掉后自动运行


# 这里我们只使用到了上面两个参数⬆️


# startsecs=10  
# 启动10秒后没有异常退出,就表示进程正常启动了,默认为1秒

# autorestart=true  
# 程序退出后自动重启,可选值有:[unexpected,true,false],默认为unexpected,表示进程被意外杀死后才重启

# startretries=3  
# 启动失败自动重试次数,默认是3

# user=django1.11.11  
# 用哪个用户启动进程,默认为root

# priority=999  
# 进程启动优先级,默认999,值小的优先启动

# redirect_stderr=true  
# 把stderr重定向到stdout,默认false

# stdout_logfile_maxbytes=20MB  
# stdout 日志文件大小,默认50MB

# stdout_logfile_backups = 20   
# stdout 日志文件备份数,默认是10

# stdout  
# 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录(supervisord 会自动创建日志文件)

# stdout_logfile=/opt/apache-tomcat-8.0.35/logs/catalina.out

# stopasgroup=false  
# 默认为false,进程被杀死时,是否向这个进程组发送stop信号,包括子进程

# killasgroup=false  
# 默认为false,向进程组发送kill信号,包括子进程

其中command是结合virtualenv的命令和supervisor的精髓:

command=/root/Envs/djang1.11.11/bin/uwsgi --ini /root/django_test/uwsgi.ini

command=/root/Envs/djang1.11.11/bin/uwsgi --uwsgi 0.0.0.0:8000 --chdir /root/django_test --home=/root/venv --module django_test.wsgi
# --chdir:指定项目的根
# --home:指的是虚拟环境目录  
# --module:找到Django项目环境中的wsgi.py文件

启动supervisor

# 启动supervisor
supervisord -c /etc/supervisord.conf

# 重启my项目
supervisorctl -c /etc/supervisord.conf restart my

supervisorctl -c /etc/supervisord.conf [start|stop|restart] [program-name|all]

重新加载supervisor

supervisorctl update
# 更新新的配置到supervisord 

supervisorctl reload
# 重新启动配置中的所有程序

supervisorctl start program_name
# 启动某个进程(program_name=你配置中写的程序名称)

supervisorctl
# 查看正在守候的进程

pervisorctl stop program_name
# 停止某一进程 (program_name=你配置中写的程序名称)

supervisorctl restart program_name
# 重启某一进程 (program_name=你配置中写的程序名称)

supervisorctl stop all
# 停止全部进程


# 注意:显示用stop停止掉的进程,用reload或者update都不会自动重启。

Django静态文件与Nginx配置

mysite/settings.py

# 此参数会将将STATICFILES_DIRS中所有文件夹中的文件,以及各app中static中的文件都复制到指定的路径下
STATIC_ROOT='/data/static'

STATIC_URL='/static'
STATICFILES_DIRS=[
    os.path.join(BASE_DIR, 'static'),
]

配置完毕后,运行命令:

python3.6 manage.py collectstatic

The above command will collect all our projects all the static files and save to the specified path under STATIC_ROOT
these documents are put together for a time such as nginx deployment of more convenient.
***
References: https: // uwsgi -docs-zh.readthedocs.io/zh_CN/latest/tutorials/Django_and_nginx.html

Guess you like

Origin www.cnblogs.com/gqy02/p/11309590.html