当前位置: 移动技术网 > IT编程>脚本编程>Python > python 终极篇 --- django 视图系统

python 终极篇 --- django 视图系统

2018年09月14日  | 移动技术网IT编程  | 我要评论

湖北经视桃花朵朵开,陈文佩,蓝月亮网站

                                       django的view(视图)                                         

一个视图函数(类),简称视图,是一个简单的python 函数(类),它接受web请求并且返回web响应。

响应可以是一张网页的html内容,一个重定向,一个404错误,一个xml文档,或者一张图片。

无论视图本身包含什么逻辑,都要返回响应。代码写在哪里也无所谓,只要它在你当前项目目录下面。除此之外没有更多的要求了——可以说“没有什么神奇的地方”。为了将代码放在某处,大家约定成俗将视图放置在项目(project)或应用程序(app)目录中的名为views.py的文件中。

                                    cbv和fbv                                         

我们之前写过的都是基于函数的view,就叫fbv。还可以把view写成基于类的。

就拿我们之前写过的添加班级为例:

fbv版:

复制代码
# fbv版添加班级
def add_class(request):
    if request.method == "post":
        class_name = request.post.get("class_name")
        models.classes.objects.create(name=class_name)
        return redirect("/class_list/")
    return render(request, "add_class.html")
复制代码

cbv版:

复制代码
# cbv版添加班级
from django.views import view


class addclass(view):

    def get(self, request):
        return render(request, "add_class.html")

    def post(self, request):
        class_name = request.post.get("class_name")
        models.classes.objects.create(name=class_name)
        return redirect("/class_list/")
复制代码

注意:

使用cbv时,urls.py中也做对应的修改:

# urls.py中
url(r'^add_class/$', views.addclass.as_view()),

cbv简单的流程:
   1. addpublisher.as_view() ——》 view函数
   2. 当请求到来的时候才执行view函数
     1. 实例化addpublisher  ——》 self
     2. self.request = request
     3. 执行self.dispatch(request, *args, **kwargs)
      1. 判断请求方式是否被允许
       handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
       通过反射获取对应的方法
       get  ——》  get
       post ——》  post
      
     2. 执行获取到的方法  get(request,)  或者post(request,)
     3. 得到httpresponse对象,返回给self.dispatch
    4. 得到httpresponse对象,返回django处理

fbv ---   基于函数的视图    

cbv ----基于类的视图

                                 加装饰器                                     

fbv本身就是函数,所以与普通函数加装饰器没有任何区别;

cbv加装饰器

类中的方法与独立函数不完全相同,因此不能直接将函数装饰器应用于类中的方法 ,我们需要先将其转换为方法装饰器。

django中提供了method_decorator装饰器用于将函数装饰器转换为方法装饰器。

复制代码
# cbv版添加班级
from django.views import view
from django.utils.decorators import method_decorator

class addclass(view):

    @method_decorator(wrapper)
    def get(self, request):
        return render(request, "add_class.html")

    def post(self, request):
        class_name = request.post.get("class_name")
        models.classes.objects.create(name=class_name)
        return redirect("/class_list/")
复制代码
# 使用cbv时要注意,请求过来后会先执行dispatch()这个方法,如果需要批量对具体的请求处理方法,如get,post等做一些操作的时候,这里我们可以手动改写dispatch方法,这个dispatch方法就和在fbv上加装饰器的效果一样。

class login(view):
     
    def dispatch(self, request, *args, **kwargs):
        print('before')
        obj = super(login,self).dispatch(request, *args, **kwargs)
        print('after')
        return obj
 
    def get(self,request):
        return render(request,'login.html')
 
    def post(self,request):
        print(request.post.get('user'))
        return httpresponse('login.post')
cbv扩展阅读

使用cbv时要注意,请求过来后会先执行dispatch()这个方法

                   request对象和response对象                  

request对象

当一个页面被请求时,django就会创建一个包含本次请求原信息的httprequest对象。
django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 request 参数承接这个对象。

其实request参数就接收了页面请求.

请求相关的常用值
path_info     返回用户访问url,不包括域名
method        请求中使用的http方法的字符串表示,全大写表示。
get              包含所有http  get参数的类字典对象
post           包含所有http post参数的类字典对象
body            请求体,byte类型 request.post的数据就是从body里面提取到的

