views函数详解
本文对views内的URL处理函数及一些重点的功能函数进行详细讲解。
URL处理函数
在views中url处理函数通常和对用url名称差不多,特点是第一个参数都是request。后面如果有参数,值是url传过来的,我们在url部分已经讲过。函数内部就是具体的对模板模型等的操作了。下面我们具体说下这个request的作用。
首先,我们需要知道request来是怎么来的,其实request是HttpRequest的一个实例对象;当页面被访问的时候,也就是你在urls.py设定的匹配地址符合的时候;request就会被创建。然后,我们需要知道HttpRequest里面的属性以及方法都有那些。
属性:
1 HttpRequest.scheme 请求的协议,一般为http或者https,字符串格式(以下属性中若无特殊指明,均为字符串格式)
2 HttpRequest.body http请求的主体,二进制格式。
3 HttpRequest.path 所请求页面的完整路径(但不包括协议以及域名),也就是相对于网站根目录的路径。
4 HttpRequest.path_info 获取具有 URL 扩展名的资源的附加路径信息。相对于HttpRequest.path,使用该方法便于移植。
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参数
10 HttpRequest.POST 返回一个querydict ,该对象包含了所有的HTTP POST参数,通过表单上传的所有 字符 都会保存在该属性中。
11 HttpRequest.COOKIES 返回一个包含了所有cookies的字典。
12 HttpRequest.FILES 返回一个包含了所有的上传文件的 querydict 对象。通过表单所上传的所有文件都会保存在该属性中。key的值是input标签中name属性的值,value的值是一个UploadedFile对象
13 HttpRequest.META 返回一个包含了所有http头部信息的字典
CONTENT_LENGTH – The length of the request body (as a string).
CONTENT_TYPE – The MIME type of the request body.
HTTP_ACCEPT – Acceptable content types for the response.
HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
HTTP_HOST – The HTTP Host header sent by the client.
HTTP_REFERER – The referring page, if any.
HTTP_USER_AGENT – The client’s user-agent string.
QUERY_STRING – The query string, as a single (unparsed) string.
REMOTE_ADDR – The IP address of the client.
REMOTE_HOST – The hostname of the client.
REMOTE_USER – The user authenticated by the Web server, if any.
REQUEST_METHOD – A string such as "GET" or "POST".
SERVER_NAME – The hostname of the server.
SERVER_PORT –The port of the server (as a string).
14 HttpRequest.session 中间件属性
15 HttpRequest.site 中间件属性
16 HttpRequest.user 中间件属性,表示当前登录的用户。HttpRequest.user实际上是由一个定义在django.contrib.auth.models 中的 user model类所创建的对象。该类有许多字段,属性和方法。列举几个常用的:
1 字段:
username 用户名
first_name
last_name
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() 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()。
常见返回值方法
我们指导views函数的返回值往往直接是体现在前端界面的,返回什么决定了前端界面显示什么,在这里总结几个常见的views函数的返回情况。
Http404
需要引入: from django.http import Http404
功能:向前端返回404错误
其实这不是一个函数,是直接提供给我们的返回对象。一般作为错误情况下返回使用。
return Http404 表示向前端返回404错误
Template
需要引入: from django.template import Template
功能:生成模板对象
e.g. t = template.Template('My name is{{ name }}.')
这样就生成一个简单的html对象
get_template
需要引入: from django.template import loader
功能:通过路径获取模板对象
e.g. t = loader.get_template(‘install.html’)
我们所查找的模板会走动按照指定的模板路径查找(templates文件夹中)。得到的也是一个模板对象
Context
需要引入: from django.template import Context
功能:生成一个context对象
e.g. c = template.Context({'name':'Adrian'})
这样生成的一个context对象用于解析模板,替换模板中的变量
render
需要引入: from django.shortcuts import render
功能:解析模板没返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。
e.g. html = t.render(c)
HttpResponse
需要引入: from django.http import HttpResponse
功能:返回一个Response用于服务器和客户机之间的信息传递。
e.g. return HttpRessponse(html)
这样,最简单的从现象来说html就会以网页形式显示在web上了
但是自django1.3开始:render()方法是render_to_response的一个崭新的快捷方式,前者会自动使用RequestContext。而后者必须coding出来,这是最明显的区别,当然前者更简洁。
return render_to_response('blog_add.html',{'blog': blog, 'form': form, 'id': id, 'tag': tag},
context_instance=RequestContext(request))
return render(request, 'blog_add.html', {'blog': blog, 'form': form, 'id': id, 'tag': tag})
render_to_response
需要引入: from django.shortcuts import render_to_response
功能:向一个模板传递context并且返回Response
e.g. return render_to_response(‘index.html’, {‘name’:’Adrian’})
通过着一点来看这个函数实际上是前面若干个函数的集合简化版本。实际这个函数还有一个重要的第三个参数,我们下面会提到。
locals
需要引入:内建函数
功能:生成一个字典对所有的局部变量的名称与值进行映射
e.g. return render_to_response(‘index.html', locals())
这样就不需要我们再费力的写一个字典逐个地写出局部变量的名称和对应的值了,注意的是这种方法字典键的名称就是变量的名称。
ResquestContext
需要引入: from django.template import RequestContext
功能:生成一个context对象
从功能上看和Context有相似之处,但实际还是有些不同。查看源码可知这个类实例化时要第一个传入request,在settings.py中有一个与RequestContext密切相关的配置项为TEMPLATE_CONTEXT_PROCESSORS。这些Processors都会被RequestContext顺序调用,往当前Context中放入一些预定义变量。再实际应用住配合render_to_reaponse的情况较多,用于向所有模板中的变量传值。
e.g. render_to_response('index.html',{'name':’Aidran’},context_instance=RequestContext(request))