Test django view which has post request - django

I am trying to test my django views which contain post request.
def save_movie(request):
'''
Fetch data and save to Movie model
data obtained from post request is a string so need to clean it and convert to json
'''
if request.method == 'POST':
movie_data = str(request.POST['movie_data'])
movie_data = movie_data.replace("\'","\"")
b=""
for i in range(len(movie_data)):
if movie_data[i] is "\"" and movie_data[i-1].isalpha() and movie_data[i+1].isalpha():
b+="\'"
else:
b+=movie_data[i]
json_data = json.loads(b)
new_movie, created = Movie.objects.get_or_create(title=json_data['title'], episode_id=int(json_data['episode_id']), opening_crawl=json_data['opening_crawl'], director=json_data['director'], producer=json_data['producer'], release_date=json_data['release_date'], characters=str(json_data['characters']), planets=str(json_data['planets']), starships=str(json_data['starships']), vehicles=str(json_data['vehicles']), species=str(json_data['species']), created=parse_datetime(json_data['created']), edited=parse_datetime(json_data['edited']), url=json_data['url'])
if created:
new_movie.save()
return HttpResponse('<h1>Movie Saved</h1>')
else:
return HttpResponse('<h1>Movie already Saved</h1>')
and test.py is
def test_save_movie(self):
response = self.client.post(self.save_movie_url, {'title':'test', 'episode_id':1, 'opening_crawl':'test for movie', 'director':'director', 'producer':'producer', 'release_date':'test_date', 'characters':'test_chars', 'planets':'test_planets', 'starships':'test_starships', 'vehicles':'str_vehicles', 'species':'str_species', 'created':'2014-12-09T13:50:49.641000Z', 'edited':'2015-12-09T13:50:49.641000Z', 'url':'https://test.com'})
print(response.status_code)
when i run this testcase i get MultiValueDictError
File "/home/abhishek/Desktop/SpotDraft/StarWars/favourites/tests/test_views.py", line 58, in test_save_movie
response = self.client.post(self.save_movie_url, {'title':'test', 'episode_id':1, 'opening_crawl':'test for movie', 'director':'director', 'producer':'producer', 'release_date':'test_date', 'characters':'test_chars', 'planets':'test_planets', 'starships':'test_starships', 'vehicles':'str_vehicles', 'species':'str_species', 'created':'2014-12-09T13:50:49.641000Z', 'edited':'2015-12-09T13:50:49.641000Z', 'url':'https://test.com'})
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/test/client.py", line 526, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **extra)
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/test/client.py", line 356, in post
secure=secure, **extra)
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/test/client.py", line 421, in generic
return self.request(**r)
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/test/client.py", line 496, in request
raise exc_value
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/abhishek/Desktop/SpotDraft/StarWars/favourites/views.py", line 109, in save_movie
movie_data = str(request.POST['movie_data'])
File "/home/abhishek/Desktop/SpotDraft/env/lib/python3.7/site-packages/django/utils/datastructures.py", line 78, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'movie_data'
It seems it cant find movie_data which should be present in my post request as the view extracts it from there
How to solve this?

Related

requests.post(url, data)error `Response`, `HttpResponse` or `HttpStreamingResponse` but received a `<class 'tuple'>`

