Getting ValueError: while using encrypt and decrypt using Django and Python - python

I am getting the following error while trying to encrypt my string type value.
Error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/lampp/htdocs/d30/carClinic_vulnerable/bookingservice/views.py", line 141, in signsave
obj = AES.new('this is a carkey123', AES.MODE_CBC, 'This is an IV456')
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/AES.py", line 94, in new
return AESCipher(key, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/AES.py", line 59, in __init__
blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/Crypto/Cipher/blockalgo.py", line 141, in __init__
self._cipher = factory.new(key, *args, **kwargs)
ValueError: AES key must be either 16, 24, or 32 bytes long
Here is my code:
name = request.POST.get('uname')
obj = AES.new('this is a carkey123', AES.MODE_CBC, 'This is an IV456')
enpass = obj.encrypt(name)

The answer is in plain letters in the error message:
"AES key must be either 16, 24, or 32 bytes long".
Your key ('this is a carkey123') is 19 bytes long, use a key that's either 16, 24 or 32 bytes long instead.

Related

How pass parameter in this method?

Hello I'm newbie Python user.
I study now django queryset. but
query.pyi in _BaseQuerySet's method
def values(self, *fields: Union[str, Combinable], **expressions: Any) -> ValuesQuerySet[_T, Dict[str, Any]]: ...
I want to pass a parameter to that function, but the first code runs, but the second code does not.
here is error code
valuelist = ("col1", "col2")
comment = Comment.objects.annotate(col1=F("contents"), col2=F("comment_depth")).values(valuelist)
and showed up if above code run
Traceback (most recent call last):
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\viewsets.py", line 114, in view
return self.dispatch(request, *args, **kwargs)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "D:\djangostudy\DjangoStudy\member\views.py", line 79, in memberlistrlist nt_depth")).values(valuelist)
comment = Comment.objects.annotate(col1=F("contents"), col2=F("commes\query.py", line 841, in valuesment_depth")).values(valuelist)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\query.py", line 836, in _valuesels\query.py", line 841, in values
clone = self._values(*fields, **expressions)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\query.py", line 836, in _values
clone.query.set_values(fields)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\sql\query.py", line 2172, in set_values
self.add_fields(field_names, True)
File "D:\Ryan\conda\envs\djangostudy\lib\site-packages\django\db\models\sql\query.py", line 1863, in add_fields
join_info = self.setup_joins(name.split(LOOKUP_SEP), opts, alias, allow_many=allow_m2m)
ttributeError: 'tuple' object has no attribute 'split'
14/Mar/2021 19:14:09] "GET /member/memberlist/ HTTP/1.1" 500 116044
not error code
comment = Comment.objects.annotate(col1=F("contents"), col2=F("comment_depth")).values("col1", "col2")
What should I do to get it running normally?
The error is in the .values(…) clause: you can not pass a tuple as parameter. You use iterable unpack to unpack the values of an iterable as individual parameters. This is done by putting an asterisk (*) in front:
Comment.objects.annotate(
col1=F('contents'),
col2=F('comment_depth')
).values(*valuelist)
That being said, often it is not a good idea to work with .values(…) [Django-doc] since it "erodes" the model layer.

TypeError: object of type 'JsonResponse' has no len() when return the json values

TypeError: object of type 'JsonResponse' has no len() when return the json values.But print (dicts) and print( json.dumps(dicts)),it shows the values ,but when the return the JsonResponse(json.dumps(dicts), safe=False) shows an error like 'TypeError: object of type 'JsonResponse' has no len()',how to solve this problem.
Error
Internal Server Error: /api/v2/usernewslist/
Traceback (most recent call last):
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\viewsets.py",
line 116, in view
return self.dispatch(request, *args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 495, in dispatch
response = self.handle_exception(exc)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 492, in dispatch
response = handler(request, *args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\mixins.py",
line 42, in list
page = self.paginate_queryset(queryset)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\generics.py", line 173, in paginate_queryset
return self.paginator.paginate_queryset(queryset, self.request, view=self)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\pagination.py", line 204, in paginate_queryset
self.page = paginator.page(page_number)
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\core\paginator.py",
line 57, in page
number = self.validate_number(number)
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\core\paginator.py",
line 46, in validate_number
if number > self.num_pages:
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\utils\functional.py",
line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\core\paginator.py",
line 91, in num_pages
if self.count == 0 and not self.allow_empty_first_page:
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\duklr\Duklr-web\venv\lib\site-packages\django\core\paginator.py",
line 84, in count
return len(self.object_list)
TypeError: object of type 'JsonResponse' has no len()
[29/Feb/2020 14:10:22] "GET /api/v2/usernewslist/ HTTP/1.1" 500 20471
Views.py
class UserNewsListingListViewSet(MobileNewsListViewSet):
def get_queryset(self):
queryset = self.queryset.filter(publish=True)
queryset = queryset.exclude(news_summary='')
# Filter News Provider
if self.request.GET.get('user_id'):
queryset = queryset.filter(posted_by__id=self.request.GET.get('user_id'))
# Filter News Category
if self.request.GET.get('news_type'):
queryset = queryset.filter(news_category__slug=self.request.GET.get('news_type'))
dicts = []
for query in queryset[:6]:
id = query.id
newstitle = query.news_title
news_summary = query.news_summary
slug = query.slug
news_image = query.news_image
news_provider = query.news_provider
news_page_url = query.news_page_url
newsdate = query.news_datetime
likescount = query.likes_count
mobile_news_summary = query.mobile_news_summary
for cat in query.news_category.all():
news_category = cat.news_category
data = {
"id":id,
"newstitle":newstitle,
"news_categories":news_category,
"news_summary":news_summary,
"slug":slug,
"news_image":news_image,
"news_provider":{
"id":query.news_provider.id,
"news_providers": query.news_provider.news_provider,
"url":query.news_provider.url,
"region":query.news_provider.region,
"image":str(query.news_provider.image),
"descriptions":query.news_provider.description,
"followers":query.news_provider.followers,
"slug":query.news_provider.slug,
"created_time":query.news_provider.created_time,
"publish":query.news_provider.publish
},
"news_page_url":news_page_url,
"newsdate":newsdate,
"likescount":likescount,
"mobile_news_summary":mobile_news_summary
}
# dat=json.dumps(data)
dicts.append(data)
return JsonResponse(json.dumps(dicts), safe=False)
When return the dicts , it shows an error like,
Traceback (most recent call last):
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\django\views\decorators\csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\viewsets.py",
line 116, in view
return self.dispatch(request, *args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 495, in dispatch
response = self.handle_exception(exc)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\views.py",
line 492, in dispatch
response = handler(request, *args, **kwargs)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\mixins.py",
line 45, in list
return self.get_paginated_response(serializer.data)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\serializers.py", line 768, in data
ret = super(ListSerializer, self).data
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\serializers.py", line 686, in to_representation
self.child.to_representation(item) for item in iterable
File "C:\duklr\Duklr-web\venv\lib\site-
packages\rest_framework\serializers.py", line 530, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\relations.py",
line 542, in to_representation
for value in iterable
File "C:\duklr\Duklr-web\venv\lib\site-packages\rest_framework\relations.py",
line 272, in to_representation
return value.pk
AttributeError: 'unicode' object has no attribute 'pk'
[02/Mar/2020 12:37:15] "GET /api/v2/usernewslist/ HTTP/1.1" 500 20224
when code changed
class UserNewsListingListViewSet(MobileNewsListViewSet):
def get_queryset(self):
queryset = self.queryset.filter(publish=True)
queryset = queryset.exclude(news_summary='')
# Filter News Provider
if self.request.GET.get('user_id'):
queryset = queryset.filter(posted_by__id=self.request.GET.get('user_id'))
# Filter News Category
if self.request.GET.get('news_type'):
queryset = queryset.filter(news_category__slug=self.request.GET.get('news_type'))
dicts = []
for query in queryset[:6]:
id = query.id
newstitle = query.news_title
news_summary = query.news_summary
slug = query.slug
news_image = query.news_image
news_provider = query.news_provider
news_page_url = query.news_page_url
newsdate = query.news_datetime
likescount = query.likes_count
mobile_news_summary = query.mobile_news_summary
for cat in query.news_category.all():
news_category = cat.id
data = {
"id":str(id),
"newstitle":str(newstitle),
"news_category":str(news_category),
"news_summary":str(news_summary),
"slug":str(slug),
"news_image":str(news_image),
"news_provider":{
"id":str(query.news_provider.id),
"news_providers": str(query.news_provider.news_provider),
"url":str(query.news_provider.url),
"region":str(query.news_provider.region),
"image":str(query.news_provider.image),
"descriptions":str(query.news_provider.description),
"followers":str(query.news_provider.followers),
"slug":str(query.news_provider.slug),
"created_time":str(query.news_provider.created_time),
"publish":str(query.news_provider.publish)
},
"news_page_url":str(news_page_url),
"newsdate":str(newsdate),
"likescount":str(likescount),
"mobile_news_summary":str(mobile_news_summary)
}
dat = json.dumps(data)
dicts.append(dat)
return dicts
It shows an error like this,
Traceback:
Traceback (most recent call last):
File "/home/test/.local/lib/python2.7/site-
packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/test/.local/lib/python2.7/site-
packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/test/.local/lib/python2.7/site-
packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args,
**callback_kwargs)
File "/home/test/.local/lib/python2.7/site-
packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/viewsets.py", line 116, in view
return self.dispatch(request, *args, **kwargs)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/mixins.py", line 45, in list
return self.get_paginated_response(serializer.data)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/serializers.py", line 768, in data
ret = super(ListSerializer, self).data
file "/home/test/.local/lib/python2.7/site-
packages/rest_framework/serializers.py", line 262, in data
self._data = self.to_representation(self.instance)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/serializers.py", line 686, in
to_representation
self.child.to_representation(item) for item in iterable
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/serializers.py", line 517, in
to_representation
attribute = field.get_attribute(instance)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/relations.py", line 536, in get_attribute
relationship = get_attribute(instance, self.source_attrs)
File "/home/test/.local/lib/python2.7/site-
packages/rest_framework/fields.py", line 101, in get_attribute
instance = getattr(instance, attr)
AttributeError: 'str' object has no attribute 'news_category'
First parameter for JsonResponse takes a dict. You are passing in json.dumps which will return a converted string corresponding to your dicts list. Use something like
JsonResponse({'data':dicts}, safe=False)
If your code's indent is not wrong, you have a logical error.In your second for loop for cat in query.news_category.all() change news_category variable, but it doesn't inserted anywhere .

too many values to unpack (expected 2) - Dictionary to JSON

I have a big dictionary with more than 50 items. I am trying to return this dictionary in the form of JSON.
The code for that is:-
return HttpResponse(json.dumps(responseData, indent = 0, default=str), content_type="application/json")
There are some date fields in the dictionary and so I mentioned default=str to convert them to string.
When I print the json.dumps, I do see proper values present in the json. But when I put it in HttpResponse, I get the below error:-
too many values to unpack (expected 2)
Could somebody tell me why exactly its happening and what is the workaround?
EDIT:- TRACEBACK
Internal Server Error: /ScApp2/home/App20/Details/
Traceback (most recent call last):
File "\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "\PythonWorkspace\ScApp\ScApp2\views.py", line 88, in ModelDetails
cmsPointScore = PspstCmspointscore.objects.filter(model_id)
File "\Python\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "\Python\Python37\lib\site-packages\django\db\models\query.py", line 836, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "\Python\Python37\lib\site-packages\django\db\models\query.py", line 854, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1277, in _add_q
split_subq=split_subq,
File "\Python\Python37\lib\site-packages\django\db\models\sql\query.py", line 1150, in build_filter
arg, value = filter_expr
ValueError: too many values to unpack (expected 2)
The error is in your query (that's why I asked for the traceback):
cmsPointScore = PspstCmspointscore.objects.filter(model_id)
You should add the field name to the filter expression, for example:
cmsPointScore = PspstCmspointscore.objects.filter(model_id=model_id)

TypeError: ufunc 'ndtri' not supported for the input types

How can I fix the following error?
I am trying to calucalte normsINV value.. But facing issue when i use it in my code for application
Internal Server Error: /reports/rschighlevel/
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/pulsedev2/prod/pulse.corp.uber.internal/ats/reports/views.py", line 167, in rschighlevel
print norm.ppf(a)
File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 1514, in ppf
place(output, cond, self._ppf(*goodargs) * scale + loc)
File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 2187, in _ppf
return _norm_ppf(q)
File "/usr/lib/python2.7/dist-packages/scipy/stats/distributions.py", line 2133, in _norm_ppf
return special.ndtri(q)
TypeError: ufunc 'ndtri' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'
Here's my code:
from scipy.stats import norm
from scipy.special import ndtri
import pdb
sigma = []
for i in usigma:
a = (1-i[6])
print type(a)
print norm.ppf(a) - Error Line
sigma.append([i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7], a])
print sigma
I use Python 2.7 and Django.
error message

How to pass two same arguments via python subprocess?

I wanted to pass two parameter in the subprocess call... like this...
./buildbot sendchange --branch=poky --property=buildname:nice --property=machine:qemux86
So I wrote the below program...
# property_name = {'key': 'value'}
y = ['--property={}:{}'.format(key, value) for key, value in property_name.items()]
cmd = [
'./buildbot', 'sendchange',
'--branch={}'.format(
branch),
y
]
And above command throws error by subprocess!
Traceback (most recent call last):
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/channels/handler.py", line 227, in process_exception_by_middleware
return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/iaskin/Workspace/buildsys/build_app/views.py", line 93, in home
property_name=property_name
File "/home/iaskin/Workspace/buildsys/build_app/helper/build_agent.py", line 50, in submit_buildbot
output = subprocess.Popen(cmd, cwd=bb_master_dir)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
TypeError: execv() arg 2 must contain only strings
So I changed the above code to this
y = ['--property={}:{}'.format(key, value) for key, value in property_name.items()]
cmd = [
'./buildbot', 'sendchange', '--master=bsp-buildvm:9999',
'--branch={}'.format(
branch),
"{}".format(' '.join(y))
]
And this is I don't want ...
./buildbot sendchange --branch=poky "--property=buildname:nice --property=machine:qemux86"
So am I doing anything wrong ? Or Is subprocess really doesn't allow this then what are the other alternatives ?
In parent process save argument as environment variables. Child process can access it.

Categories