def index(request): 這個request其實就是內(nèi)部已經(jīng)封裝好的Http請求HttpRequest,它是一個請求對象
Django中的視圖主要用來接受Web請求,并做出響應(yīng)。
視圖的本質(zhì)就是一個Python中的函數(shù)
視圖的響應(yīng)分為兩大類
1) 以json數(shù)據(jù)形式返回(JsonResponse)
2) 以網(wǎng)頁的形式返回
2.1) 重定向到另一個網(wǎng)頁(HttpResponseRedirect)
2.2) 錯誤視圖(4xx,5xx)(HttpResponseNotFound,HttpResponseForbidden,HttpResponseNotAllowed等)
視圖響應(yīng)過程:
瀏覽器輸入-> urls 路由匹配 -> 視圖響應(yīng) -> 回饋到瀏覽器
視圖參數(shù):
1)一個HttpRequest的實例,一般命名為request
2)通過ur1正則表達式傳遞過來的參數(shù)
位置:
通常在應(yīng)用下的views.py中定義
錯誤視圖:
1)404視圖(頁面沒找到)
2)400視圖(客戶操作錯誤)
3) 500視圖 (服務(wù)器內(nèi)部錯誤)
HttpRequest
服務(wù)器在接收到Http請求后,會根據(jù)報文創(chuàng)建HttpRequest對象
視圖中的第一個參數(shù)就是HttpRequest對象
Django框架接收到http請求之后會將http請求包裝為HttpRequest對象,之后傳遞給視圖。
request常用屬性和方法
屬性:
path 請求的完整路徑
method 請求的方法,常用GET,POST
GET 類似字典的參數(shù),包含了get的所有參數(shù)
POST 類似字典的參數(shù),包含了post所有參數(shù)
FILES 類似字典的參數(shù),包含了上傳的文件
COOKIES 字典,包含了所有COOKIE
session 類似字典,表示會話
META['REMOTE_ADDR']
方法:
is_ajax() 判斷是否是ajax(),通常用在移動端和JS中
get_full_path() 返回包含參數(shù)字符串的請求路徑
QueryDict: 類字典的對象
類似字典的數(shù)據(jù)結(jié)構(gòu)。與字典的區(qū)別:可以存在相同的鍵。
QueryDict中數(shù)據(jù)獲取方式
dict['uname']或 dict.get('uname')
獲取指定key對應(yīng)的所有值
dict.getlist('uname')
HttpResponse
服務(wù)器返回給客戶端的數(shù)據(jù)
HttpResponse由程序員自己創(chuàng)建
1)不使用模板,直接調(diào)用HttpResponse(),返回HttpResponse對象。
2)調(diào)用模板,進行渲染。
使用render
render(request,template_name[,context])
request 請求體對象
template_name 模板路徑
context 字典參數(shù),用來填坑
屬性: content 返回的內(nèi)容
charset 編碼格式
status_code 響應(yīng)狀態(tài)碼(2xx,3xx,4xx,5xx)
方法:
write(xxx) 直接寫出文本
flush() 沖刷緩沖區(qū)
set_cookie(key,value='xxx',max_age=None) 設(shè)置cookie
delete_cookie(key) 刪除cookie
HttpResponse子類
HttpResponseRedirect
響應(yīng)重定向:可以實現(xiàn)服務(wù)器內(nèi)部跳轉(zhuǎn)
return HttpResponseRedict('/grade/2030')
使用的時候推薦使用反向解析
JsonResponse
返回Json數(shù)據(jù)的請求,通常用在異步請求上
JsonResponse(dict)
返回json數(shù)據(jù)時,Content-type是application/json
實踐
新建一個項目 Day05DjangoPro,創(chuàng)建一個應(yīng)用 叫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文章來源:http://www.zghlxwxcb.cn/news/detail-663601.html
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 可以當(dāng)成字典來用
。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請求的參數(shù) <QueryDict: {'name': ['清風(fēng)'], 'age': ['18']}>
print(request.GET['name']) # 第一種方式,如果沒有就會報錯
print(request.GET.get('name', default='匿名用戶')) # 第二種方式,如果沒有就會返回None或者默認(rèn)值(跟字典一樣dict),不會報錯,推薦使用這種方式
print(request.GET.getlist('name')) # 第三種,如果name有多個值,則都會獲取,以列表[]的形式返回,沒有數(shù)據(jù)就返回空列表[]
# print(request.POST) # POST請求的參數(shù) <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=清風(fēng)&name=微泫
此外還有…
# 請求
def my_request(request):
print(request) # 請求對象
print(request.COOKIES) # cookie 會話技術(shù)
# {'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')
響應(yīng)
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. 返回字符串:企業(yè)項目中使用很少
# return HttpResponse('ok')
# 2. 返回模板:前后端不分離的時候使用
# return render(request, 'index.html', {'key1': 'value1', 'key2': 'value2'})
# 3. 重定向: 頁面跳轉(zhuǎn)用的,路徑的跳轉(zhuǎn)
# 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請求的參數(shù) <QueryDict: {'name': ['清風(fēng)'], 'age': ['18']}>
# print(request.GET['name']) # 第一種方式,如果沒有就會報錯
# print(request.GET.get('name', default='匿名用戶')) # 第二種方式,如果沒有就會返回None或者默認(rèn)值(跟字典一樣dict),不會報錯,推薦使用這種方式
# print(request.GET.getlist('name')) # 第三種,如果name有多個值,則都會獲取,以列表[]的形式返回,沒有數(shù)據(jù)就返回空列表[]
# # print(request.POST) # POST請求的參數(shù) <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 會話技術(shù)
# {'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和內(nèi)容加進去,在它內(nèi)部會將html內(nèi)容、模板語法 和 發(fā)過去的數(shù)據(jù) 進行結(jié)合做渲染,渲染之后得到的content其實是一個可能很長的html數(shù)據(jù),所以返回的也是一個字符串。
App\views.py
def my_response(request):
response = HttpResponse('ok')
response.content = 'hello'
response.status_code = 400
return response
文章來源地址http://www.zghlxwxcb.cn/news/detail-663601.html
到了這里,關(guān)于Django視圖-HttpRequest請求對象和HttpResponse響應(yīng)對象的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!