2017-05-23 2 views
1

가입 URL을 테스트하려고합니다. 다음과 같이하면 오류가 발생합니다.테스트 중에 게시 요청을 보내는 동안 JSON 디코딩 오류가 발생했습니다.

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":"[email protected]", "confirm_password":"test_password", "type_of_user":"1", "first_name":"john", "last_name":"doe"}) 
     print response 
     self.assertIs(response, {"success":True}) 

그것은 나에게 다음과 같은 오류 제공 : 이것은 내 urls.py입니다

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 

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을 사용해 보았으며 작은 따옴표 대신 큰 따옴표를 사용해 보았습니다. 그것은 작동하지 않습니다.

+0

작은 따옴표를 큰 따옴표로 바꾸십시오. – latsha

+0

@latsha 그걸 시도했다. 아직도 작동하지 않습니다. 또한 json을 사용하여 덤프를 시도했습니다. – user2507

+0

django 버전을 사용하고 계십니까? – latsha

답변

2

data = json.loads(data)의 가입보기에서 오류가 발생했습니다.

data = request.POST 

그래서이 라인을 제거하고 코드 위의 라인을 교체 :

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

을 또는 통해 파악로 (시도 단순히 request.POST를 사용하여 액세스 할 수 POST 데이터에 액세스하기 위해 토론) :

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

모바일 장치를 통해이 데이터를 전송할 때부터 request.body가 필요했습니다. POST 요청 데이터가 요청에 오지 않았습니다 .POST – user2507

+0

'request.body'를 인쇄 해보십시오. 실제 사용자 이름 및 암호 또는 전자 메일과 같은 중요한 정보를 게시하지 마십시오. –

+0

POST 요청에서 매개 변수로 전송 된 데이터의 json 객체를 가져옵니다. POSTMAN 또는 모바일 장치를 통해 데이터를 보내면 모든 것이 잘 작동합니다. 테스트하는 동안 휴식. – user2507