Django视图-HttpRequest请求对象和HttpResponse响应对象


def index(request):  这个request其实就是内部已经封装好的Http请求HttpRequest,它是一个请求对象

Django中的视图主要用来接受Web请求,并做出响应。
视图的本质就是一个Python中的函数
视图的响应分为两大类
	1) 以json数据形式返回(JsonResponse)
	2) 以网页的形式返回
		2.1) 重定向到另一个网页(HttpResponseRedirect)
		2.2) 错误视图(4xx,5xx)(HttpResponseNotFound,HttpResponseForbidden,HttpResponseNotAllowed等)
视图响应过程:
	浏览器输入-> urls 路由匹配  -> 视图响应 -> 回馈到浏览器
视图参数:
	1)一个HttpRequest的实例,一般命名为request
	2)通过ur1正则表达式传递过来的参数
位置:
	通常在应用下的views.py中定义
		错误视图:
			1404视图(页面没找到)
			2400视图(客户操作错误)
			3) 500视图 (服务器内部错误)

HttpRequest

服务器在接收到Http请求后,会根据报文创建HttpRequest对象
视图中的第一个参数就是HttpRequest对象
Django框架接收到http请求之后会将http请求包装为HttpRequest对象,之后传递给视图。

request常用属性和方法
	属性:
		path	请求的完整路径
		method 	请求的方法,常用GET,POST
		GET		类似字典的参数,包含了get的所有参数
		POST	类似字典的参数,包含了post所有参数
		FILES	类似字典的参数,包含了上传的文件
		COOKIES	字典,包含了所有COOKIE
		session	类似字典,表示会话
		META['REMOTE_ADDR']
	方法:
		is_ajax()	判断是否是ajax(),通常用在移动端和JS中
		get_full_path()	返回包含参数字符串的请求路径
QueryDict:	类字典的对象
	类似字典的数据结构。与字典的区别:可以存在相同的键。
	QueryDict中数据获取方式
		dict['uname']dict.get('uname')
		获取指定key对应的所有值
		dict.getlist('uname')

HttpResponse

服务器返回给客户端的数据
HttpResponse由程序员自己创建
	1)不使用模板,直接调用HttpResponse(),返回HttpResponse对象。
	2)调用模板,进行渲染。
	使用render
		render(request,template_name[,context])
		request			请求体对象
		template_name	模板路径
		context			字典参数,用来填坑

属性: 	content		返回的内容
		charset		编码格式
		status_code	响应状态码(2xx,3xx,4xx,5xx)

方法:
		write(xxx)		直接写出文本
		flush()			冲刷缓冲区
		set_cookie(key,value='xxx',max_age=None)	设置cookie
		delete_cookie(key)		删除cookie

HttpResponse子类
	HttpResponseRedirect
		响应重定向:可以实现服务器内部跳转
		return HttpResponseRedict('/grade/2030')
		使用的时候推荐使用反向解析
	JsonResponse
		返回Json数据的请求,通常用在异步请求上
			JsonResponse(dict)
			返回json数据时,Content-type是application/json

实践

新建一个项目 Day05DjangoPro,创建一个应用 叫App

在这里插入图片描述
不写子路由啦,直接写根路由Day05DjangoPro\urls.py

from django.contrib import admin
from django.urls import path
from App.views import *

urlpatterns = [
    path('myrequest/',my_request),
    path('admin/', admin.site.urls),
]

App\views.py

from django.shortcuts import render, HttpResponse


# 请求
def my_request(request):
    print(request)   # 请求对象
    # <WSGIRequest: GET '/myrequest/'>
    return HttpResponse('ok')

http://127.0.0.1:8000/myrequest/

打印得到的是<WSGIRequest: GET ‘/myrequest/’>
WSGIRequest是什么?我们可以看一下
在这里插入图片描述
WSGIRequest 继承 HttpRequest ,HttpRequest 再点开看一下
在这里插入图片描述
QueryDict 继承 MultiValueDict,MultiValueDict继承 dict字典,所以QueryDict 可以当成字典来用。QueryDict 是一个 类字典对象。

request对象的属性和方法

App\views.py

from django.shortcuts import render, HttpResponse


