Django中的request里面到底有些啥?

本文转载自:http://www.cnblogs.com/MnCu8261/p/5871085.html

最近做在线学习网站的用户修改头像的功能,使用一个表单上传,在后端接收数据的时候,不止是接收request.POST,还接收了request.FILE,后面这个里面存放的是文件类的信息。

那么request中到底有些什么,不同类型的数据都在什么里面呢?


Django 使用Request 对象和Response 对象在系统间传递状态。

当请求一个页面时,Django会建立一个包含请求元数据的 HttpRequest 对象。 当Django 加载对应的视图时,HttpRequest 对象将作为视图函数的第一个参数。每个视图会返回一个HttpResponse 对象。

本文档对HttpRequest 和HttpResponse 对象的API 进行说明,这些API 定义在django.http 模块中。

举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class LoginView(View):
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
user = authenticate(username = user_name, password = pass_word)
if user is not None:
if user.is_active:
login(request, user)
return render(request, "index.html")
else:
return render(request, "login.html", {"msg": "用户未激活"})
else:
return render(request, "login.html", {"msg":"用户名或者密码错误"})
else:
return render(request, "login.html", { "login_form": login_form})

上面这段代码就是一个简单的登录的视图函数,get和post函数的第一个(目前看就一个)参数就是request,也就是上面说到的HttpRequest类型的对象。


Request

我们知道当URLconf文件匹配到用户输入的路径后,会调用对应的view函数,并将 HttpRequest对象作为第一个参数传入该函数。

我们来看一看这个HttpRequest对象有哪些属性或者方法:

属性:

1.HttpRequest.scheme

这是请求的协议,一般是http或者https,字符串格式的。

1
scheme = {str}'http'

2 HttpRequest.body

http请求的主体,二进制格式。

1
body = {bytes}b''

3 HttpRequest.path

所请求页面的完整路径(但不包括协议以及域名),也就是相对于网站根目录的路径。

1
path={str}'/users/mycourse/'

4 HttpRequest.path_info

获取具有 URL 扩展名的资源的附加路径信息。相对于HttpRequest.path,使用该方法便于移植。

1
path_info={str}'/users/mycourse/'

if the WSGIScriptAlias for your application is set to “/minfo”, then path might be “/minfo/music/bands/the_beatles/“ and path_info would be “/music/bands/the_beatles/“.

5 HttpRequest.method

获取该请求的方法,比如: GET POST ………

6 HttpRequest.encoding

获取请求中表单提交数据的编码。

7 HttpRequest.content_type

获取请求的MIME类型(从CONTENT_TYPE头部中获取),django1.10的新特性。

8 HttpRequest.content_params

获取CONTENT_TYPE中的键值对参数,并以字典的方式表示,django1.10的新特性。

9 HttpRequest.GET

返回一个 querydict 对象(类似于字典,本文最后有querydict的介绍),该对象包含了所有的HTTP GET参数

1
2
3
4
__len__ = {int} 0
_encoding = {str} 'utf-8'
_mutable = {bool} False
encoding = {str} 'utf-8'

10 HttpRequest.POST

返回一个 querydict ,该对象包含了所有的HTTP POST参数,通过表单上传的所有 字符 都会保存在该属性中。

1
2
3
4
__len__ = {int} 0
_encoding = {str} 'utf-8'
_mutable = {bool} False
encoding = {str} 'utf-8'

11 HttpRequest.COOKIES  

返回一个包含了所有cookies的字典。

12 HttpRequest.FILES   

返回一个包含了所有的上传文件的 querydict 对象。通过表单所上传的所有文件 都会保存在该属性中。

1
2

   key的值是input标签中name属性的值,value的值是一个UploadedFile对象

13 HttpRequest.META

返回一个包含了所有http头部信息的字典

举了个例子,内容比较多,详情见附录中的代码。

14 HttpRequest.session

中间件属性

15 HttpRequest.site  

中间件属性

16 HttpRequest.user  

中间件属性,表示当前登录的用户。


HttpRequest.user实际上是由一个定义在django.contrib.auth.models 中的 user model类所创建的对象。

该类有许多字段,属性和方法。列举几个常用的: 获取更详细信息–>官方文档

1 字段:

username 用户名

first_name

last_name

email

password

groups

user_permissions,

is_staff 布尔值,标明用户是否可以访问admin页面

is_superuser

last_login 上一次登陆时间

date_joined 用户创建时间

2 属性

is_authenticated

布尔值,标志着用户是否已认证。在django1.10之前,没有该属性,但有与该属性同名的方法。

3 方法

1 HttpRequest.user.get_username()

注意:方法的圆括号在templates标签中必需省略!!因为我们要获得的是这个函数得到的值,而不能调用这个方法。

