django 启动和请求


Django运行方式

  • 调试模式 直接 python manage.py runserver
python manage.py runserver
python manage.py runserver  0.0.0.0:80

 

  • web + uwsgi + django
    请求顺序:
    the web client <-> the web server <-> the socket <-> uwsgi <-> Django

     

下面具体说明如何实现:
参考:http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html

  • 安装uwsgi
pip install uwsgi

 

  • 创建测试文件
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pyversion:python3.5
# owner:fuzj
# Pw @ 2017-01-09 15:46:32

def application(env,start_response):
   start_response('200 OK',[('Content_Type','text/html')])
   return "Congraduation!!! uWSGI Testing OK!!!"

 

  • 运行
[root@test ~]# uwsgi --http :8000 --wsgi-file ./test.py
*** Starting uWSGI 2.0.14 (64bit) on [Mon Jan  9 18:08:23 2017] ***
compiled with version: 4.4.7 20120313 (Red Hat 4.4.7-17) on 09 January 2017 17:37:30
os: Linux-2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013
nodename: test.novalocal
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 4
current working directory: /root
detected binary path: /usr/local/python2.7/bin/uwsgi
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 30523
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :8000 fd 4
spawned uWSGI http 1 (pid: 2553)
uwsgi socket 0 bound to TCP address 127.0.0.1:47160 (port auto-assigned) fd 3
Python version: 2.7.11 (default, Dec 29 2016, 15:13:34)  [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)]
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0xd46800
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72768 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0xd46800 pid: 2552 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 2552, cores: 1)

 

  • 结果
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 0.0.0.0:6379                0.0.0.0:*                   LISTEN      1246/redis-server *
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      979/sshd
tcp        0      0 127.0.0.1:47160             0.0.0.0:*                   LISTEN      2552/uwsgi
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1228/master
tcp        0      0 0.0.0.0:8000                0.0.0.0:*                   LISTEN      2552/uwsgi
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      1130/mysqld
tcp        0      0 :::6379                     :::*                        LISTEN      1246/redis-server *
tcp        0      0 :::22                       :::*                        LISTEN      979/sshd
tcp        0      0 ::1:25                      :::*                        LISTEN      1228/master
[root@test core]# curl http://127.0.0.1:8000
Congraduation!!! uWSGI Testing OK!!![root@test core]#****

 

  • nginx + uwsgi + django

    • nginx 配置:

      server {
      listen       80;
      server_name  op.xywy.com;
      
      #charset koi8-r;
      
      access_log  logs/op.xywy.com-access.log  main;
      location ^~ /static {
          alias /usr/local/python2.7/lib/python2.7/site-packages/django/contrib/admin/static/;
      
          }
      location / {
          include  uwsgi_params;
          uwsgi_pass  127.0.0.1:8000;
      }
      
      }

       

    • uwsgi配置

    uwsgi 支持 .ini .xml 等格式的配置文件,。以ini为例

[uwsgi]
chdir=/data/eoms                #项目目录
module=eoms.wsgi:application    #uwsgi的模块
#env=DJANGO_SETTINGS_MODULE=eoms.settings.prod
master=True   #主进程
pidfile=/tmp/eoms.pid  
socket=127.0.0.1:8000 
processes=4     #子进程数量
max-requests=5000
vacuum=True    #退出、重启时清理文件
daemonize=/tmp/eoms.log  

 

启动nginx和uwsgi

/usr/local/nginx/sbin/nginx
uwsgi /data/eoms/uwsgi.ini

 

Django 处理请求

Django使用Request对象和Response对象在客户端和服务端传递状态,当客户端发起请求到django之后,Django会建立一个包含请求元数据的HttpRequest对象,所以,django的url对应的视图中,每个views函数中需将此httprequest作为参数传递进去,最后每个视图会讲处理的结果封装为Httpresponse对象

HttpRequest对象