# 请求
def my_request(request):
    print(request)  # 请求对象
    # <WSGIRequest: GET '/myrequest/'>

    # request对象的属性和方法
    print(request.method)  # 请求方式,GET,POST...
    print(request.GET)  # GET请求的参数 <QueryDict: {'name': ['清风'], 'age': ['18']}>
    print(request.GET['name'])  # 第一种方式,如果没有就会报错
    print(request.GET.get('name', default='匿名用户'))  # 第二种方式,如果没有就会返回None或者默认值(跟字典一样dict),不会报错,推荐使用这种方式
    print(request.GET.getlist('name'))  # 第三种,如果name有多个值,则都会获取,以列表[]的形式返回,没有数据就返回空列表[]
    # print(request.POST)  # POST请求的参数 <QueryDict: {}>
    # print(request.POST.get('name', default='匿名用户')) # 也是一样的

    print(request.path)  # 路径,就是我们写的路由 /myrequest/
    print(request.get_full_path())  # 整个路径  /myrequest/?age=18&name=%E6%B8%85%E9%A3%8E&name=%E5%BE%AE%E6%B3%AB

    return HttpResponse('ok')

http://127.0.0.1:8000/myrequest/?age=18&name=清风&name=微泫

在这里插入图片描述

此外还有…

# 请求
def my_request(request):
    print(request)  # 请求对象
    print(request.COOKIES)  # cookie 会话技术
    # {'csrftoken': 'lvQaYuMDgiemswhYomZXc1msPaoSS35J'}
    print(request.session)  # session 会话
    # <django.contrib.sessions.backends.db.SessionStore object at 0x0000023890CB3890>
    print(request.FILES)  # 文件,前端上传的文件对象
    print(request.META['REMOTE_ADDR'])  # 客户端的IP地址

    return HttpResponse('ok')

响应

Day05DjangoPro\urls.py

path('myresponse/', my_response),

App\views.py

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect, reverse, HttpResponseRedirect


def my_response(request):
    # 1. 返回字符串:企业项目中使用很少
    # return HttpResponse('ok')

    # 2. 返回模板:前后端不分离的时候使用
    # return render(request, 'index.html', {'key1': 'value1', 'key2': 'value2'})

    # 3. 重定向: 页面跳转用的,路径的跳转
    # redirect 和 HttpResponseRedirect是一样的
    # return redirect("https://blog.csdn.net/weixin_59633478/category_12401835.html")
    # return redirect("/request/")
    # return HttpResponseRedirect("/request/")
    # redirect(reverse("命名空间:userdetail", args=(2,)))
    # return redirect(reverse("App:userdetail", kwargs={'uid': 2}))

    # 4. 返回JSON: 前后端分离的情况使用
    return JsonResponse({
        'data': 123
    })


# 请求
def my_request(request):
    print(request)  # 请求对象
    # <WSGIRequest: GET '/myrequest/'>

    # request对象的属性和方法
    # print(request.method)  # 请求方式,GET,POST...
    # print(request.GET)  # GET请求的参数 <QueryDict: {'name': ['清风'], 'age': ['18']}>
    # print(request.GET['name'])  # 第一种方式,如果没有就会报错
    # print(request.GET.get('name', default='匿名用户'))  # 第二种方式,如果没有就会返回None或者默认值(跟字典一样dict),不会报错,推荐使用这种方式
    # print(request.GET.getlist('name'))  # 第三种,如果name有多个值,则都会获取,以列表[]的形式返回,没有数据就返回空列表[]
    # # print(request.POST)  # POST请求的参数 <QueryDict: {}>
    # # print(request.POST.get('name', default='匿名用户')) # 也是一样的
    #
    # print(request.path)  # 路径,就是我们写的路由 /myrequest/
    # print(request.get_full_path())  # 整个路径  /myrequest/?age=18&name=%E6%B8%85%E9%A3%8E&name=%E5%BE%AE%E6%B3%AB

    print(request.COOKIES)  # cookie 会话技术
    # {'csrftoken': 'lvQaYuMDgiemswhYomZXc1msPaoSS35J'}
    print(request.session)  # session 会话
    # <django.contrib.sessions.backends.db.SessionStore object at 0x0000023890CB3890>
    print(request.FILES)  # 文件,前端上传的文件对象
    print(request.META['REMOTE_ADDR'])  # 客户端的IP地址

    return HttpResponse('ok')

在这里插入图片描述


在这里插入图片描述
其实render返回的也是HttpResponse,只不过我们通过render_to_string方法将我们模板也就是html和内容加进去,在它内部会将html内容、模板语法 和 发过去的数据 进行结合做渲染,渲染之后得到的content其实是一个可能很长的html数据,所以返回的也是一个字符串。


App\views.py

def my_response(request):
    response = HttpResponse('ok')
    response.content = 'hello'
    response.status_code = 400
    return response

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值