获取username。尽量使用该方法来代替使用username字段

2 HttpRequest.user.get_full_name()

注意:方法的圆括号在templates标签中必需省略!!

获取first_name和last_name

3 HttpRequest.user.short_name()

注意:方法的圆括号在templates标签中必需省略!!

获取first_name

4 HttpRequest.user.set_password(raw_password)

注意:该方法无法在template标签中使用!!

设置密码

5 HttpRequest.user.check_password(raw_password)

注意:该方法无法在template标签中使用!!

如果raw_password与用户密码相等,则返回True

方法:

1 HttpRequest.get_host()

返回请求的源主机。example: 127.0.0.1:8000

2 HttpRequest.get_port()

获得端口号,比如8000. 这是django1.9的新特性。

3 HttpRequest.get_full_path()

返回完整路径,并包括附加的查询信息。

example: “/music/bands/the_beatles/?print=true”

4 HttpRequest.bulid_absolute_uri(location)

返回location的绝对uri,location默认为request.get_full_path()。

Example: “https://example.com/music/bands/the_beatles/?print=true


QueryDict

QueryDict是一个类似于Python中字典的一种对象,他是Python中字典的子类,所以继承了字典的所有方法,(那么字典有什么常用的方法呢?)

当然QueryDict对字典的某些方法进行了加工,并补充了一些独特的方法。这里列出部分方法。详情请看: 官方文档

1 QueryDict.get(key,default=None)

返回key所对应的value,若key不存在,则返回default的值

2 QueryDict.update(other_dict)

更新

3 QueryDict.values()

列出所有的值

4 QueryDict.items()

列出所有的键值对,若一个key有多个值,只显示最后一个值。

5 QueryDict.pop(key)

删除某个键值对

6 QueryDict.getlist(key)

根据输入的key返回一个Python中的list

7 QueryDict.dict()

返回QueryDict的字典的表现形式


