参考文档:
https://docs.djangoproject.com/zh-hans/4.1/ref/request-response/#httpresponse-objects
请求对象 HttpRequest
请求头
def get(self, request):
return JsonResponse({'foo': 'bar'})
if 'user-agent' not in request.headers:
return HttpResponse('请求异常')
return render(request, 'register.html')
请求参数
请求头:HttpRequest.META
CONTENT_LENGTH :请求体的长度(字符串)
CONTENT_TYPE :请求体的 MIME 类型
HTTP_ACCEPT :可接受的响应内容类型
HTTP_ACCEPT_ENCODING :可接受的响应编码
HTTP_ACCEPT_LANGUAGE :可接受的响应语言
HTTP_HOST :客户端发送的 HTTP 主机头
HTTP_REFERER :referrer 页面,如果有的话
HTTP_USER_AGENT :客户端的用户代理字符串
QUERY_STRING :查询字符串,是一个单一的(未解析的)字符串
REMOTE_ADDR :客户机的 IP 地址
REMOTE_HOST :客户机的主机名
REQUEST_METHOD : "GET" 或 "POST" 等字符串
SERVER_NAME :服务器的主机名
SERVER_PORT :服务器的端口(字符串)
请求头:HttpRequest.headers
一个不区分大小写的类似字典的对象,提供对请求中所有 HTTP 前缀头的访问
(加上 Content-Length 和 Content-Type)
当显示每个请求头时,请求头名称都是用标题的形式来表示的(例如 User-Agent)
请求参数:
HttpRequest.method:代表请求中使用的 HTTP 方法的字符串。保证是大写字母。
HttpRequest.GET:一个类似字典的对象,包含所有给定的 HTTP GET 参数。
HttpRequest.POST:一个类似字典的对象,包含所有给定的 HTTP POST 参数,
前提是请求包含表单数据。
HttpRequest.COOKIES:一个包含所有 cookies 的字典。键和值是字符串。
HttpRequest.FILES:
一个类似字典的对象,包含所有上传的文件。FILES 中的每个键是 <input type="file" name="">
中的 name。FILES 中的每个值是一个 UploadedFile。
FILES 只有在请求方法是 POST,并且发布请求的 <form> 有
enctype="multipart/form-data" 的情况下,才会包含数据。
否则,FILES 将是一个类似字典的空白对象。
响应对象 HttpResponse
from email import header
from http.client import FORBIDDEN
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
# Create your views here.
def login(request):
if request.method == "POST":
username = request.POST.get('username', '')
password = request.POST.get('password', '')
# 业务逻辑判断
headers = {
'token': 'andy123456'
}
# return HttpResponse(f"用户{username}的密码是{password}",
# content_type="text/html; charset=utf-8",
# status=200 ,headers=headers)
res = {
'name': username,
'password': password,
'status': 200,
'message': 'OK'
}
return JsonResponse(res)
elif request.method == 'GET':
age = request.GET.get('age', '')
gender = request.GET.get('gender', '')
print(age, gender)
print(request.COOKIES)
return render(request, 'login.html')
class RegisterView(View):
def get(self, request):
return render(request, 'register.html')
def post(self, request):
username = request.POST.get('username')
password = request.POST.get('password')
password2 = request.POST.get('password2')
avart = request.FILES.get('avatar', '')
print(avart)
# 业务逻辑判断
return HttpResponse(f"用户{username}的密码是{password}")