Django从curl

时间:2017-08-01 04:19:55

标签: django curl

我创建了一个函数,该函数应该从curl请求接收post数据并返回结果。我已经为视图禁用了csrf,因此我得到的错误是我无法解析json。

这是我的观点

@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

这意味着这不是从curl请求中读取json的最佳方式,如此

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

2 个答案:

答案 0 :(得分:0)

在您的情况下,request.body中没有数据,这就是它显示错误的原因,即request.POST方法中的数据,因此您可以在目录中加载请求.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')

答案 1 :(得分:0)

我后来发现卷曲请求中的输入并不是有效的格式化json,这是正确格式化的方式

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