Getting MultiValueDictKeyError on Django while trying to receiving a stripe hook - python-3.x

I am getting a django.utils.datastructures.MultiValueDictKeyError while trying to receive a stripe signal when a subscription's charge fails,
Here is the traceback
Traceback (most recent call last):
File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/aditya/dev/cn/pmx_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/aditya/dev/cn/pmx_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/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback
return callback(request, *args, **kwargs)
File "/usr/lib/python3.7/contextlib.py", line 74, in inner
return func(*args, **kwds)
File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/zebra/views.py", line 38, in webhooks
request_data = json.loads(request.POST["request_data"])
File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/utils/datastructures.py", line 80, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'request_data'
[13/Nov/2021 09:36:29] "POST /zebra/webhooks/ HTTP/1.1" 500 121292
I am using
django 2.2
Python 3.7.12
Thanks in advance for any solutions and suggestions.

There is no need for json.loads, you can just use the request.POST.get() method like this
request_data = request.POST.get("request_data")
This will return a None value if there is no request_data key in the dictionary.

Related

Django rest Framework django.utils.datastructures.MultiValueDictKeyError: 'files'

I am trying to upload the image using the api but this error is displayed.
can anyone please tell me what is the problem.
Method Not Allowed: /scanner/batch-upload/
[09/Nov/2021 00:44:03] "GET /scanner/batch-upload/ HTTP/1.1" 405 8763
Internal Server Error: /scanner/batch-upload/
Traceback (most recent call last):
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/django/utils/datastructures.py", line 78, in __getitem__
list_ = super().__getitem__(key)
KeyError: 'files'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/rest_framework/generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/accounts/views.py", line 336, in create
file_path = request.FILES['files'].read()
File "/home/kali/Desktop/py_speedy_scanner_img2pdf/venv/lib/python3.9/site-packages/django/utils/datastructures.py", line 80, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'files'
[09/Nov/2021 00:44:07] "POST /scanner/batch-upload/ HTTP/1.1" 500 110792
I think this is because cannot find the file key in the request.Post .
Python dictionaries have an integrated static method .get() . When .get() cannot find a key, it returns the default None value or the value you specified.
I suggest using .get() . Here is an example.
Change the settings of the program
request.POST[""]
to
request.POST.get("", "default value")
In addition, there is no need to write {% csrf_token %} before each input field. For each form only one csrf_token is required. Thus, you can remove others, just store one inside the form tag.

'super' object has no attribute 'set_context'

I upgrade Django version from 1.11 to 3.2 and upgrade the installed python.
I am facing an error at this line
super().set_context(serializer_field)
Below is the Full class code.
class UniqueForProjectValidator(UniqueValidator):
def set_context(self, serializer_field):
super().set_context(serializer_field)
self.project = serializer_field.parent.context['project']
def filter_queryset(self, value, queryset):
queryset = queryset.filter(project=self.project)
return super().filter_queryset(value, queryset)
Here is the Error
Traceback (most recent call last):
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\viewsets.py", line 125, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\mixins.py", line 82, in partial_update
return self.update(request, *args, **kwargs)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\mixins.py", line 67, in update
serializer.is_valid(raise_exception=True)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py", line 419, in run_validation
value = self.to_internal_value(data)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\serializers.py", line 476, in to_internal_value
validated_value = field.run_validation(primitive_value)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\fields.py", line 799, in run_validation
return super().run_validation(data)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\fields.py", line 569, in run_validation
self.run_validators(value)
File "C:\Users\arauf\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\fields.py", line 587, in run_validators
validator.set_context(self)
File "C:\Users\arauf\Desktop\innerzone\NewCode\InnerZone-Backend\core\utils.py", line 213, in set_context
super().set_context(serializer_field)
AttributeError: 'super' object has no attribute 'set_context'
It seems you have possibly upgraded Django Rest Framework as well however on Django Rest Frameworks GitHub page, the method set_context does not exist. So your error is telling you, the method set_context on the parent class UniqueValidator does not exist.
See their GitHub page here.

