请求与响应、重定向
网络协议 + 域名 + 路由地址 +查询字符串
https:// +editor.csdn.net/ + md +?articleId=XXXX
一. 请求 - request
利用HTTP协议向服务器传递参数有几种途径?
- 在服务器端的路由中用正则表达式截取URL特定部分,如:/news/wuhan/2020;
- 通过查询字符串(query string),形如key1=value1&key2=value2;
- 包含于发送数据的请求体中,比如表单数据、json、xml;
- 包含于在http报文的头(header)中
1. 带多个路由地址
views.py
# weather/wuhan/2020/
def weather(request, city, year):
print(city)
print(year)
return HttpResponse("%s-%s" % (city, year))
users\urls.py
from django.urls import path, re_path
urlpatterns = [
re_path(r'^weather/([a-z]+)/(\d{4})/$', views.weather),
]
2. 带查询字符串
views.py
# 带查询参数
def f_search(request):
a = request.GET.get("a")
b = request.GET.get("b")
print(a)
print(b)
# get获取的重复数据
a_list = request.GET.get_list('a')
print(a_list)
return HttpResponse("ok")
users\urls.py
from django.urls import path, re_path
urlpatterns = [
re_path(r'^f_search/$', views.f_search),
]
输入:
输出:
3. post请求 (通过软件进行测试)
(1). 请求体为表单数据
views.py
# 请求体
# p/
def post(request):
a = request.POST.get("a")
b = request.POST.get("b")
# 获取表单提交的重复数据
a_list = request.POST.getlist("a")
print(a)
print(b)
print(a_list)
# dict_test = {"a": 666}
# print(dict_test["b"]) - 报错
# print(dict_test.get("b", "缺省值")) - 返回None
# 综上建议使用get方法
return HttpResponse("ok")
users/urls.py
re_path(r'^p/$', views.post),
注释掉setting.py文件中的一行代码:
注意:post请求测试的时候,需要关闭csrf中间件
跳过注册,按照下列步骤,构建post请求体,进行发送请求操作
结果:
(2). 请求体为非表单数据
如:json,xml
不再是表单数据,而是类似于于python中字典的键值对的格式一样的数据(json中必须用双引号来标识数据)
views.py
# js/
def get_body_json(request):
json_str = request.body
json_str = json_str.decode # 不解码,json_str就为二进制
print(json_str)
req_data = json.loads(json_str)
# 没s文件对象
# 有s字符串或字典数据
print(type(req_data))
return HttpResponse("ok")
users/urls.py
re_path(r'^json/$', views.get_body_json),
构建json请求体:
结果:
二. 请求头
可以通过request.META属性获取请求头headers中的数据,request.META的类型为:dict
常见的请求头如下:
CONTENT_LENGTH
– The length of the request body (as a string). #请求正文的长度CONTENT_TYPE
– The MIME type of the request body.#正文的MIME类型。HTTP_ACCEPT
– Acceptable content types for the response.#响应的可接受内容类型HTTP_ACCEPT_ENCODING
– Acceptable encodings for the response.HTTP_ACCEPT_LANGUAGE
– Acceptable languages for the response.HTTP_HOST
– The HTTP Host header sent by the client.HTTP_REFERER
– The referring page, if any.#参考页,如果有的话。HTTP_USER_AGENT
– The client’s user-agent string.QUERY_STRING
– The query string, as a single (unparsed) string.REMOTE_ADDR
– The IP address of the client. #远程REMOTE_HOST
– The hostname of the client.REMOTE_USER
– The user authenticated by the Web server, if any.REQUEST_METHOD
– A string such as"GET"
or"POST"
. #请求的方法SERVER_NAME
– The hostname of the server.SERVER_PORT
– The port of the server (as a string).
使用方法,如:
def get_headers(request):
print(request.META['CONTENT_TYPE'])
return HttpResponse('OK')
三. 响应 - response
-
视图在接受请求并处理后,必须要返回HttpResponse对象或子对象。
-
HttpRequest对象由Django创建,HttpResponse对象由开发人员创建。
1. HttpResponse对象
(1). 可以使用django.http.HttpResponse来构建响应对象。
HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
(2). 可以使用HttpResponse对象属性来设置响应体、响应体数据类型和状态码。
- content:表示返回的内容
- code_status:表示返回的HTTP响应状态码
响应头可以直接将HttpResponse对象当做字典进行响应头键值对的设置:
response = HttpResponse()
# 自定义响应头属性'place',内容为'wuhan'
response['place'] = 'wuhan'
示例:
from django.http import HttpResponse
def demo_view(request):
return HttpResponse('Hello Django', status=400)
或者
response = HttpResponse('Hello Django')
response.code_status = 400
response['place'] = 'wuhan'
return response
2. HttpResponse对象的子类
Django提供了一系列HttpResponse的子类,可以快速设置状态码:
- HttpResponseRedirect 301
- HttpResponsePermanentRedirect 302
- HttpResponseNotModified 304
- HttpResponseBadRequest 400
- HttpResponseNotFound 404
- HttpResponseForbidden 403
- HttpResponseNotAllowed 405
- HttpResponseGone 410
- HttpResponseServerError 500
这种方法虽然便于观察,但写法麻烦,不建议使用
3.JsonResponse对象
若要返回json数据,可以使用JsonResponse来构造响应对象。
JsonResponse对象的作用:
- 帮助将数据转换成json字符串
- 设置响应头Content-Type为application/json
from django.http import JsonResponse
def demo_view(request):
return JsonResponse({'city':'wuhan', 'name':'lyh'})
四. redirect重定向
redirect(指定的页面地址)
from django.shortcuts import redirect
def demo_view(request):
return redirect('/index.html')