微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Django - - - -视图层之视图函数(views)

视图层之视图函数(views)

一个视图函数,简称视图,是一个简单的Python 函数,它接受Web请求并且返回Web响应。内容,一个重定向一个404错误一个XML文档,或者一张图片. . . 是任何东西都可以。代码写在哪里也无所谓,只要它在你的Python目录下面。代码放在某处,约定是将视图放置在项目或应用程序目录中的名为teral">文件中。

函数:
一定包含两个对象:
requset---->用户请求相关的所有信息(对象)
Httpresponse---->响应字符串

一个简单的视图

一个返回当前日期和时间作为HTML文档的视图:

django.http <span style="color: #0000ff;">def<span style="color: #000000;"> current_datetime(request):
Now
=<span style="color: #000000;"> datetime.datetime.Now()
html
= <span style="color: #800000;">"
<span style="color: #800000;">It is Now %s.<span style="color: #800000;">" %<span style="color: #000000;"> Now
<span style="color: #0000ff;">return HttpResponse(html)

代码:

  • irst">teral">模块导入了teral">类,以及Python的teral">库。

  • irst">teral">函数函数。函数都使用teral">对象作为第一个参数,并且通常称之为teral">

    函数的名称并不重要;一个统一的命名方式来命名,以便让Django识别它。teral">,是因为这个名称能够精确地反映出它的功能

  • irst">一个teral">对象,其中包含生成的响应。函数都负责返回一个teral">对象。

视图函数,围绕着两个对象进行:HttpResponse和HttpRequest

1.HttpRequest

  request---->请求信息

属性

request.path     获取访问文件路径 属性   获取请求中使用的HTTP方式(POST/GET)

request.body      #含所有请求体信息 是bytes类型
 

    
      上传文件的类字典对象;FILES中的每一个Key都是标签中
                 name属性的值,FILES中的每一个value同时也是一个标准的python字典对象,包含下面三个Keys:
             filename:      <a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>名,用字符串表示
             content_type:   <a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>的Content Type
             content:       <a href="/tag/shangchuan/" target="_blank" class="keywords">上传</a><a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>的原始<a href="/tag/neirong/" target="_blank" class="keywords">内容</a></span>

<span style="color: #ff0000;">request.user: <span style="color: #008000;"> 是一个django.contrib.auth.models.User对象,<span style="color: #ff0000;">代表当前登陆的用户。如果访问用户当前
    没有登陆,user将被初始化为django.contrib.auth.models.AnonymousUser的实例。你
    可以通过user的is_authenticated()方法来辨别用户是否登陆:
    if req.user.is_authenticated();只有激活Django中的AuthenticationMiddleware
    时该属性才可用

<span style="color: #ff0000;">request.<span style="color: #000000;"><span style="color: #ff0000;">session:    <span style="color: #008000;">唯一可读写的属性,代表当前会话的字典对象;自己有激活Django中的session支持时该属性才可用

request.GET.get('name')<span style="color: #ff0000;">   拿到GET请求里name的值

<span style="color: #ff0000;">如果某个键对应有多个值,则不能直接用get取值,需要用getlist,如:

<span style="color: #ff0000;">request.POST.getlist("hobby")



请求路径
request.path结果为:/index.html/23


request.get_full_path()结果为:/index.html/23?a=1

方法

Highlighter sh-gutter">
Highlighter_526121" class="SyntaxHighlighter python">

注意:键值对的值是多个的时候,比如checkBox类型的input标签,select标签,需要用:

Highlighter sh-gutter">
Highlighter_907921" class="SyntaxHighlighter python">

2.HttpResponse

  HttpResponse---->相应字符串

  对于HttpRequest请求对象来说,是由django自动创建的,但是,HttpResponse响应对象就必须我们自己创建。每个view请求处理方法必须返回一个HttpResponse响应对象。HttpResponse类在django.http.HttpResponse。

在HttpResponse对象上扩展的常用方法

1.render 函数

  指定页面渲染后返回给浏览器

render(request,template_name[,context])

结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 HttpResponse 对象。