HttpRequest 作为参数传递到views中,具有的相关属性如下:

  • request.scheme client 的请求协议 通常是http或者https
  • request.body 请求正文,通常post请求会将数据放入body中
  • request.path 请求uri。但是不包含host
  • request.path_info 获取具有 URL 扩展名的资源的附加路径信息。相对于HttpRequest.path,使用该方法便于移植 例如,如果应用的WSGIScriptAlias 设置为"/minfo",那么当path 是"/minfo/music/bands/the_beatles/" 时path_info 将是"/music/bands/the_beatles/"。
  • request.method 请求的方式,比如: GET POST .........
  • request.encoding 请求中表单提交数据的编码。
  • request.content_type 获取请求的MIME类型(从CONTENT_TYPE头部中获取) django1.10的新特性。
  • request.content_params 获取CONTENT_TYPE中的键值对参数,并以字典的方式表示,django1.10的新特性。
  • request.GET 返回一个 querydict 对象
  • request.POST 返回一个 querydict ,该对象包含了所有的HTTP POST参数,通过表单上传的所有 字符 都会保存在该属性中。
  • request.COOKIES 以字典形式返回header中cookie
  • request.FILES 以字典形式返回上传文件的对象,key的值是input标签中name属性的值,value的值是一个UploadedFile对象

  • request.META 以字典形式返回所有http头部信息

  • request.user 一个auth_user_model类型的对象,表示当前登录的用户,如果没有登录,user将设置为django.contrib.auth.models.AnonymousUser 的一个实例

  • request.session 当前会话的session

具有的相关方法如下:

  • request.get_host() 返回请求的源主机。example: 127.0.0.1:8000
  • request.get_port() django1.9的新特性。
  • request.get_full_path() 返回完整路径,并包括附加的查询信息。example: "/music/bands/the_beatles/?print=true"
  • request.bulid_absolute_uri(location) 返回location的绝对uri,location默认为request.get_full_path()。    Example: "https://example.com/music/bands/the_beatles/?print=true"   

HttpResponse对象

httpresponse 是视图返回的对象,由django.http模块定义。

属性:

  • HttpResponse.content 返回的具体内容,默认编码为header 中content_type,也可以在实例化的时候指定
  • HttpResponse.status_code 相应的http状态码
  • HttpResponse.streaming 用于中间件middleware区别对待流式response和常规response
  • HttpResponse.closed 关闭连接

方法:

HttpResponse.__init__(content='', content_type=None, status=200, reason=None, charset=None)
使用页面的内容(content)和content-type来实例化一个HttpResponse对象。

  • HttpResponse.__setitem__(header, value)
    由给定的首部名称和值设定相应的报文首部。 header 和 value 都应该是字符串类型。

  • HttpResponse.__delitem__(header)
    根据给定的首部名称来删除报文中的首部。如果对应的首部不存在将沉默地(不引发异常)失败。不区分大小写。

  • HttpResponse.__getitem__(header)
    根据首部名称返回其值。不区分大小写。

  • HttpResponse.has_header(header)
    通过检查首部中是否有给定的首部名称(不区分大小写),来返回True 或 False 。

  • HttpResponse.setdefault(header, value) 设置一个默认首部,除非该首部 header 已经存在了。

  • HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False) 设置cookie

  • HttpResponse的子类

    • HttpResponseRedirect 302临时重定向
    • HttpResponsePermanentRedirect 301 永久重定向
    • HttpResponseNotModified 304 没有任何改变
    • HttpResponseBadRequest 400 错误的请求
    • HttpResponseNotFound 404 请求对象不存在
    • HttpResponseForbidden 403 请求被拒绝
    • HttpResponseNotAllowed 405 请求的方式不允许
    • HttpResponseGone 410 请求的资源已被删除
    • HttpResponseServerError 500 服务内部错误
    • JsonResponse对象 JsonResponse可以直接将返回的对象序列化为json字符串

      JsonResponse.__init__(data, encoder=DjangoJSONEncoder, safe=True, **kwargs)
      它的第一个参数data,应该为一个dict 实例。如果safe 参数设置为False,它可以是任何可JSON 序列化的对象


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM