当前位置: 移动技术网 > IT编程>脚本编程>Python > django 请求 与 响应

django 请求 与 响应

2019年07月17日  | 移动技术网IT编程  | 我要评论

zuzu面膜官网,打印耗材网,善男信女 步微澜

请求(httprequest) 与 响应(httpresponse)

httprequest对象

  • request(请求)

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

请求相关的常用值

  • request.path_info 返回用户访问url,不包括域名(id和端口),参数 如:(/index/)
  • request.path 与path_info一样
  • request.method 请求中使用的http方法的字符串表示,全大写表示(8种)。
  • request.get 包含所有http get参数的类字典对象(url上携带的参数)
  • request.post 包含所有http post参数的类字典对象(post请求提交的数据)
  • request.body 请求体,byte类型 request.post的数据就是从body里面提取到的 如(b'内容')

属性

  • 所有的属性应该被认为是只读的,除非另有说明。
"""
  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 启用会话的支持时才可用。
    完整的细节参见会话的文档。
  • 上传文件示例

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")
    
#html 
<form action="" method="post" enctype="multipart/form-data">#要写enctype
    {% csrf_token %}#防跨站伪造
    <input type="file"  name="f1">
    <button>上传</button>
</form>
  • 方法
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()   #带参数 不包涵ip 端口

  返回 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') 装饰你的视图以让响应能够正确地缓存。

注意:键值对的值是多个的时候,比如checkbox类型的input标签,select标签,需要用:request.post.getlist("hobby")

httpresponse对象

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

httpresponse类位于django.http模块中。
"""
from django.shortcuts import render, redirect, httpresponse
httpresponse('字符串')    ——》  ’字符创‘
render(request,'模板的文件名',{k1:v1})   ——》 返回一个完整的tml页面
redirect('重定向的地址')    ——》 重定向   location : 地址
"""

#前后端分离项目 利用json传输数据
from django.http.response import jsonresponse
def json_data(request):
    data = {'name':'gandan','age':18}
jsonresponse(data) #浏览器会自己做json反序列化 把数据变为可用的

jsonresponse(data,safe=false) #列表序列化
  • 传递字符串
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)
  • django shortcut functions

render() 参数

img

  • 结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的 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))

redirect() 参数

  • 参数可以是:
  一个模型:将调用模型的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页面。
"""

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

相关文章:

验证码:
移动技术网