I am doing my first Django MongoDB project and trying to save the data set in the database
here is the create method that I'm using
def create(self, request, *args, **kwargs):
try:
client = MongoClient('srv13.absolute.ag:27017')
collection = client.farmos.device
header = request.headers['Authorization']
req = json.loads(request.body)
resp = requests.post(url=f"{settings.MAINFLUX_URL}/things", data=req, params=args, headers=header)
device_id = resp.headers['Location'][8:]
req['device_token'] = device_id
collection.insert_one(req)
return {'data': 'Success'}, 200
except Exception as e:
return {'data': str(e)}, 400
But it showing an error
and the error is
Internal Server Error: /api/v1/device/
Traceback (most recent call last):
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/adarsh/farmos/farmos/persistance_layer/mongodb/device_operations.py", line 53, in create
response = requests.post(url=f"{settings.MAINFLUX_URL}/things", data=json.dumps(req), headers=header)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/api.py", line 117, in post
return request('post', url, data=data, json=json, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/sessions.py", line 515, in request
prep = self.prepare_request(req)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/sessions.py", line 453, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/models.py", line 319, in prepare
self.prepare_headers(headers)
File "/home/adarsh/farmos/venv/lib/python3.6/site-packages/requests/models.py", line 451, in prepare_headers
for header in headers.items():
AttributeError: 'str' object has no attribute 'items'
I think there is a problem in this line
python
resp = requests.post(url=f"{settings.MAINFLUX_URL}/things", data=req, params=args, headers=header)
I have tried different thing changing the type of req and header to solve it but couldn't do it

When trying to send a post request, a ZeroReturnError occurs

I use:
Python 2.7.6
ssl.OPENSSL_VERSION: 'OpenSSL 1.0.1f 6 Jan 2014'
I am communicating with a third party service which has TLSProtocol TLSV1.2.
I manage to successfully request an access token from the service.
It is also possible to send files to this service and pick up the names of these files assigned by the service.
Next, I generate data in json format and send it to this service. Here at this step I get ZeroReturnError.
It would be desirable to understand why connection is closed.
My guess is that this is because pyopenssl doesn't support TLS1.2 in python2.7.6.
But I doubt this guess, because the first request for a token and the second request for sending files pass.
My code:
def __init__(self):
self._logger = logging.getLogger("XXXXXXXX")
self._hostname = r'https://xxxxxx'
self._api = r'xxxxx'
self._client_id = 'xxxxxx'
self._secret = 'xxxxxx'
self._session = requests.session()
def get_token(self):
api_method = 'access_token'
url_get = r'{}/{}/{}/'.format(self._hostname, self._api, api_method)
payload = {'client_id': self._client_id, 'secret': self._secret}
response = self._session.get(url_get, params=payload, timeout=90, verify='/etc/cacert.pem')
self._logger.info('Request received successfully')
return response.json().get('token')
def send_files(self, owner_token=None, files=None):
api_method = 'file_upload'
url_post = r'{}/{}/{}/?token={}'.format(self._hostname, self._api, api_method, owner_token)
response = self._session.post(url_post, files=files, timeout=90, verify='/etc/cacert.pem')
self._logger.info('Files received successfully')
return response.json()
def send_data(self, owner_token=None, data=None):
api_method = 'submit_declaration'
url_post_data = r'{}/{}/{}/?token={}'.format(self._hostname, self._api, api_method, owner_token)
pattern = r'\{.*?\}'
response = self._session.post(url_post_data, data=data, timeout=90, verify='/etc/cacert.pem')
self._logger.info('Data received successfully')
result = re.findall(pattern, response.text)
if result:
return json.loads(result[0])
return
This is log:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 105, in get_response
response = middleware_method(request, callback, callback_args, callback_kwargs)
File "/var/www/*/common/timeit.py", line 13, in process_view
response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 48, in view
return self.dispatch(request, *args, **kwargs)
File "/var/www/*/common/mixins.py", line 727, in dispatch
return super(UserToSchoolMixin, self).dispatch(request, *args, **kwargs)
File "/var/www/*/common/mixins.py", line 201, in dispatch
return super(SelectedObjectWithProtection, self).dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py", line 69, in dispatch
return handler(request, *args, **kwargs)
File "/var/www/*/views.py", line 1089, in post
response = staff_request.send_data(owner_token=owner_token, data=json_data)
File "/var/www/*/helpers_reqeust.py", line 56, in send_data
response = self._session.post(url_post_data, data=data, timeout=90, verify='/etc/cacert.pem')
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 509, in post
return self.request('POST', url, data=data, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 467, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 570, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 394, in send
r.content
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 679, in content
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 616, in generate
decode_content=True):
File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 225, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 174, in read
data = self._fp.read(amt)
File "/usr/lib/python2.7/httplib.py", line 602, in read
s = self.fp.read(amt)
File "/usr/lib/python2.7/dist-packages/urllib3/contrib/pyopenssl.py", line 152, in read
data = self._sock.recv(left)
ZeroReturnError

create method is raising key error in serializer

I am creating an API for signup.
Serializers.py
class UserSignupSerializer(serializers.Serializer):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'role']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validate_data):
user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])
user.set_password(validate_data['password'])
user.save()
return user
Views.py
class UserSignupView(APIView):
def post(self, request):
serializer = UserSignupSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(status=status.HTTP_204_NO_CONTENT)
But this is giving key error 'email' or anything I put first in this line:
user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])
Edit
Error
Internal Server Error: /api/user_signup/
Traceback (most recent call last):
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 497, in dispatch
response = self.handle_exception(exc)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 457, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 468, in raise_uncaught_exception
raise exc
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 494, in dispatch
response = handler(request, *args, **kwargs)
File "D:\Django\FitnessProject\FitnessApp\fitness_api\views.py", line 187, in post
serializer.save()
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\serializers.py", line 213, in save
self.instance = self.create(validated_data)
File "D:\Django\FitnessProject\FitnessApp\fitness_api\serializers.py", line 85, in create
user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])
KeyError: 'email'
[2019-09-03 11:49:43,186] log: ERROR - Internal Server Error: /api/user_signup/
Traceback (most recent call last):
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 497, in dispatch
response = self.handle_exception(exc)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 457, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 468, in raise_uncaught_exception
raise exc
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\views.py", line 494, in dispatch
response = handler(request, *args, **kwargs)
File "D:\Django\FitnessProject\FitnessApp\fitness_api\views.py", line 187, in post
serializer.save()
File "D:\django\FitnessProject\fitness_venv\lib\site-packages\rest_framework\serializers.py", line 213, in save
self.instance = self.create(validated_data)
File "D:\Django\FitnessProject\FitnessApp\fitness_api\serializers.py", line 85, in create
user = User.objects.create(email=validate_data['email'], first_name=validate_data['first_name'],last_name=validate_data['last_name'], role='user', username=validate_data['username'])
KeyError: 'email'
[03/Sep/2019 11:49:43] "POST /api/user_signup/?username=user_4&last_name=user&first_name=user&email=u#gmail.com&password=user&role=user HTTP/1.1" 500 18553
I think you should use serializers.Modelserializer instead of serializers.Serializer.