属性----重要

属性:
  django将请求报文中的请求行、头部信息、内容主体封装成 httprequest 类中的属性。
   除了特殊说明的之外,其他均为只读的。


0.httprequest.scheme
   表示请求方案的字符串(通常为http或https)

1.httprequest.body

  一个字符串,代表请求报文的主体。在处理非 http 形式的报文时非常有用,例如:二进制图片、xml,json等。

  但是,如果要处理表单数据的时候,推荐还是使用 httprequest.post 。

  另外,我们还可以用 python 的类文件方法去操作它,详情参考 httprequest.read() 。

 

2.httprequest.path

  一个字符串,表示请求的路径组件(不含域名)。

  例如:"/music/bands/the_beatles/"



3.httprequest.method

  一个字符串,表示请求使用的http 方法。必须使用大写。

  例如:"get"、"post"

 

4.httprequest.encoding

  一个字符串,表示提交的数据的编码方式(如果为 none 则表示使用 default_charset 的设置,默认为 'utf-8')。
   这个属性是可写的,你可以修改它来修改访问表单数据使用的编码。
   接下来对属性的任何访问(例如从 get 或 post 中读取数据)将使用新的 encoding 值。
   如果你知道表单数据的编码不是 default_charset ,则使用它。

 

5.httprequest.get 

  一个类似于字典的对象,包含 http get 的所有参数。详情请参考 querydict 对象。

 

6.httprequest.post

  一个类似于字典的对象,如果请求中包含表单数据,则将这些数据封装成 querydict 对象。

  post 请求可以带有空的 post 字典 —— 如果通过 http post 方法发送一个表单,但是表单中没有任何的数据,querydict 对象依然会被创建。
   因此,不应该使用 if request.post  来检查使用的是否是post 方法;应该使用 if request.method == "post" 

  另外:如果使用 post 上传文件的话,文件信息将包含在 files 属性中。

 7.httprequest.cookies

  一个标准的python 字典,包含所有的cookie。键和值都为字符串。

 

8.httprequest.files

  一个类似于字典的对象,包含所有的上传文件信息。
   files 中的每个键为<input type="file" name="" /> 中的name,值则为对应的数据。

  注意,files 只有在请求的方法为post 且提交的<form> 带有enctype="multipart/form-data" 的情况下才会
   包含数据。否则,files 将为一个空的类似于字典的对象。

 

9.httprequest.meta

   一个标准的python 字典,包含所有的http 首部。具体的头部信息取决于客户端和服务器,下面是一些示例:

    content_length —— 请求的正文的长度(是一个字符串)。
    content_type —— 请求的正文的mime 类型。
    http_accept —— 响应可接收的content-type。
    http_accept_encoding —— 响应可接收的编码。
    http_accept_language —— 响应可接收的语言。
    http_host —— 客服端发送的http host 头部。
    http_referer —— referring 页面。
    http_user_agent —— 客户端的user-agent 字符串。
    query_string —— 单个字符串形式的查询字符串(未解析过的形式)。
    remote_addr —— 客户端的ip 地址。
    remote_host —— 客户端的主机名。
    remote_user —— 服务器认证后的用户。
    request_method —— 一个字符串,例如"get" 或"post"。
    server_name —— 服务器的主机名。
    server_port —— 服务器的端口(是一个字符串)。
   从上面可以看到,除 content_length 和 content_type 之外,请求中的任何 http 首部转换为 meta 的键时,
    都会将所有字母大写并将连接符替换为下划线最后加上 http_  前缀。
    所以,一个叫做 x-bender 的头部将转换成 meta 中的 http_x_bender 键。

 