参数:
     request: 用于生成响应的请求对象。
 template_name:要使用的模板的完整<a href="/tag/mingcheng/" target="_blank" class="keywords">名称</a>,可选的参数

 context:<a href="/tag/tianjia/" target="_blank" class="keywords">添加</a>到模板上下文的<a href="/tag/yige/" target="_blank" class="keywords">一个</a>字典。<a href="/tag/mo/" target="_blank" class="keywords">默</a>认是<a href="/tag/yige/" target="_blank" class="keywords">一个</a>空字典。如果字典中的某个值是可<a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>的,视图将在渲染模板之前<a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>它。

 content_type:<a href="/tag/shengcheng/" target="_blank" class="keywords">生成</a>的文档要使用的MIME类型。<a href="/tag/mo/" target="_blank" class="keywords">默</a>认为DEFAULT_CONTENT_TYPE 设置的值。

 status:响应的状态码。<a href="/tag/mo/" target="_blank" class="keywords">默</a>认为200。</pre>

<div class="cnblogs_code">

 django.shortcuts <span style="color: #0000ff;">def<span style="color: #000000;"> test(request):
<span style="color: #0000ff;">return render(request,<span style="color: #800000;">'<span style="color: #800000;">index.html<span style="color: #800000;">') <span style="color: #008000;">#<span style="color: #008000;">向用户显示一个html页面

下面为render官方源码,可以看出render最后也是返回了一个HttpResponse给webserver