IndexError: list index out of range in Test case

I have strange problems
I have next code Using TesCase and APIClient to get request with token
class Profile(TestCase):
fixtures = ['profiles.json']
def setUp(self):
self.client = APIClient()
self.user = Profile.objects.get(username='some-username')
self.token = Token.objects.create(user=self.user)
self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
def test_profile(self):
response = self.client.get('/api/some-username/profile/')
print(response.status_code)
print(response.data)`
Authorization goes well,but the I received error. If i use requests.get with headers (token) to development django server all pass well i receive a correct json response
Full Traceback when i run this test:
Traceback (most recent call last):
File "/home/work/project/profiles/tests.py", line 103, in test_user_profile
response = self.client.get('/api/some-username/profile/')
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 291, in get
response = super(APIClient, self).get(path, data=data, **extra)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 208, in get
return self.generic('GET', path, **r)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 237, in generic
method, path, data, content_type, secure, **extra)
File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 416, in generic
return self.request(**r)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 288, in request
return super(APIClient, self).request(**kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/test.py", line 240, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 501, in request
six.reraise(*exc_info)
File "/usr/local/lib/python3.5/dist-packages/django/utils/six.py", line 686, in reraise
raise value
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 489, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python3.5/dist-packages/rest_framework_tracking/mixins.py", line 69, in handle_exception
response = super(BaseLoggingMixin, self).handle_exception(exc)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 449, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/views.py", line 486, in dispatch
response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/generics.py", line 254, in get
return self.retrieve(request, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/mixins.py", line 58, in retrieve
return Response(serializer.data)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 533, in data
ret = super(Serializer, self).data
File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 500, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/home/work/project/profiles/serializers.py", line 10, in to_representation
return institute.all()[0].slug
File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 289, in __getitem__
return list(qs)[0]
IndexError: list index out of range
How know what is the problem?

Django 1.11 EmailMultiAlternatives: ValueError: need more than 1 value to unpack

Iam trying to send an email using EmailMultiAlternative. Using Django 1.11, Python 3.4. However I am getting ValueError. Am using the SMTP backend.This is the code:
subject = "Hi {} !".format(user.username)
sender = settings.DEFAULT_FROM_EMAIL
recipients = [user.email, ]
html_content = render_to_string('email/hello.html', {'url': url, 'first_name': user.first_name, 'last_name': user.last_name, 'static': HOST + settings.STATIC_URL,})
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
msg.attach_alternative(html_content, "text/html")
msg.send().
However I am get the following error:
ValueError: need more than 1 value to unpack
Complete traceback here:
Traceback (most recent call last):
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/views/generic/edit.py", line 183, in post
return self.form_valid(form)
File "/home/george/george/project/new_beco/applications/accounts/views.py", line 87, in form_valid
msg.send()
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/message.py", line 348, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages
sent = self._send(message)
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/backends/smtp.py", line 123, in _send
from_email = sanitize_address(email_message.from_email, encoding)
File "/home/george/virtuals/new_project/lib/python3.4/site-packages/django/core/mail/message.py", line 136, in sanitize_address
nm, addr = addr
ValueError: need more than 1 value to unpack