2017-05-23 2 views
1

Ich versuche meine Anmelde-URL zu testen. Wenn ich folgendes mache, gibt es einen Fehler.JSON-Dekodierfehler beim Senden der Postanforderung während des Testens

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}) 

Es gibt mir die folgende Fehlermeldung:

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 

Das ist mein 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'), 
] 

Das ist mein views.py

ist
@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 Ich habe versucht mit json.loads und json.dump und versuchte auch mit doppelten Anführungszeichen anstelle von einfachen Anführungszeichen. Es funktioniert nicht.

+0

versuchen, einfache Anführungszeichen in doppelte Anführungszeichen zu ersetzen. – latsha

+0

@latsha Versuchte das. Funktioniert immer noch nicht. Versuchte auch, mit json dumping. – user2507

+0

welche django version verwendest du? – latsha

Antwort

2

Der Fehler kommt von der Anmeldeansicht in Zeile data = json.loads(data). Um die POST Daten zugreifen, die Sie einfach request.POST unter Verwendung von zugreifen können:

data = request.POST 

Also diese Zeilen entfernen und mit über Codezeile ersetzen:

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

Oder versuchen (wie über heraus Diskussion):

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

Ich brauchte request.body, da ich diese Daten über ein mobiles Gerät gesendet habe. Die POST-Anfragedaten sind nicht in request.POST gekommen – user2507

+0

Versuchen Sie, 'request.body' zu drucken, was Sie bekommen? Bitte poste keine sensiblen Informationen wie echten Benutzernamen und Passwort oder E-Mail. –

+0

Ich bekomme ein JSON-Objekt der Daten als Parameter in der POST-Anfrage gesendet. Alles funktioniert einwandfrei, wenn ich Daten über POSTMAN oder ein mobiles Gerät sende. Es bricht beim Testen. – user2507

Verwandte Themen