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 序列化的对象

django 启动和请求的更多相关文章

  1. Django跨域请求之JSONP和CORS

    现在来新建一个Django项目server01,url配置为 url(r'^getData.html$',views.get_data) 其对应的视图函数为get_data: from django. ...

  2. django启动入口源码分析

    manage.py是启动入口,在里面调用execute_from_command_line(sys.argv)方法 def execute_from_command_line(argv=None): ...

  3. 玩转Django的POST请求 CSRF

    玩转Django的POST请求 CSRF 不少麻油们玩django都会碰到这个问题,POST请求莫名其妙的返回 403 foribidden,希望这篇博文能解答所有问题 三种方法 To enable ...

  4. 如何使用Django 启动命令行及执行脚本

    使用django启动命令行和脚本,可以方便的使用django框架做开发,例如,数据库的操作等. 下面分别介绍使用方法. django shell的启动 启动命令: $/data/python-virt ...

  5. Spring mvc 启动 和 请求分发

    Spring mvc 启动 和 请求分发 启动加载: abstract class HttpServletBean extends HttpServlet void init() initServle ...

  6. Django启动

    Django启动 (一)CMD中创建启动: 1.配置好django-admin.exe环境变量,切换到项目文件夹路径 切换磁盘:>>>E: 显示文件列表:>>>di ...

  7. Django—跨域请求(jsonp)

    同源策略 如果两个页面的协议,端口(如果有指定)和域名都相同,则两个页面具有相同的源. 示例:两个Django demo demo1 url.py url(r'^demo1/',demo1), vie ...

  8. gunicorn结合django启动后台线程

    preload 为True的情况下,会将辅助线程或者进程开在master里,加重master的负担(master最好只是用来负责监听worker进程) django应用的gunicorn示例:只在主线 ...

  9. django中间件(获取请求ip)

    def simple_middleware(get_response): # 此处编写的代码仅在Django第一次配置和初始化的时候执行一次. print('1----django启动了') def ...

随机推荐

  1. 字符(汉子)转换为ASCII

    一般在jdk里面都会自包含一个官方提供的转换工具:native2ascii.exe 调用方法: 打开cmd界面,使用cd  C:\Program Files\Java\jdk1.6.0_39\bin命 ...

  2. Eclipse 里的 Classpath Variables M2_REPO 无法修改(maven)

      解决方法: 在C:\Documents and Settings\Administrator\.m2中放入setting.xml,并修改本地仓库为 <localRepository>D ...

  3. PHP你可能也会掉入的坑

    今天被人问: $var = 'test'; if (isset($var['somekey'])) { echo 'reach here!!!'; } 会不会输出'reach here!!!'? -- ...

  4. JAVA wait(), notify(),sleep具体解释

    在CSDN开了博客后,一直也没在上面公布过文章,直到前一段时间与一位前辈的对话,才发现技术博客的重要,立志要把CSDN的博客建好.但一直没有找到好的开篇的主题,今天再看JAVA线程相互排斥.同步的时候 ...

  5. BOOST 线程完全攻略 - 扩展 - 可被关闭的线程类

    本文假设读者已经基本了解boost线程库的使用方法. boost是个开源工程,线程这一块也在不断完善之中,到现在这个阶段,boost::thread仅仅实现了一个完美的技术框架,但是读者在实际使用中会 ...

  6. 导出word文档

    string id = Request["id"];            if (string.IsNullOrEmpty(id))            {           ...

  7. winform窗体中查找控件

    private RichTextBox FindControl()        { RichTextBox ret = null;            try            {       ...

  8. DOM生成&解析

    开篇注意,由于解析有可能有大文件非常耗时,建议另开一个线程解析也可以不开具体视情况而定     DOM生成 1.拿到Document的工厂实例化 DocumentBuilderFactory df = ...

  9. Android HttpClient框架get和post方式提交数据(非原创)

    1.fragment_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android& ...

  10. React react-ui-tree的使用

    公司需要做一个IDE,要做IDE当然少不了文件列表了.下面我就来展示一下刚刚研究的一个库. 下面是链接:https://react.rocks/example/react-ui-tree 至于如何导入 ...