2017-08-01 74 views
1

我創建了一個應該從curl請求接收發布數據並返回結果的函數。我禁用了視圖的csrf,所以我得到的錯誤是我無法解析json。Django從curl接收發布結果

這是我的看法

@csrf_exempt 
def create_user(request): 
    response = {'status': None} 

    if request.method == 'POST': 
     data = json.loads(request.body) 
     ... 

我得到的終端

Internal Server Error: /api-user-create/ 
Traceback (most recent call last): 
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response 
    response = self.process_exception_by_middleware(e, request) 
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response 
    response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view 
    return view_func(*args, **kwargs) 
File "/home/samuel/Documents/code/binabikers/delivery/views.py", line 14, in create_user 
    data = json.loads(request.body) 
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads 
    return _default_decoder.decode(s) 
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode 
    raise ValueError("No JSON object could be decoded") 
ValueError: No JSON object could be decoded 
[01/Aug/2017 03:58:24] "POST /api-user-create/ HTTP/1.1" 500 85347 

這意味着這不是讀捲曲請求JSON這樣

curl -X POST -d "username=john&password=john2&[email protected]&first_name=john&last_name=smith" http://localhost:8000/api-user-create/ 

回答

0
最好的辦法對這個錯誤

你可以試試這個,

if request.method == 'POST': 
     data = json.loads(request.POST) 
0

在你的情況下,有在request.body沒有數據,這就是爲什麼它的示值誤差,在request.POST方法的數據,這樣你就可以目錄request.POST內容加載到JSON格式,也可以使用

request.POST.get("your parameter") 

1. if requset.method =="POST": 
    data = json.loads(request.POST) 
2. if requset.method =="POST": 
    rg = request.POST.get 
    print (rg('your parameter') 

0

我後來發現,在輸入上捲曲的要求在這裏無效格式的JSON的方式正確格式化

curl -X POST -d '{"user-type": "user", "username":"john", "password":"john2", "email": "[email protected]", "f", "last-name":"smith"}' http://localhost:8000/api-user-create/