在测试期间发送post请求时JSON解码错误

时间:2017-05-23 06:13:14

标签: json django django-testing

我正在尝试测试我的注册网址。当我执行以下操作时,它会给我一个错误。

tests.py

from __future__ import unicode_literals
from django.test import TestCase
# Create your tests here.
class SignUpTest(TestCase):
    def test_createAccount(self):
        import pdb; pdb.set_trace()
        response = self.client.post('/signup/', {'username': 'test_username', 'password': 'test_password',"email":"example@gmail.com", "confirm_password":"test_password", "type_of_user":"1", "first_name":"john", "last_name":"doe"})
        print response
        self.assertIs(response, {"success":True})

它给了我以下错误:

Internal Server Error: /signup/
Traceback (most recent call last):
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/akashtomar/Desktop/repo/onlinestore/portal/views.py", line 20, in signup
    data = json.loads(data)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/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
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/test/client.py", line 548, in post
    secure=secure, **extra)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/test/client.py", line 350, in post
    secure=secure, **extra)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/test/client.py", line 416, in generic
    return self.request(**r)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/test/client.py", line 501, in request
    six.reraise(*exc_info)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/akashtomar/.virtualenvs/wingify/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/akashtomar/Desktop/repo/onlinestore/portal/views.py", line 20, in signup
    data = json.loads(data)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/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

这是我的urls.py

from django.conf.urls import url
from django.contrib import admin
from portal.views import *
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^signup/',signup,name='signup'),
    url(r'^addproduct/',addProduct,name='addproduct'),
    url(r'^logout/',logout,name='logout'),
    url(r'^login/',login,name='login'),
    url(r'^deleteproduct/',deleteProduct,name='deleteproduct'),
    url(r'^search/',search,name='search'),
    url(r'^update/',update,name='update'),
    url(r'^getproduct/',getProduct,name='getproduct'),
]

这是我的views.py

@csrf_exempt
def signup(request):
    if request.method=='POST':
        data = request.body
        data = json.loads(data)
        username = data["username"]
        email = data["email"]
        password = data["password"]
        confirm_password = data["confirm_password"]
        first_name = data["first_name"]
        last_name = data["last_name"]
        type_of_user = data["type_of_user"]

        if password!=confirm_password:
            return JsonResponse({"success":False,"reason":"passwords don't match"})
        user = User(username=username,email=email,first_name=first_name,last_name=last_name)
        user.set_password(password)
        user.is_active=True
        try:
            user.save()
        except:
            return JsonResponse({"success":False,"reason":"user already exists"})

        user_a=authenticate(username=username,password=password)
        if user_a is not None:
            if user_a.is_active:
                log(request,user_a)
        else:
            return HttpResponse({"success":False,"reason":"internal db error"});

        access_token = str(uuid.uuid4().get_hex())
        try:
            # import pdb; pdb.set_trace()
            at = AccessToken(token_value=access_token)
            at.save()
            UserProfile(user=user,type_of_user=int(type_of_user),access_token=at).save()
        except:
            return JsonResponse({"success":False,"reason":"internal error"})
        return JsonResponse({"success":True,"access_token":access_token})

P.S我尝试过使用json.loadsjson.dump,并尝试使用双引号而不是单引号。它不起作用。

2 个答案:

答案 0 :(得分:4)

错误来自第data = json.loads(data)行的注册视图。 要访问POST数据,您只需使用request.POST

即可访问该数据
data = request.POST

所以删除这些行并替换为上面的代码行:

data = request.body
data = json.loads(data)

或尝试(通过讨论得出):

response = self.client.post('/signup/', json.dumps(my_data), content_type='application/json')

答案 1 :(得分:0)

如果打印(使用) response.json() 时出错 而不是 response.json() 使用 response.data

response = self.client.get(url, data)
print(response.json()) # if cause 'json.decoder.JSONDecodeError', use response.data