function in Django behaves differently

I have a function named localtime(ltz, /) to calculate users' local time. Outside of Django it works, but I get localtime takes 0 positional arguments but 1 was given error inside of Django.
Here's the function
UTILITY.PY
def localtime(ltz, /):
utc_now = datetime.datetime.now(tz=pytz.UTC)
return utc_now.astimezone(pytz.timezone(ltz))
VIEWS.PY
....
qs = Users.objects.filter(id=self.request.user).values()
for val in qs:
local_time = localtime(val['time_zone'])
print(local_time)
....
Traceback (most recent call last):
File "../env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "../env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "../env/lib/python3.8/site-packages/django/views/generic/base.py", line 73, in view
return self.dispatch(request, *args, **kwargs)
File "../env/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "../env/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "../env/lib/python3.8/site-packages/django/views/generic/base.py", line 101, in dispatch
return handler(request, *args, **kwargs)
File "../env/lib/python3.8/site-packages/django/views/generic/edit.py", line 172, in post
return super().post(request, *args, **kwargs)
File "../env/lib/python3.8/site-packages/django/views/generic/edit.py", line 142, in post
return self.form_valid(form)
File "../users/views.py", line 148, in form_valid
local_tz = localtime(val['time_zone'])
Exception Type: TypeError at /timesheet/
Exception Value: localtime() takes 0 positional arguments but 1 was given
Can anyone help figure out why I'm getting localtime takes 0 positional arguments but 1 was given error in Django? Thank you in advance.

Cannot delete from datastore emulator

I have this simple piece of code:
from google.cloud import datastore
import requests
ds_c = datastore.Client(_http=requests.Session)
for entity in ds_c.query(kind='Kind').fetch():
ds_c.delete(entity.key)
I am getting:
google.api_core.exceptions.ResourceExhausted: 429 Received message larger than max (4207799 vs. 4194304)
Full stack trace:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/grpc/_channel.py", line 826, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/usr/local/lib/python3.7/dist-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.RESOURCE_EXHAUSTED
details = "Received message larger than max (4207799 vs. 4194304)"
debug_error_string = "{"created":"#1589308786.798030838","description":"Received message larger than max (4207799 vs. 4194304)","file":"src/core/ext/filters/message_size/message_size_filter.cc","file_line":191,"grpc_status":8}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/vagrant/.local/bin/fab", line 8, in <module>
sys.exit(program.run())
File "/home/vagrant/.local/lib/python3.7/site-packages/invoke/program.py", line 384, in run
self.execute()
File "/home/vagrant/.local/lib/python3.7/site-packages/invoke/program.py", line 566, in execute
executor.execute(*self.tasks)
File "/home/vagrant/.local/lib/python3.7/site-packages/invoke/executor.py", line 129, in execute
result = call.task(*args, **call.kwargs)
File "/home/vagrant/.local/lib/python3.7/site-packages/invoke/tasks.py", line 127, in __call__
result = self.body(*args, **kwargs)
File "/vagrant/cyclone/fabfile.py", line 34, in clean_test_datastore
for entity in ds_c.query(kind=kind).fetch():
File "/usr/local/lib/python3.7/dist-packages/google/api_core/page_iterator.py", line 212, in _items_iter
for page in self._page_iter(increment=False):
File "/usr/local/lib/python3.7/dist-packages/google/api_core/page_iterator.py", line 249, in _page_iter
page = self._next_page()
File "/usr/local/lib/python3.7/dist-packages/google/cloud/datastore/query.py", line 537, in _next_page
self._query.project, partition_id, read_options, query=query_pb
File "/usr/local/lib/python3.7/dist-packages/google/cloud/datastore_v1/gapic/datastore_client.py", line 384, in run_query
request, retry=retry, timeout=timeout, metadata=metadata
File "/usr/local/lib/python3.7/dist-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
on_error=on_error,
File "/usr/local/lib/python3.7/dist-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/usr/local/lib/python3.7/dist-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.ResourceExhausted: 429 Received message larger than max (4207799 vs. 4194304)
The easiest work around would be to fetch only the keys you are looking for, e.g. for entity in ds_c.query(kind='Kind').keys_only().fetch(): It's probably a good idea to add a limit to your fetch to reduce the size of the response, e.g. for entity in ds_c.query(kind='Kind').keys_only().fetch(limit=500):

