在测试过程中发送post请求时出现JSON解码错误

3
我正在尝试测试我的注册链接。当我执行以下操作时,它会给我一个错误。
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})

补充说明:我已经尝试过使用json.loadsjson.dump,并尝试使用双引号代替单引号,但都无法正常工作。


尝试将单引号替换为双引号。 - latsha
@latsha 尝试过了。仍然不起作用。也尝试使用json进行转储。 - Akash Tomar
你正在使用哪个版本的Django? - latsha
请提供完整的异常回溯信息,包括您的 urls.py 文件中包含 /signup/ 模式以及包含其视图的 views.py 文件。如果上述代码只是为了解释错误而编写的,请同时展示您的真实测试用例代码。 - Aamir Rind
@latsha django 1.11 - Akash Tomar
@AamirAdnan 请检查我的代码。 - Akash Tomar
3个回答

8
错误来自注册视图的第 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')

我需要使用request.body,因为我是通过移动设备发送这些数据的。POST请求数据不在request.POST中。 - Akash Tomar
尝试打印request.body,你得到了什么?请不要发布敏感信息,如真实用户名、密码或电子邮件。 - Aamir Rind
尝试在测试中使用以下代码:response = self.client.post('/signup/', json.dumps(my_data), content_type='application/json') - Aamir Rind
是的,需要明确设置“content_type”。 - Akash Tomar
如果我想将授权作为请求参数,那么这种格式正确吗?response = self.client.post('/addproduct/', json.dumps(my_data), content_type='application/json',Authorization=self.access_token) - Akash Tomar
显示剩余2条评论

0

我也曾卡在这里。使用 dict() 而不是 json。

data = dict(request.POST)['checkedbox']
result = list(map(int, data))

1
请添加更多细节来解释您的答案,为什么需要进行这个修复? - YLR
你好!老实说,我在使用 json.loads(request.body) 时遇到了错误,其他方法也没有为我解决问题(我在 StackOverflow 上搜索了类似的问题)。然后我想到了使用 dict()。从哈希表中获取值,我们可以使用 .get()[]。然后我们需要将这些值转换为整数(因为它们是用于进一步过滤的 ID),默认情况下它们是字符串,因为它们来自 URL。 - SleeplessChallenger

0

如果你在打印(使用)response.json()时出现错误,可以尝试使用response.data。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接