use*_*001 7 django rest json django-rest-framework
我试图通过Django REST框架实现一个简单的GET/POST api
views.py
class cuser(APIView):
def post(self, request):
stream = BytesIO(request.DATA)
json = JSONParser().parse(stream)
return Response()
Run Code Online (Sandbox Code Playgroud)
urls.py
from django.conf.urls import patterns, url
from app import views
urlpatterns = patterns('',
url(r'^challenges/',views.getall.as_view() ),
url(r'^cuser/' , views.cuser.as_view() ),
)
Run Code Online (Sandbox Code Playgroud)
我正在尝试POST
一些json /api/cuser/
(api是我项目中的命名空间urls.py
),JSON
{
"username" : "abhishek",
"email" : "john@doe.com",
"password" : "secretpass"
}
Run Code Online (Sandbox Code Playgroud)
我尝试了从Browseable API页面和httpie
(类似于curl的python制作工具)
httpie command
http --json POST http://localhost:58601/api/cuser/ username=abhishek email=john@doe.com password=secretpass
Run Code Online (Sandbox Code Playgroud)
但我得到JSON解析错误:
JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Run Code Online (Sandbox Code Playgroud)
Whole Debug message using --verbose --debug
POST /api/cuser/ HTTP/1.1
Content-Length: 75
Accept-Encoding: gzip, deflate
Host: localhost:55392
Accept: application/json
User-Agent: HTTPie/0.8.0
Connection: keep-alive
Content-Type: application/json; charset=utf-8
{"username": "abhishek", "email": "john@doe.com", "password": "aaezaakmi1"}
HTTP/1.0 400 BAD REQUEST
Date: Sat, 24 Jan 2015 09:40:03 GMT
Server: WSGIServer/0.1 Python/2.7.9
Vary: Accept, Cookie
Content-Type: application/json
Allow: POST, OPTIONS
{"detail":"JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"}
Run Code Online (Sandbox Code Playgroud)
您遇到的问题是您的请求已被解析,并且您正尝试再次解析它.
视图的有效解析器集始终定义为类列表.当
request.data
被访问时,REST框架将检查传入请求的Content-Type头,并确定要使用到解析请求其内容解析器.
在您正在访问的代码中request.DATA
,这是2.4.x等效的代码request.data
.因此,只要您调用它,您的请求就会被解析,并且request.DATA
实际上正在返回您希望解析的字典.
json = request.DATA
Run Code Online (Sandbox Code Playgroud)
实际上你需要解析传入的JSON数据.你真的传递了一个Python字典json.loads
,它似乎无法解析它,这就是你得到错误的原因.
我通过Google到达了该帖子,标题为““ detail”:“ JSON解析错误-期望属性名称用双引号引起来:”。结果,您在JSON中无法使用逗号结尾。因此,如果您遇到此错误,则可能需要更改这样的帖子:
{
"username" : "abhishek",
"email" : "john@doe.com",
"password" : "secretpass",
}
Run Code Online (Sandbox Code Playgroud)
对此:
{
"username" : "abhishek",
"email" : "john@doe.com",
"password" : "secretpass"
}
Run Code Online (Sandbox Code Playgroud)
请注意,JSON对象中最后一个属性后的逗号已删除。
归档时间: |
|
查看次数: |
16164 次 |
最近记录: |