首页 > 解决方案 > 访问请求数据对象

问题描述

我将以下帖子数据发送到 django Rest API

Request URL: http://localhost:8000/polls/
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8100
Content-Length: 90
Content-Type: text/html; charset=utf-8
Date: Mon, 18 Jun 2018 11:01:54 GMT
Server: WSGIServer/0.2 CPython/3.6.5
Vary: Origin
X-Frame-Options: SAMEORIGIN
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 83
content-type: text/plain
Host: localhost:8000
Origin: http://localhost:8100
Referer: http://localhost:8100/
User-Agent: Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Mobile Safari/537.36


   
0:
{id: "1", username: "admin", password: "admin", user_group_id: "1", status: "1"}

此处发送的内容将首先根据保存在数据库中的内容进行身份验证。我正在尝试访问这些数据,但没有这样做。当我使用 json parse 处理数据时

情况1。

def dunction(request)
data = json.loads(request.body.decode("utf-8"))
vak=data
return HttpResponse(vak)

然后收到以下响应

{'id': '1', 'username': 'admin', 'password': 'admin', 'user_group_id': '1', 'status': '1'}

case 2. 操作相同代码时

data = json.loads(request.body.decode("utf-8"))
vak=data[0]
return HttpResponse(vak)

收到回复

idusernamepassworduser_group_idstatus

案例 3。

def dunction(request):
  data = json.loads(request.body.decode("utf-8"))
  vak=data.username
  return HttpResponse(vak)

抛出错误'list' object has no attribute 'username'

仅供参考,我在这里尝试创建一个自定义身份验证功能,该功能对 userData 进行身份验证,然后将数据发送回服务器。

 'DEFAULT_AUTHENTICATION_CLASSES':  
    'polls.authentication.UserAuthentication',

标签: djangodjango-rest-framework

解决方案


HttpResponse 需要一个可迭代的。您正在向它传递实际上是可迭代的各种东西:在第一种情况下,是一个列表,因此它会打印该列表中的(唯一)条目,这是一个字典;在第二种情况下,你传递给它一个字典,所以它遍历只给出键的字典。在第三种情况下,由于某种原因,您尝试使用对象表示法来访问列表内的 dict 的键,这根本不起作用。

我不确定您的实际问题是什么,但如果您确实想访问您需要的用户名data[0]['username']

请注意,尽管 DRF 的目的是抽象出很多这些东西。您应该使用内置功能而不是执行任何此类操作。


推荐阅读