参考文档:
https://docs.djangoproject.com/zh-hans/4.1/ref/request-response/#httpresponse-objects

请求对象 HttpRequest

请求头

  1. def get(self, request):
  2. return JsonResponse({'foo': 'bar'})
  3. if 'user-agent' not in request.headers:
  4. return HttpResponse('请求异常')
  5. return render(request, 'register.html')

请求参数

请求头:HttpRequest.META

  1. CONTENT_LENGTH :请求体的长度(字符串)
  2. CONTENT_TYPE :请求体的 MIME 类型
  3. HTTP_ACCEPT :可接受的响应内容类型
  4. HTTP_ACCEPT_ENCODING :可接受的响应编码
  5. HTTP_ACCEPT_LANGUAGE :可接受的响应语言
  6. HTTP_HOST :客户端发送的 HTTP 主机头
  7. HTTP_REFERER referrer 页面,如果有的话
  8. HTTP_USER_AGENT :客户端的用户代理字符串
  9. QUERY_STRING :查询字符串,是一个单一的(未解析的)字符串
  10. REMOTE_ADDR :客户机的 IP 地址
  11. REMOTE_HOST :客户机的主机名
  12. REQUEST_METHOD : "GET" "POST" 等字符串
  13. SERVER_NAME :服务器的主机名
  14. SERVER_PORT :服务器的端口(字符串)

请求头:HttpRequest.headers

  1. 一个不区分大小写的类似字典的对象,提供对请求中所有 HTTP 前缀头的访问
  2. (加上 Content-Length Content-Type
  3. 当显示每个请求头时,请求头名称都是用标题的形式来表示的(例如 User-Agent

请求参数:

  1. HttpRequest.method:代表请求中使用的 HTTP 方法的字符串。保证是大写字母。
  2. HttpRequest.GET:一个类似字典的对象,包含所有给定的 HTTP GET 参数。
  3. HttpRequest.POST:一个类似字典的对象,包含所有给定的 HTTP POST 参数,
  4. 前提是请求包含表单数据。
  5. HttpRequest.COOKIES:一个包含所有 cookies 的字典。键和值是字符串。
  6. HttpRequest.FILES
  7. 一个类似字典的对象,包含所有上传的文件。FILES 中的每个键是 <input type="file" name="">
  8. 中的 nameFILES 中的每个值是一个 UploadedFile
  9. FILES 只有在请求方法是 POST,并且发布请求的 <form>
  10. enctype="multipart/form-data" 的情况下,才会包含数据。
  11. 否则,FILES 将是一个类似字典的空白对象。

响应对象 HttpResponse

  1. from email import header
  2. from http.client import FORBIDDEN
  3. from django.http import HttpResponse, JsonResponse
  4. from django.shortcuts import render
  5. from django.views import View
  6. # Create your views here.
  7. def login(request):
  8. if request.method == "POST":
  9. username = request.POST.get('username', '')
  10. password = request.POST.get('password', '')
  11. # 业务逻辑判断
  12. headers = {
  13. 'token': 'andy123456'
  14. }
  15. # return HttpResponse(f"用户{username}的密码是{password}",
  16. # content_type="text/html; charset=utf-8",
  17. # status=200 ,headers=headers)
  18. res = {
  19. 'name': username,
  20. 'password': password,
  21. 'status': 200,
  22. 'message': 'OK'
  23. }
  24. return JsonResponse(res)
  25. elif request.method == 'GET':
  26. age = request.GET.get('age', '')
  27. gender = request.GET.get('gender', '')
  28. print(age, gender)
  29. print(request.COOKIES)
  30. return render(request, 'login.html')
  31. class RegisterView(View):
  32. def get(self, request):
  33. return render(request, 'register.html')
  34. def post(self, request):
  35. username = request.POST.get('username')
  36. password = request.POST.get('password')
  37. password2 = request.POST.get('password2')
  38. avart = request.FILES.get('avatar', '')
  39. print(avart)
  40. # 业务逻辑判断
  41. return HttpResponse(f"用户{username}的密码是{password}")