如何在django中正确传递JSON

时间:2017-07-15 12:01:23

标签: python json django

我正在为我的django应用程序编写视图测试。 该视图接受POST请求。它应该是JSON数据。我已经用Postman对它进行了测试,但是当我尝试在不运行的test.py中传递它时,说JSON必须用双引号括起来。事情是双引号。我究竟做错了什么?检查下面的代码。谢谢!

views.py

"""This registration app-module generates views for register and auth pages."""

from json import loads
from django.http import HttpResponse
from django.contrib import auth
from django.core.exceptions import ValidationError
from django.core.validators import validate_email

from .models import CustomUser


def register(request):
    """
    Registration method for CustomUser registration.
    Args:
        request: http request.
    Returns:
        If new user gets successfully registered - returns HttpResponse(201).
        If not - returns HttpResponse(400).
    """

    if request.method == 'POST':
        data = loads(request.body.decode('utf-8'))
        email = data["email"]
        password = data["password"]

        if CustomUser.get_by_email(email) is None:
            try:
                validate_email(email)
                CustomUser.create(email, password)
                return HttpResponse("User successfully created.", status=201)
            except ValidationError:
                return HttpResponse("This email is not valid format.", status=400)
        return HttpResponse("This email is already registered.", status=400)

    return HttpResponse(status=400)

tests.py

from django.test import TestCase
from django.urls import reverse

from registration.models import CustomUser

class RegisterViewTests(TestCase):
    """
    Test CustomUser model methods.
    """

    def test_create(self):
        """
        Test CustomUser.create().
        """

        response = self.client.post(reverse('register_view'),
                                            {"email": "test@gmail.com", "password": "secret"},
                                            content_type='application/json')
        self.assertEqual(response.status_code, 201)

错误

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_create (tests.test_registration.RegisterViewTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/metal/Documents/projects/myTrip/myTrip/tests/test_registration.py", line 120, in test_create
    content_type='application/json')
  File "/home/metal/Documents/projects/myTrip/venv/lib/python3.6/site-packages/django/test/client.py", line 548, in post
    secure=secure, **extra)
  File "/home/metal/Documents/projects/myTrip/venv/lib/python3.6/site-packages/django/test/client.py", line 350, in post
    secure=secure, **extra)
  File "/home/metal/Documents/projects/myTrip/venv/lib/python3.6/site-packages/django/test/client.py", line 416, in generic
    return self.request(**r)
  File "/home/metal/Documents/projects/myTrip/venv/lib/python3.6/site-packages/django/test/client.py", line 501, in request
    six.reraise(*exc_info)
  File "/home/metal/Documents/projects/myTrip/venv/lib/python3.6/site-packages/django/utils/six.py", line 686, in reraise
    raise value
  File "/home/metal/Documents/projects/myTrip/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/metal/Documents/projects/myTrip/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/metal/Documents/projects/myTrip/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/metal/Documents/projects/myTrip/myTrip/registration/views.py", line 23, in register
    data = loads(request.body.decode('utf-8'))
  File "/home/metal/.pyenv/versions/3.6.1/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/home/metal/.pyenv/versions/3.6.1/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/home/metal/.pyenv/versions/3.6.1/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

----------------------------------------------------------------------
Ran 1 test in 0.049s

FAILED (errors=1)
Destroying test database for alias 'default'...

1 个答案:

答案 0 :(得分:1)

@Rajan Chahan的评论。 在你的tests.py中 加 代码顶部的import json。并将您的代码修改为:

class RegisterViewTests(TestCase):
"""
Test CustomUser model methods.
"""

def test_create(self):
    """
    Test CustomUser.create().
    """

    response = self.client.post(reverse('register_view'),
                                        json.dumps({"email": "test@gmail.com", "password": "secret"}),
                                        content_type='application/json')
    self.assertEqual(response.status_code, 201)

json.dumps会将python dict转储到json对象