web框架巡礼之django

django

安装django

pip install django==1.11

hello world程序

创建helloworld工程:
django-admin startproject HelloWorld

得到的目录树为:
.
├── HelloWorld
│ ├── init.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py

在HelloWorld/HelloWorld下新建view.py,写hello函数:

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world ! ")

在HelloWorld/HelloWorld/urls.py里配置url与hello函数的关联:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/', view.hello),
]

为了保证其他机器能访问到我的服务,还要设置setting.py里的ALLOWED_HOSTS为本机ip:
ALLOWED_HOSTS = [‘192.168.199.245’]

最后,执行服务:
python manage.py runserver 0.0.0.0:8000

在另一台机器上使用http://xx.xx.xx.xx:8000访问即可得到Hello World页面。

增加日志

在setting.py文件里增加:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '[%(asctime)s] [%(levelname)s] %(message)s'
        },
    },
    'handlers': {
        'console':{
            'level':'INFO',
            'class':'logging.StreamHandler',
            'formatter': 'verbose'
        },
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': 'logs/django.log',
            'formatter': 'verbose'
        },
        'email': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html' : True,
        }
    },
    'loggers': {
        'django': {
            'handlers': ['console', 'file', 'email'],
            'level': 'INFO',
            'propagate': True,
        },
    },
}

代码里这样访问:
import logging
logger = logging.getLogger(‘django’)
logger.info(‘hello_tmpl called’)

django的一些使用细节

使用的模板引擎

从setting.py里可以看到,是:

'BACKEND': 'django.template.backends.django.DjangoTemplates',

也可改成jinja2。

热插拔特性

django里修改了Python文件是可以立刻生效的,所以调试很方便。

render输出原始文本

render会对替换文本做转义,如要禁止转义,可在模板里加上safe过滤器:

<html>
<head>
</head>
<body>
    {{content|safe}}
</body>
</html>

django+nginx

前面使用的是django自带的webserver,只能用于测试,生产环境要改为使用nginx。
nginx不能直连django,中间必须经过wsgi网关做请求转发。

wsgi和uwsgi都是web server和web framework之间的通信协议。端到端的流程应该是这个样子:

the web client <-> the web server <-> the socket <-> uwsgi <-> Django

nginx就是图中的web server。

uWSGI(注意大小写!)是一个web server+gateway的混合体,它实现了wsgi、uwsgi和http协议,
相当于上图的:
the web server <-> the socket <-> uwsgi

所以,uWSGI是有多种用途的,即可做web server也可做wsgi网关。

我们可以直接把uWSGI作为web server来启动django工程:
uwsgi –http :8000 –chdir /home/uniquelip/study/web/django/HelloWorld/ -w HelloWorld.wsgi –static-map=/static=static
此时,从其他机器上用http://xx.xx.xx.xx:8000访问可得到Hello World页面,跟用apache访问的效果一样。
【注意】-w参数HelloWorld.wsgi的含义,.号代表一层目录,所以HelloWorld.wsgi指的是django工程里的
HelloWorld/wsgi.py文件!

但uWSGI作为web server毕竟不像nginx那样具备工业级别的稳定性和效率,所以一般还是用nginx做web server,而只是用uWSGI做wsgi网关,这时候uWSGI往往是内网接口,而nginx是外网公共接口。在有多个uWSGI的情况下,nginx还可兼做负载均衡之用。

配置uwsgi

uwsgi.ini:

[uwsgi]
socket=127.0.0.1:9090
chdir=/home/uniquelip/study/web/django/HelloWorld/
module=HelloWorld.wsgi
master=true
processes=2
threads=2
max-requests=2000
chmod-socket=664
vacuum=true
daemonize=/home/uniquelip/study/web/django/HelloWorld/logs/uwsgi.log

启动uwsgi:
uwsgi –ini /home/uniquelip/study/web/django/HelloWorld/uwsgi.ini

停掉uwsgi:
sudo killall -9 uwsgi

配置nginx

nginx_hello.conf:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    server {
            listen 80;
            server_name  _;
            charset  utf-8;

            access_log /home/uniquelip/study/web/django/HelloWorld/logs/nginx/access.log;
            error_log /home/uniquelip/study/web/django/HelloWorld/logs/nginx/error.log;

            location / {
              include /etc/nginx/uwsgi_params;
              uwsgi_pass 127.0.0.1:9090;
            } 
    }

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    #include /etc/nginx/conf.d/*.conf;
    #include /etc/nginx/sites-enabled/*;
}

启动nginx:
sudo nginx -c /home/uniquelip/study/web/django/HelloWorld/nginx_hello.conf &

停掉nginx:
找到nginx master process的ID:
ps -ef|grep nginx
然后,优雅的停掉nginx:
sudo kill -QUIT pid

django+nginx联合工作的原理

nginx由master进程+worker进程组成,master只负责nginx自身的管理,worker负责业务,包括处理网络连接、从socket读取数据及向socket写入数据。
worker进程可以有多个,多个worker进程间是平等的,某个时刻只能有一个worker监听listen fd,并接受新连接,这种互斥是通过进程间锁来实现的。不过,nginx使用的是try_lock而非lock方式,try_lock只是一条CAS指令(参看我对pthread库的分析文章),开销很小。
worker进程接受新连接后,会得到一个普通fd,向epoll机制注册该fd的读事件,可以获得来自对端的http请求。接下来,nginx会根据conf文件里指定的规则将http请求重新包装,并转发给相应的模块去处理,比如下面的规则:

        location / {
              include /etc/nginx/uwsgi_params;
              uwsgi_pass 127.0.0.1:9090;
            } 

会指导nginx将请求转发给uWSGI网关。
uWSGI采用了跟nginx类似的设计,也是master进程+多个worker进程组成,worker进程负责接受连接、处理wsgi请求。当一个wsgi请求到达时,uWSGI会使用一个wsgi_app来处理,每个app内部持有一个python解释器(可新建也可共用一个全局解释器,视uwsgi的配置参数而定),由python解释器来调用django应用。在调用django应用的过程中,要始终持有python GIL,因为一个进程一个时刻只能有一个python解释器在执行代码(称之为current thread state)。所以,django应用其实是运行在uWSGI的进程中的。

猜你喜欢

转载自blog.csdn.net/tlxamulet/article/details/80342725