10.httprequest.user

  一个 auth_user_model 类型的对象,表示当前登录的用户。

  如果用户当前没有登录,user 将设置为 django.contrib.auth.models.anonymoususer 的一个实例。你可以通过 is_authenticated() 区分它们。

    例如:

    if request.user.is_authenticated():
        # do something for logged-in users.
    else:
        # do something for anonymous users.
     

       user 只有当django 启用 authenticationmiddleware 中间件时才可用。

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

    匿名用户
    class models.anonymoususer

    django.contrib.auth.models.anonymoususer 类实现了django.contrib.auth.models.user 接口,但具有下面几个不同点:

    id 永远为none。
    username 永远为空字符串。
    get_username() 永远返回空字符串。
    is_staff 和 is_superuser 永远为false。
    is_active 永远为 false。
    groups 和 user_permissions 永远为空。
    is_anonymous() 返回true 而不是false。
    is_authenticated() 返回false 而不是true。
    set_password()、check_password()、save() 和delete() 引发 notimplementederror。
    new in django 1.8:
    新增 anonymoususer.get_username() 以更好地模拟 django.contrib.auth.models.user。

 

11.httprequest.session

   一个既可读又可写的类似于字典的对象,表示当前的会话。只有当django 启用会话的支持时才可用。
    完整的细节参见会话的文档。
request属性
1.httprequest.get_host()

  根据从http_x_forwarded_host(如果打开 use_x_forwarded_host,默认为false)和 http_host 头部信息返回请求的原始主机。
   如果这两个头部没有提供相应的值,则使用server_name 和server_port,在pep 3333 中有详细描述。

  use_x_forwarded_host:一个布尔值,用于指定是否优先使用 x-forwarded-host 首部,仅在代理设置了该首部的情况下,才可以被使用。

  例如:"127.0.0.1:8000"

  注意:当主机位于多个代理后面时,get_host() 方法将会失败。除非使用中间件重写代理的首部。

 

2.httprequest.get_full_path()

  返回 path,如果可以将加上查询字符串。

  例如:"/music/bands/the_beatles/?print=true"

 

3.httprequest.get_signed_cookie(key, default=raise_error, salt='', max_age=none)

  返回签名过的cookie 对应的值,如果签名不再合法则返回django.core.signing.badsignature。

  如果提供 default 参数,将不会引发异常并返回 default 的值。

  可选参数salt 可以用来对安全密钥强力攻击提供额外的保护。max_age 参数用于检查cookie 对应的时间戳以确保cookie 的时间不会超过max_age 秒。

        复制代码
        >>> request.get_signed_cookie('name')
        'tony'
        >>> request.get_signed_cookie('name', salt='name-salt')
        'tony' # 假设在设置cookie的时候使用的是相同的salt
        >>> request.get_signed_cookie('non-existing-cookie')
        ...
        keyerror: 'non-existing-cookie'    # 没有相应的键时触发异常
        >>> request.get_signed_cookie('non-existing-cookie', false)
        false
        >>> request.get_signed_cookie('cookie-that-was-tampered-with')
        ...
        badsignature: ...    
        >>> request.get_signed_cookie('name', max_age=60)
        ...
        signatureexpired: signature age 1677.3839159 > 60 seconds
        >>> request.get_signed_cookie('name', false, max_age=60)
        false
        复制代码
         


4.httprequest.is_secure()

  如果请求时是安全的,则返回true;即请求通是过 https 发起的。

 

5.httprequest.is_ajax()

  如果请求是通过xmlhttprequest 发起的,则返回true,方法是检查 http_x_requested_with 相应的首部是否是字符串'xmlhttprequest'。

  大部分现代的 javascript 库都会发送这个头部。如果你编写自己的 xmlhttprequest 调用(在浏览器端),你必须手工设置这个值来让 is_ajax() 可以工作。

  如果一个响应需要根据请求是否是通过ajax 发起的,并且你正在使用某种形式的缓存例如django 的 cache middleware, 
   你应该使用 vary_on_headers('http_x_requested_with') 装饰你的视图以让响应能够正确地缓存。
request方法

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

request.post.getlist("hobby")

上传文件实例:

<body>

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button>提交</button>
</form>

</body>
上传页面html
def upload(request):
    """
    保存上传文件前,数据需要存放在某个位置。默认当上传文件小于2.5m时,django会将上传文件的全部内容读进内存。从内存读取一次,写磁盘一次。
    但当上传文件很大时,django会把上传文件写到临时文件中,然后存放到系统临时文件夹中。
    :param request: 
    :return: 
    """
    if request.method == "post":
        # 从请求的files中获取上传文件的文件名,file为页面上type=files类型input的name属性值
        filename = request.files["file"].name
        # 在项目目录下新建一个文件
        with open(filename, "wb") as f:
            # 从上传的文件对象中一点一点读
            for chunk in request.files["file"].chunks():
                # 写入本地文件
                f.write(chunk)
        return httpresponse("上传ok")