附录:request中的Meta内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
__len__ = {int} 127
'CLUTTER_IM_MODULE' (140112391888232) = {str} 'xim'
'COMPIZ_BIN_PATH' (140112391908336) = {str} '/usr/bin/'
'COMPIZ_CONFIG_PROFILE' (140112391914096) = {str} 'ubuntu-lowgfx'
'CONTENT_LENGTH' (140112460080688) = {str} ''
'CONTENT_TYPE' (140112460133488) = {str} 'text/plain'
'CSRF_COOKIE' (140112395828464) = {str} 'AmLkhr3sDwSswAuAO7dY7wobUVP1qKsm'
'DBUS_SESSION_BUS_ADDRESS' (140112391859696) = {str} 'unix:abstract=/tmp/dbus-92hKQ2jrmm'
'DEFAULTS_PATH' (140112391918128) = {str} '/usr/share/gconf/ubuntu.default.path'
'DESKTOP_SESSION' (140112391905392) = {str} 'ubuntu'
'DISPLAY' (140112391895280) = {str} ':0'
'DJANGO_SETTINGS_MODULE' (140112391887872) = {str} 'mymooc.settings'
'GATEWAY_INTERFACE' (140112460099424) = {str} 'CGI/1.1'
'GDMSESSION' (140112391917616) = {str} 'ubuntu'
'GDM_LANG' (140112391905456) = {str} 'en_US'
'GNOME_DESKTOP_SESSION_ID' (140112391859536) = {str} 'this-is-deprecated'
'GNOME_KEYRING_CONTROL' (140112391888592) = {str} ''
'GNOME_KEYRING_PID' (140112391888016) = {str} ''
'GPG_AGENT_INFO' (140112391908080) = {str} '/home/peter/.gnupg/S.gpg-agent:0:1'
'GTK2_MODULES' (140112391918000) = {str} 'overlay-scrollbar'
'GTK_IM_MODULE' (140112391908208) = {str} 'fcitx'
'GTK_MODULES' (140112391907248) = {str} 'gail:atk-bridge:unity-gtk-module'
'HOME' (140112391896904) = {str} '/root'
'HTTP_ACCEPT' (140112153031280) = {str} 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
'HTTP_ACCEPT_ENCODING' (140112446239992) = {str} 'gzip, deflate, sdch, br'
'HTTP_ACCEPT_LANGUAGE' (140112446241144) = {str} 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4'
'HTTP_CONNECTION' (140112108849200) = {str} 'keep-alive'
'HTTP_COOKIE' (140112108895792) = {str} 'sessionid=n58ij785n5lnv4k37vr73wfufkwo7fgp; csrftoken=AmLkhr3sDwSswAuAO7dY7wobUVP1qKsm'
'HTTP_HOST' (140112108838512) = {str} 'localhost:8000'
'HTTP_REFERER' (140112153032688) = {str} 'http://localhost:8000/users/userinfo/'
'HTTP_UPGRADE_INSECURE_REQUESTS' (140112152861712) = {str} '1'
'HTTP_USER_AGENT' (140112145171376) = {str} 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
'IDE_PROJECT_ROOTS' (140112391888088) = {str} '/home/peter/mymooc'
'IM_CONFIG_PHASE' (140112391908784) = {str} '1'
'INSTANCE' (140112391906800) = {str} ''
'IPYTHONENABLE' (140112391907184) = {str} 'True'
'JOB' (140112391895056) = {str} 'unity-settings-daemon'
'LANG' (140112391895784) = {str} 'en_US.UTF-8'
'LANGUAGE' (140112391908848) = {str} 'en_US'
'LC_ADDRESS' (140112391906416) = {str} 'zh_CN.UTF-8'
'LC_IDENTIFICATION' (140112391887800) = {str} 'zh_CN.UTF-8'
'LC_MEASUREMENT' (140112391906096) = {str} 'zh_CN.UTF-8'
'LC_MONETARY' (140112391907568) = {str} 'zh_CN.UTF-8'
'LC_NAME' (140112391896456) = {str} 'zh_CN.UTF-8'
'LC_NUMERIC' (140112391917872) = {str} 'zh_CN.UTF-8'
'LC_PAPER' (140112391907888) = {str} 'zh_CN.UTF-8'
'LC_TELEPHONE' (140112391905904) = {str} 'zh_CN.UTF-8'
'LC_TIME' (140112391925864) = {str} 'zh_CN.UTF-8'
'LD_LIBRARY_PATH' (140112391918384) = {str} './PyCharm/pycharm-2017.1/bin:'
'LESSCLOSE' (140112391917744) = {str} '/usr/bin/lesspipe %s %s'
'LESSOPEN' (140112391908528) = {str} '| /usr/bin/lesspipe %s'
'LIBGL_ALWAYS_SOFTWARE' (140112391914168) = {str} '1'
'LIBRARY_ROOTS' (140112391906864) = {str} '/home/peter/mymooc/mymoocvenv/lib/python3.5:/home/peter/mymooc/mymoocvenv/lib/python3.5/plat-x86_64-linux-gnu:/home/peter/mymooc/mymoocvenv/lib/python3.5/lib-dynload:/usr/lib/python3.5:/usr/lib/python3.5/plat-x86_64-linux-gnu:/home/peter/mymooc/mymoocvenv
'LOGNAME' (140112391896288) = {str} 'root'
'LS_COLORS' (140112391906672) = {str} 'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;3
'MAIL' (140112391895224) = {str} '/var/mail/root'
'MANDATORY_PATH' (140112391906352) = {str} '/usr/share/gconf/ubuntu.mandatory.path'
'NLSPATH' (140112391896624) = {str} '/usr/dt/lib/nls/msg/%L/%N.cat'
'PATH' (140112391897016) = {str} '/home/peter/mymooc/mymoocvenv/bin:/home/peter/mymooc/mymoocvenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games'
'PATH_INFO' (140112460132912) = {str} '/users/mycourse/'
'PS1' (140112391895616) = {str} '(mymoocvenv) '
'PWD' (140112391895840) = {str} '/home/peter/mymooc'
'PYCHARM_HOSTED' (140112391909040) = {str} '1'
'PYTHONDONTWRITEBYTECODE' (140112391888808) = {str} '1'
'PYTHONIOENCODING' (140112391887728) = {str} 'UTF-8'
'PYTHONPATH' (140112391908016) = {str} '/home/peter/mymooc:/home/peter/mymooc/apps:/home/peter/mymooc/media:/home/peter/PyCharm/pycharm-2017.1/helpers/pydev'
'PYTHONUNBUFFERED' (140112391888304) = {str} '1'
'QT4_IM_MODULE' (140112391908592) = {str} 'fcitx'
'QT_ACCESSIBILITY' (140112391913664) = {str} '1'
'QT_IM_MODULE' (140112391906928) = {str} 'fcitx'
'QT_LINUX_ACCESSIBILITY_ALWAYS_ON' (140112391902464) = {str} '1'
'QT_QPA_PLATFORMTHEME' (140112391888376) = {str} 'appmenu-qt5'
'QUERY_STRING' (140112460133104) = {str} ''
'REMOTE_ADDR' (140112460133168) = {str} '127.0.0.1'
'REMOTE_HOST' (140112460133936) = {str} ''
'REQUEST_METHOD' (140112460080624) = {str} 'GET'
'RUN_MAIN' (140112391908976) = {str} 'true'
'SCRIPT_NAME' (140112460133040) = {str} ''
'SERVER_NAME' (140112460132720) = {str} 'localhost'
'SERVER_PORT' (140112460132848) = {str} '8000'
'SERVER_PROTOCOL' (140112460132784) = {str} 'HTTP/1.1'
'SERVER_SOFTWARE' (140112460132656) = {str} 'WSGIServer/0.2'
'SESSION' (140112391896512) = {str} 'ubuntu'
'SESSIONTYPE' (140112391909168) = {str} 'gnome-session'
'SESSION_MANAGER' (140112391909104) = {str} 'local/peter-VirtualBox:@/tmp/.ICE-unix/1997,unix/peter-VirtualBox:/tmp/.ICE-unix/1997'
'SHELL' (140112391895112) = {str} '/bin/bash'
'SHLVL' (140112391895448) = {str} '2'
'SSH_AUTH_SOCK' (140112391907504) = {str} '/run/user/1000/keyring/ssh'
'TERM' (140112391925976) = {str} 'xterm-256color'
'TZ' (140112391895672) = {str} 'Asia/Shanghai'
'UPSTART_EVENTS' (140112391905520) = {str} 'xsession started'
'UPSTART_INSTANCE' (140112391887656) = {str} ''
'UPSTART_JOB' (140112391907760) = {str} 'unity7'
'UPSTART_SESSION' (140112391905776) = {str} 'unix:abstract=/com/ubuntu/upstart-session/1000/1756'
'USER' (140112391896792) = {str} 'root'
'VIRTUALENVWRAPPER_HOOK_DIR' (140112391858976) = {str} '/home/peter/.virtualenvs'
'VIRTUALENVWRAPPER_PROJECT_FILENAME' (140112391902552) = {str} '.project'
'VIRTUALENVWRAPPER_SCRIPT' (140112391859296) = {str} '/usr/local/bin/virtualenvwrapper.sh'
'VIRTUALENVWRAPPER_WORKON_CD' (140112391859456) = {str} '1'
'VIRTUAL_ENV' (140112391905648) = {str} '/home/peter/mymooc/mymoocvenv'
'VTE_VERSION' (140112391908144) = {str} '4205'
'WINDOWID' (140112391907312) = {str} '69206026'
'WORKON_HOME' (140112391908912) = {str} '/home/peter/.virtualenvs'
'XAUTHORITY' (140112391907824) = {str} '/home/peter/.Xauthority'
'XDG_CONFIG_DIRS' (140112391918320) = {str} '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg'
'XDG_CURRENT_DESKTOP' (140112391913592) = {str} 'Unity'
'XDG_DATA_DIRS' (140112391908464) = {str} '/usr/share/ubuntu:/usr/share/gnome:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop'
'XDG_GREETER_DATA_DIR' (140112391913808) = {str} '/var/lib/lightdm-data/peter'
'XDG_MENU_PREFIX' (140112391917680) = {str} 'gnome-'
'XDG_RUNTIME_DIR' (140112391908656) = {str} '/run/user/1000'
'XDG_SEAT' (140112391918064) = {str} 'seat0'
'XDG_SEAT_PATH' (140112391908272) = {str} '/org/freedesktop/DisplayManager/Seat0'
'XDG_SESSION_DESKTOP' (140112391888736) = {str} 'ubuntu'
'XDG_SESSION_ID' (140112391906736) = {str} 'c2'
'XDG_SESSION_PATH' (140112391913880) = {str} '/org/freedesktop/DisplayManager/Session0'
'XDG_SESSION_TYPE' (140112391914024) = {str} 'x11'
'XDG_VTNR' (140112391907120) = {str} '7'
'XFILESEARCHPATH' (140112391906032) = {str} '/usr/dt/app-defaults/%L/Dt'
'XMODIFIERS' (140112391906544) = {str} '@im=fcitx'
'_' (140112498935152) = {str} './PyCharm/pycharm-2017.1/bin/pycharm.sh'
'wsgi.errors' (140112391813552) = {TextIOWrapper} <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>
'wsgi.file_wrapper' (140112391778000) = {type} <class 'wsgiref.util.FileWrapper'>
'wsgi.input' (140112391813488) = {BufferedReader} <_io.BufferedReader name=5>
'wsgi.multiprocess' (140112391777928) = {bool} False
'wsgi.multithread' (140112391777856) = {bool} True
'wsgi.run_once' (140112391813680) = {bool} False
'wsgi.url_scheme' (140112391813744) = {str} 'http'
'wsgi.version' (140112391813616) = {tuple} <class 'tuple'>: (1, 0)