python-telegram-bot doesn't work on Python 3.x

I'm trying to make a program that uses python-telegram-bot, and I need to use Python 3 for that. But when I try to launch it using Python 3, I get some error I don't quite understand. The same happens when I use the built-in examples. Could somebody explain what it means? The precise output of the program follows.
2016-06-29 06:17:44,260 - telegram.ext.updater - ERROR - unhandled exception
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/telegram/ext/updater.py", line 105, in _thread_wrapper
target(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/telegram/ext/updater.py", line 216, in _start_polling
self._bootstrap(bootstrap_retries, clean=clean, webhook_url='')
File "/usr/local/lib/python3.4/dist-packages/telegram/ext/updater.py", line 320, in _bootstrap
self.bot.setWebhook(webhook_url=webhook_url, certificate=cert)
File "/usr/local/lib/python3.4/dist-packages/telegram/bot.py", line 121, in decorator
result = func(self, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/telegram/bot.py", line 1263, in setWebhook
result = request.post(url, data, timeout=kwargs.get('timeout'))
File "/usr/local/lib/python3.4/dist-packages/telegram/utils/request.py", line 174, in post
headers={'Content-Type': 'application/json'})
File "/usr/local/lib/python3.4/dist-packages/telegram/utils/request.py", line 100, in _request_wrapper
resp = _get_con_pool().request(*args, **kwargs)
File "/usr/lib/python3/dist-packages/urllib3/request.py", line 72, in request
**urlopen_kw)
File "/usr/lib/python3/dist-packages/urllib3/request.py", line 135, in request_encode_body
**urlopen_kw)
TypeError: urlopen() got multiple values for keyword argument 'body'
Exception in thread updater:
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 920, in _bootstrap_inner
self.run()
File "/usr/lib/python3.4/threading.py", line 868, in run
self._target(*self._args, **self._kwargs)
File "/usr/local/lib/python3.4/dist-packages/telegram/ext/updater.py", line 105, in _thread_wrapper
target(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/telegram/ext/updater.py", line 216, in _start_polling
self._bootstrap(bootstrap_retries, clean=clean, webhook_url='')
File "/usr/local/lib/python3.4/dist-packages/telegram/ext/updater.py", line 320, in _bootstrap
self.bot.setWebhook(webhook_url=webhook_url, certificate=cert)
File "/usr/local/lib/python3.4/dist-packages/telegram/bot.py", line 121, in decorator
result = func(self, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/telegram/bot.py", line 1263, in setWebhook
result = request.post(url, data, timeout=kwargs.get('timeout'))
File "/usr/local/lib/python3.4/dist-packages/telegram/utils/request.py", line 174, in post
headers={'Content-Type': 'application/json'})
File "/usr/local/lib/python3.4/dist-packages/telegram/utils/request.py", line 100, in _request_wrapper
resp = _get_con_pool().request(*args, **kwargs)
File "/usr/lib/python3/dist-packages/urllib3/request.py", line 72, in request
**urlopen_kw)
File "/usr/lib/python3/dist-packages/urllib3/request.py", line 135, in request_encode_body
**urlopen_kw)
TypeError: urlopen() got multiple values for keyword argument 'body'
2016-06-29 06:17:45,248 - telegram.ext.dispatcher - CRITICAL - stopping due to exception in another thread
For this to work, install urllib3>=1.10 from the package manager.

Resources