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)设置cookieHttpResponse的子类
- 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 启动和请求的更多相关文章
- Django跨域请求之JSONP和CORS
现在来新建一个Django项目server01,url配置为 url(r'^getData.html$',views.get_data) 其对应的视图函数为get_data: from django. ...
- django启动入口源码分析
manage.py是启动入口,在里面调用execute_from_command_line(sys.argv)方法 def execute_from_command_line(argv=None): ...
- 玩转Django的POST请求 CSRF
玩转Django的POST请求 CSRF 不少麻油们玩django都会碰到这个问题,POST请求莫名其妙的返回 403 foribidden,希望这篇博文能解答所有问题 三种方法 To enable ...
- 如何使用Django 启动命令行及执行脚本
使用django启动命令行和脚本,可以方便的使用django框架做开发,例如,数据库的操作等. 下面分别介绍使用方法. django shell的启动 启动命令: $/data/python-virt ...
- Spring mvc 启动 和 请求分发
Spring mvc 启动 和 请求分发 启动加载: abstract class HttpServletBean extends HttpServlet void init() initServle ...
- Django启动
Django启动 (一)CMD中创建启动: 1.配置好django-admin.exe环境变量,切换到项目文件夹路径 切换磁盘:>>>E: 显示文件列表:>>>di ...
- Django—跨域请求(jsonp)
同源策略 如果两个页面的协议,端口(如果有指定)和域名都相同,则两个页面具有相同的源. 示例:两个Django demo demo1 url.py url(r'^demo1/',demo1), vie ...
- gunicorn结合django启动后台线程
preload 为True的情况下,会将辅助线程或者进程开在master里,加重master的负担(master最好只是用来负责监听worker进程) django应用的gunicorn示例:只在主线 ...
- django中间件(获取请求ip)
def simple_middleware(get_response): # 此处编写的代码仅在Django第一次配置和初始化的时候执行一次. print('1----django启动了') def ...
随机推荐
- C# -- 扩展方法的应用(Extension Methods)
当你有下面这样一个需求的时候,扩展方法就会起到作用:在项目中,类A需要添加功能,我们想到的就是在类A中添加公共方法,这个显而易见肯定可以,但是由于某种原因,你不能修改类A本身的代码,但是确实又需要增加 ...
- Hive 12、Hive优化
要点:优化时,把hive sql当做map reduce程序来读,会有意想不到的惊喜. 理解hadoop的核心能力,是hive优化的根本. 长期观察hadoop处理数据的过程,有几个显著的特征: 1. ...
- iOS FMDB中的使用
n使用事务 [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { [db executeUpdate:@"INSERT INTO ...
- Eat Candy(暴力,水)
Eat Candy Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 8 Solved: 6[Submit][Status][Web Board] Des ...
- 在Docker中运行torch版的neural style
相关的代码都在Github上,请参见我的Github,https://github.com/lijingpeng/deep-learning-notes 敬请多多关注哈~~~ 在Docker中运行to ...
- SQLLoader6(一个或多个数据文件按条件导入不同的表)
测试一1.创建表: SQL), col2 )); 表已创建. SQL), col2 )); 表已创建. SQL> COMMIT; 提交完成. 2.数据文件:test.txt A A A B B ...
- css3 在线编辑工具 连兼容都写好了
http://www.css3maker.com/index.html
- JS中面向对象的,对象理解、构造函数、原型、原型链
6.1 理解对象 6.1.1 对象属性类型 ECMS属性有两种类型:数据属性和访问器属性 1 数据属性 [[configurable]] 表示能否通过Delete 删除属性从而从新定义属性,能否修改属 ...
- Android----------eclipse常用快捷键
类级操作:--------------------一个去包,一个导包------------------------------------ Ctrl+shift+O (不是零) 清除没用引用 ctr ...
- 你所不了解的css选择器补充
div p和div>p的区别 1.div p选择 <div> 元素内部的所有 <p> 元素 2.div>p选择父元素为 <div> 元素的所有 < ...