Django---请求与响应

利用HTTP协议向服务器传参的四种方式:

URL路径参数

a:未命令参数按定义顺序传递

url(r'^weather/(a-z]+)/(\d{4})/$', views.weather)

def  weather(request, city, year):

  print('city=%s' % city)

  print('year=%s' % year)

  return HttpResponse("ok")

未定义时,参数需要一一对应

b:命名参数按名字传递

url(r'^weather/(?P<city>[a-z]+)/(?P<year>\d{4})$', views.weather)

def weather(request, year, city):

  

  print('city=%s' % city)

  print('year=%s' % year)

  return HttpResponse("ok")

不需要一一对应,参数名称对上即可

Django中的QueryDict对象

定义在django.http.QueryDict

HttpRequest对象的属性GET,POST都是QueryDict类型的对象

与python字典不同,QueryDict类型的对象用来处理同一个键带有多个值的情况

方法get():根据键获取值

  如果一个键同时拥有多个值获取最后一个值

  如果键不存在则返回None值,可以设置默认值进行后续处理

  dict.get('键', 默认值)  可简写:dict['键']

方法getlist():根据键获取值,值以列表返回,可以设置默认值进行后续处理

  dict.getlist('键',默认值)

查询字符串Query String

获取请求路径中的查询字符串参数(形如?k1=v1&k2=v2), 可以通过request.GET属性获取,返回QueryDict对象

def   get(request):

  get_dict = request.GET

  # ?a=10&b=python

  a = get_dict.get('a')

  b = get_dict.get('b')

  print(type(a))

  print(b)

  return JsonResponse({'data':'json'})

def  post1(request):

  post_dict = request.POST

  a = post_dict.get("a")

  b = post_dict.get("b")

  print(a)

  print(b)

  return JsonResponse({"data":"json"})

请求体

请求体数据格式不固定,可以是JSON字符串,可以是XML字符串,应区别对待.

可以发送请求数据的请求方式有: POST, PUT, PATCH,DELETE.

Django默认开启csrf防护,会对上述请求方式进行csrf防护验证,在测试时可以关闭csrf防护机制,

表单类型Form  Data

前端发送的表单类型的请求数据,可以通过request.POST属性获取,返回QueryDict对象.

非表单类型的请求体数据,Django无法自动解析,可以通过request.boby属性获取最原始的请求数据,再解析,response.boby返回bytes类型

def  boby(request):

  # 获取非表单数据,类型bytes

  json_bytes = request.boby

  # 转字符串

  json_str = json_bytes.decode()

  # json.dumps() ===> 将字典转字符串

  # json.loads() == > 将字符串转字典

  json_dict = json.loads(json_str)

  print(type(json_dict))

  print(json_dict.get('a'))

  print(json_dict('b'))

  return HttpResponse('boby')

  请求头:

可以通过request.META属性获取请求heades中的数据,request.META为字典类型

常见的请求头如下:

  • CONTENT_LENGTH – The length of the request body (as a string).
  • CONTENT_TYPE – The MIME type of the request body.
  • 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).

  

猜你喜欢

转载自www.cnblogs.com/zhouzetian/p/9853543.html