Django请求和响应

问题描述

请求和响应

请求HttpRequest

视图函数的第一个参数,即HttpRequest对象

request.GET
request.POST
request.FILES

request.path_info  # url信息
request.get_full_path()  # 请求的完整路径

request.META  # 消息头(元数据、请求头)
request.META['REMOTE_ADDR']  # 客户端IP地址
request.headers
request.body

request.scheme #请求协议(http/https)
request.method

request.COOKIES
request.session

GET请求

产生get请求的场景

  • 浏览器url地址栏
  • < a href=“地址?参数=值&参数=值” >
  • form表单中设置method为get

取值

  • request.GET[‘参数名’]
  • request.GET.get(‘参数名’, ‘默认值’)
  • request.GET.getlist(‘参数名’)

POST请求

取值

  • request.POST[‘参数名’]
  • request.POST.get(‘参数名’, ‘默认值’)
  • request.POST.getlist(‘参数名’)

请求判断

if request.method == 'GET':
    # 操作get请求内容
else request.method == 'POST':
    # 操作post请求内容
......

响应HttpResponse

from django.shortcuts import HttpResponse  # 快捷导入from django.http import HttpResponse

HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

content_type

参数名 响应体数据类型
‘text/html’ 默认,html文件
‘text/plain’ 纯文本
‘text/css’ css文件
‘text/javascript’ js文件
‘multipart/form-data’ 文件提交
‘application/json’ json传输
‘application/xml’ xml文件

HttpResponse子类

from django.http import xxx
类型 作用 状态码
HttpResponseRequest 重定向 302
HttpResponseNotModified 未修改 304
HttpResponseBadRequest 错误请求 400
HttpResponseNotFound 没有对应的资源 404
HttpResponseForbidden 请求被禁止 403
HttpResponseServerError 服务器错误 500

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)