render(request,template_name,context=None,content_type=None,status=None,using== loader.render_to_string(template_name,context,request,using= HttpResponse(content,content_type,status)

细说render:

  render方法主要是将从服务器提取的数据,填充到模板中,然后将渲染后的html静态文件返回给浏览器。这里一定要注意:render渲染的是模板,下面我们看看什么叫作模板:

Meta Meta Meta Title decoration <{{ book.btitle }}

上面{%%}之间包括的就是我们要从数据库取出的数据,进行填充。对于这样一个没有填充数据的html文件,浏览器是不能进行渲染的,所以,对于上述{%%}之间的内容先要被render进行渲染之后,才能发送给浏览器。

  下面举个例子:

Meta Meta Meta decoration <{{ book.btitle }}<span style="color: #0000ff;"></<span style="color: #800000;">ul<span style="color: #0000ff;">>
<span style="color: #0000ff;"></
<span style="color: #800000;">body
<span style="color: #0000ff;">>

<span style="color: #0000ff;"></
<span style="color: #800000;">html
<span style="color: #0000ff;">>

= BookInfo.objects.get(pk=id)   数据库中取出对应id的数据 herolist == {: herolist}      render(request,,context)

2.redirect 函数

    一个模型:将调用模型的teral">函数
  • 一个视图,可以带有参数:将使用teral">来反向解析名称
  • 一个绝对的或相对的URL,将原封不动的作为重定向的位置。

默认返回一个临时的重定向teral">可以返回一个永久的重定向

teral">函数

irst">一个对象

irst">调用teral">方法获取重定向的URL:

Highlighter sh-gutter">
Highlighter_738800" class="SyntaxHighlighter python">

</td>
<td class="code">
<div class="container">
<div class="line number1 index0 alt2"><code class="python keyword">from
<code class="python plain">django.shortcuts
<code class="python keyword">import<code class="python plain">redirect


<div class="line number2 index1 alt1">

<div class="line number3 index2 alt2"><code class="python keyword">def<code class="python plain">my_view(request):

<div class="line number4 index3 alt1"><code class="python spaces"><code class="python plain">...

<div class="line number5 index4 alt2"><code class="python spaces"><code class="python functions">object<code class="python keyword">=<code class="python plain">MyModel.objects.get(...)

<div class="line number6 index5 alt1"><code class="python spaces"><code class="python keyword">return<code class="python plain">redirect(<code class="python functions">object<code class="python plain">)

</td>

</tr>

</table>

一个视图的名称

关键字参数;teral">方法反向解析URL: 

Highlighter sh-gutter">
Highlighter_806960" class="SyntaxHighlighter python">

</td>
<td class="code">
<div class="container">
<div class="line number1 index0 alt2"><code class="python keyword">def<code class="python plain">my_view(request):


<div class="line number2 index1 alt1"><code class="python spaces"><code class="python plain">...

<div class="line number3 index2 alt2"><code class="python spaces"><code class="python keyword">return<code class="python plain">redirect(<code class="python string">'some-view-name'<code class="python plain">,foo<code class="python keyword">=<code class="python string">'bar'<code class="python plain">)

</td>

</tr>

</table>

传递要重定向一个硬编码的URL

Highlighter sh-gutter">
Highlighter_274817" class="SyntaxHighlighter python">

</td>
<td class="code">
<div class="container">
<div class="line number1 index0 alt2"><code class="python keyword">def<code class="python plain">my_view(request):


<div class="line number2 index1 alt1"><code class="python spaces"><code class="python plain">...

<div class="line number3 index2 alt2"><code class="python spaces"><code class="python keyword">return<code class="python plain">redirect(<code class="python string">'/some/url/'<code class="python plain">)

</td>

</tr>

</table>

也可以是一个完整的URL:

Highlighter sh-gutter">
Highlighter_687133" class="SyntaxHighlighter python">

</td>
<td class="code">
<div class="container">
<div class="line number1 index0 alt2"><code class="python keyword">def<code class="python plain">my_view(request):


<div class="line number2 index1 alt1"><code class="python spaces"><code class="python plain">...

<div class="line number3 index2 alt2"><code class="python spaces"><code class="python keyword">return<code class="python plain">redirect(<code class="python string">'http://example.com/'<code class="python plain">)

</td>

</tr>

</table>

默认情况下,teral">返回一个临时重定向一个teral">参数;teral">,将返回一个永久的重定向

Highlighter sh-gutter">
Highlighter_881685" class="SyntaxHighlighter python">

</td>
<td class="code">
<div class="container">
<div class="line number1 index0 alt2"><code class="python keyword">def<code class="python plain">my_view(request):


<div class="line number2 index1 alt1"><code class="python spaces"><code class="python plain">...

<div class="line number3 index2 alt2"><code class="python spaces"><code class="python functions">object<code class="python keyword">=<code class="python plain">MyModel.objects.get(...)

<div class="line number4 index3 alt1"><code class="python spaces"><code class="python keyword">return<code class="python plain">redirect(<code class="python functions">object<code class="python plain">,permanent<code class="python keyword">=<code class="python color1">True<code class="python plain">)  

</td>

</tr>

</table>

跳转重定向)应用

-----------------------------------url(r<span style="color: #800000;">"<span style="color: #800000;">login<span style="color: #800000;">"<span style="color: #000000;">,views.login),url(r<span style="color: #800000;">"<span style="color: #800000;">yuan_back<span style="color: #800000;">"<span style="color: #000000;">,views.yuan_back),-----------------------------------<span style="color: #000000;">views.py
<span style="color: #0000ff;">def<span style="color: #000000;"> login(req):
<span style="color: #0000ff;">if req.method==<span style="color: #800000;">"<span style="color: #800000;">POST<span style="color: #800000;">"<span style="color: #000000;">:
<span style="color: #0000ff;">if 1<span style="color: #000000;">:
<span style="color: #008000;">#<span style="color: #008000;"> return redirect("/yuan_back/")
name=<span style="color: #800000;">"<span style="color: #800000;">yuanhao<span style="color: #800000;">"

        <span style="color: #0000ff;"&gt;return</span> render(req,<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;my backend.html</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,locals())

</span><span style="color: #0000ff;"&gt;return</span> render(req,<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;login.html</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,locals())

<span style="color: #0000ff;">def<span style="color: #000000;"> yuan_back(req):

name</span>=<span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;苑昊</span><span style="color: #800000;"&gt;"</span>

<span style="color: #0000ff;"&gt;return</span> render(req,locals())

-----------------------------------<span style="color: #000000;">login.html

<form action=<span style="color: #800000;">"<span style="color: #800000;">/login/<span style="color: #800000;">" method=<span style="color: #800000;">"<span style="color: #800000;">post<span style="color: #800000;">">

姓名 name=>

性别 name=>

邮箱 name=>

value=>

-----------------------------------

用户{{ name }}你好

下面我们来看一个现象:

--------------------urls.py------------------------------urlpatterns =<span style="color: #000000;"> [
url(r<span style="color: #800000;">'<span style="color: #800000;">^admin/<span style="color: #800000;">'<span style="color: #000000;">,admin.site.urls),url(r<span style="color: #800000;">'<span style="color: #800000;">^login/<span style="color: #800000;">'<span style="color: #000000;">,url(r<span style="color: #800000;">'<span style="color: #800000;">^index/<span style="color: #800000;">'<span style="color: #000000;">,views.index,),<span style="color: #008000;">#<span style="color: #008000;"> url(r'^register/',views.register,name='reg'),
<span style="color: #000000;">
]

------------------view.py-------------------------------
<span style="color: #0000ff;">def<span style="color: #000000;"> login(request):
<span style="color: #0000ff;">if request.method==<span style="color: #800000;">'<span style="color: #800000;">POST<span style="color: #800000;">'<span style="color: #000000;">:
username=request.POST.get(<span style="color: #800000;">'<span style="color: #800000;">user<span style="color: #800000;">'<span style="color: #000000;">)
password=request.POST.get(<span style="color: #800000;">'<span style="color: #800000;">pwd<span style="color: #800000;">'<span style="color: #000000;">)
<span style="color: #0000ff;">if username==<span style="color: #800000;">'<span style="color: #800000;">yuan<span style="color: #800000;">' <span style="color: #0000ff;">and password==<span style="color: #800000;">'<span style="color: #800000;">123<span style="color: #800000;">'<span style="color: #000000;">:
<span style="color: #008000;">#<span style="color: #008000;"> return render(request,'index.html')
<span style="color: #0000ff;">return redirect(<span style="color: #800000;">'<span style="color: #800000;">/index/<span style="color: #800000;">'<span style="color: #000000;">)
<span style="color: #0000ff;">else<span style="color: #000000;">:
<span style="color: #0000ff;">return render(request,<span style="color: #800000;">'<span style="color: #800000;">login.html<span style="color: #800000;">',{<span style="color: #800000;">'<span style="color: #800000;">info<span style="color: #800000;">':<span style="color: #800000;">'<span style="color: #800000;">账号或密码错误<span style="color: #800000;">'<span style="color: #000000;">})
<span style="color: #0000ff;">else<span style="color: #000000;">:
<span style="color: #0000ff;">return render(request,<span style="color: #800000;">'<span style="color: #800000;">login.html<span style="color: #800000;">'<span style="color: #000000;">)

<span style="color: #0000ff;">def<span style="color: #000000;"> index(request):
name=<span style="color: #800000;">'<span style="color: #800000;">yuan<span style="color: #800000;">'
<span style="color: #0000ff;">return render(request,<span style="color: #800000;">'<span style="color: #800000;">index.html<span style="color: #800000;">',{<span style="color: #800000;">'<span style="color: #800000;">a<span style="color: #800000;">'<span style="color: #000000;">:name})

---------------login.html--------------------------------

登陆界面

method=>

姓名 name=>

密码 name=>

>

{{ info }}

---------------login.html--------------------------------

个人主页

hello,{{ a}}

代码

首先,启动服务器后,我们进入login页面

正确输入姓名,密码后,此时执行redirect函数,结果如下

现在我们将redirect换成render,再重新走一遍看看,在login页面,正确输入姓名,密码后,结果如下:

细心的人会发现,用render函数执行后的,地址栏的地址没有变化,还是login,且页面上的{{a}}此时也没有被渲染,所以hello,后面没有内容显示

对比render与redirect:

原因是
render: 只是返回页面内容,但是未发送第二次请求
redirect:发送了第二次请求,url更新

一个登陆成功后的页面,刷新该页面回复跳转页面。而redirect则不会

页面需要模板语言渲染,需要的将数据库的数据加载到html,那么render方法则不会显示这一部分,render返回一个登陆成功页面,不会经过url路由分发系统,也就是说,不会执行跳转后url的视图函数。这样,返回的页面渲染不成功;而redirect是跳转指定页面,当登陆成功后,会在url路由系统进行匹配,如果有存在的映射函数,就会执行对应的映射函数

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