逻辑代码

上传文件的form表单配置  ----   <form action="" method="post" enctype="multipart/form-data">

           response对象             

与由django自动创建的httprequest对象相比,httpresponse对象是我们的职责范围了。我们写的每个视图都需要实例化,填充和返回一个httpresponse。

httpresponse类位于django.http模块中。

使用

传递字符串

from django.http import httpresponse
response = httpresponse("here's the text of the web page.")
response = httpresponse("text only, please.", content_type="text/plain")

设置或删除响应头信息

response = httpresponse()
response['content-type'] = 'text/html; charset=utf-8'
del response['content-type']

属性

httpresponse.content:响应内容

httpresponse.charset:响应内容的编码

httpresponse.status_code:响应的状态码

 

jsonresponse对象

jsonresponse是httpresponse的子类,专门用来生成json编码的响应。

复制代码
from django.http import jsonresponse

response = jsonresponse({'foo': 'bar'})
print(response.content)

b'{"foo": "bar"}'
复制代码

默认只能传递字典类型,如果要传递非字典类型需要设置一下safe关键字参数。

response = jsonresponse([1, 2, 3], safe=false)

1. httpresponse('字符串')   ——》  页面显示字符串的内容
       content-type : text/html;charset=utf8
 2. render(request,'模板文件名',{})  ——》 返回一个完整的页面

结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 httpresponse 对象。
参数:
request: 用于生成响应的请求对象。
template_name:要使用的模板的完整名称,可选的参数
context:添加到模板上下文的一个字典。默认是一个空字典。如果字典中的某个值是可调用的,视图将在渲染模板之前调用它。
content_type:生成的文档要使用的mime类型。默认为 default_content_type 设置的值。默认为'text/html'
status:响应的状态码。默认为200。
useing: 用于加载模板的模板引擎的名称。
一个简单的例子:
from django.shortcuts import render

def my_view(request):
    # 视图的代码写在这里
    return render(request, 'myapp/', {'foo': 'bar'})
上面的代码等于:

from django.http import httpresponse
from django.template import loader

def my_view(request):
    # 视图代码写在这里
    t = loader.get_template('myapp/')
    c = {'foo': 'bar'}
    return httpresponse(t.render(c, request))
render

3. redirect('/index/')    跳转 重定向 location:/index/      

参数可以是:
一个模型:将调用模型的get_absolute_url() 函数
一个视图,可以带有参数:将使用urlresolvers.reverse 来反向解析名称
一个绝对的或相对的url,将原封不动的作为重定向的位置。
默认返回一个临时的重定向;传递permanent=true 可以返回一个永久的重定向。
示例:
你可以用多种方式使用redirect() 函数。
传递一个具体的orm对象(了解即可)
将调用具体orm对象的get_absolute_url() 方法来获取重定向的url:

from django.shortcuts import redirect
 
def my_view(request):
    ...
    object = mymodel.objects.get(...)
    return redirect(object)

传递一个视图的名称
def my_view(request):
    ...
    return redirect('some-view-name', foo='bar')
传递要重定向到的一个具体的网址
def my_view(request):
    ...
    return redirect('/some/url/')
当然也可以是一个完整的网址
def my_view(request):
    ...
    return redirect('http://example.com/')
默认情况下,redirect() 返回一个临时重定向。以上所有的形式都接收一个permanent 参数;如果设置为true,将返回一个永久的重定向:
def my_view(request):
    ...
    object = mymodel.objects.get(...)
    return redirect(object, permanent=true)  
扩展阅读: 
临时重定向(响应状态码:302)和永久重定向(响应状态码:301)对普通用户来说是没什么区别的,它主要面向的是搜索引擎的机器人。
a页面临时重定向到b页面,那搜索引擎收录的就是a页面。
a页面永久重定向到b页面,那搜索引擎收录的就是b页面。
redirect

4. jsonresponse(字典)  ——》 content-type : application/json

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网