Getting error json.decoder.JSONDecodeError - python

Here's the full traceback of the error I am getting:
ERROR 2022-11-08 13:29:54,926: Internal Server Error: /voice_chat/rooms
Traceback (most recent call last):
File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 451, in thread_handler
raise exc_info[1]
File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 38, in inner
response = await get_response(request)
File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 233, in _get_response_async
response = await wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 414, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "C:\Users\15512\anaconda3\lib\asyncio\tasks.py", line 455, in wait_for
return await fut
File "C:\Users\15512\anaconda3\lib\concurrent\futures\thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 455, in thread_handler
return func(*args, **kwargs)
File "C:\Users\15512\anaconda3\lib\site-packages\django\views\generic\base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
request_body = json.loads(decode_request)
File "C:\Users\15512\anaconda3\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\15512\anaconda3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\15512\anaconda3\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
ERROR 2022-11-08 13:29:54,959: HTTP POST /voice_chat/rooms 500 [0.32, 127.0.0.1:54258]
This is my code:
def post(self, request, *args, **kwargs):
decode_request = request.body.decode("utf-8")
print('decoded request body', decode_request)
request_body = json.loads(decode_request)
# print('request body', request_body)
room_name = request_body.get("roomName")
participant_label = request_body["participantLabel"]
# print('username', curr_username)
response = VoiceResponse()
dial = Dial()
dial.conference(
name=room_name,
participant_label=participant_label,
start_conference_on_enter=True,
)
response.append(dial)
return HttpResponse(response.to_xml(), content_type="text/xml")
Here is a sample of what I'm posting:
{"roomName":"testingUseremmanuelS21","participantLabel":"emmanuelS21","matchedUser":"testingUser"}
This is what I have in decode_request
AccountSid=***&ApiVersion=2010-04-01&ApplicationSid=***&CallSid=CAf4e
***&CallStatus=ringing&Called=&Caller=client%3AemmanuelS21&Direction=inbound&From=client%3AemmanuelS21&To=&participantLabel=emmanuelS21&roomName=testingUseremmanuelS21

Related

Call Celery Inspect from Django fails on every 2 requests with a "not enough values to unpack (expected 2, got 1)"

I am calling the following code from a django view (taken from https://docs.celeryq.dev/en/latest/userguide/workers.html#inspecting-workers):
inspect_report = celery_app.control.inspect()
tasks_active = inspect_report.active()
It works correctly the first time but when I refresh the page i get a ValueError: not enough values to unpack (expected 2, got 1)
Stacktrace:
File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 458, in thread_handler
raise exc_info[1]
File "/venv_path/python3.9/site-packages/django/core/handlers/exception.py", line 38, in inner
response = await get_response(request)
File "/venv_path/python3.9/site-packages/django/core/handlers/base.py", line 233, in _get_response_async
response = await wrapped_callback(request, *callback_args, **callback_kwargs)
File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 423, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "/home/benjamin/.pyenv/versions/3.9.6/lib/python3.9/asyncio/tasks.py", line 442, in wait_for
return await fut
File "/venv_path/python3.9/site-packages/asgiref/current_thread_executor.py", line 22, in run
result = self.fn(*self.args, **self.kwargs)
File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 462, in thread_handler
return func(*args, **kwargs)
File "/venv_path/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/venv_path/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/benjamin/project/administration/views.py", line 357, in dashboard
tasks_active = inspect_report.active()
File "/venv_path/python3.9/site-packages/celery/app/control.py", line 149, in active
return self._request('active', safe=safe)
File "/venv_path/python3.9/site-packages/celery/app/control.py", line 106, in _request
return self._prepare(self.app.control.broadcast(
File "/venv_path/python3.9/site-packages/celery/app/control.py", line 741, in broadcast
return self.mailbox(conn)._broadcast(
File "/venv_path/python3.9/site-packages/kombu/pidbox.py", line 344, in _broadcast
return self._collect(reply_ticket, limit=limit,
File "/venv_path/python3.9/site-packages/kombu/pidbox.py", line 386, in _collect
self.connection.drain_events(timeout=timeout)
File "/venv_path/python3.9/site-packages/kombu/connection.py", line 317, in drain_events
return self.transport.drain_events(self.connection, **kwargs)
File "/venv_path/python3.9/site-packages/kombu/transport/virtual/base.py", line 969, in drain_events
get(self._deliver, timeout=timeout)
File "/venv_path/python3.9/site-packages/kombu/transport/redis.py", line 526, in get
ret = self.handle_event(fileno, event)
File "/venv_path/python3.9/site-packages/kombu/transport/redis.py", line 508, in handle_event
return self.on_readable(fileno), self
File "/venv_path/python3.9/site-packages/kombu/transport/redis.py", line 504, in on_readable
chan.handlers[type]()
File "/venv_path/python3.9/site-packages/kombu/transport/redis.py", line 905, in _brpop_read
dest, item = dest__item
ValueError: not enough values to unpack (expected 2, got 1)
3rd page call is OK, 4th give same error, etc.
Why does it fail every 2 requests?

error : json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

stock_df = pd.DataFrame()
stock = []
stock = yf.download(ticker, start= start_date, end= end_date, progress= False)
stock_df= stock_df.append(stock, sort= False)
stock_df['Symbol'] = ticker
Exception in thread Thread-4:
Traceback (most recent call last):
File "/opt/anaconda3/envs/learn-env/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/opt/anaconda3/envs/learn-env/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/opt/anaconda3/envs/learn-env/lib/python3.8/site-packages/multitasking/__init__.py", line 102, in _run_via_pool
return callee(*args, **kwargs)
File "/opt/anaconda3/envs/learn-env/lib/python3.8/site-packages/yfinance/multi.py", line 166, in _download_one_threaded
data = _download_one(ticker, start, end, auto_adjust, back_adjust,
File "/opt/anaconda3/envs/learn-env/lib/python3.8/site-packages/yfinance/multi.py", line 178, in _download_one
return Ticker(ticker).history(period=period, interval=interval,
File "/opt/anaconda3/envs/learn-env/lib/python3.8/site-packages/yfinance/base.py", line 155, in history
data = data.json()
File "/opt/anaconda3/envs/learn-env/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/opt/anaconda3/envs/learn-env/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/opt/anaconda3/envs/learn-env/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/opt/anaconda3/envs/learn-env/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Python API asyncio error - traceback script error

I made a script with a friend, unluckily the script does not run smoothly. It fails at some point and gives the following error:
Traceback (most recent call last):
File "restClient.py", line 157, in <module>
loop.run_until_complete(task)
File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "restClient.py", line 142, in func
available = client.getStockAmount(_product)
File "/root/brandcanyon/BrandCanyonApi/client.py", line 269, in getStockAmount
productId, productVariantId = self.findProductIdAndVariantId(product.name, product.size)
File "/root/brandcanyon/BrandCanyonApi/client.py", line 168, in findProductIdAndVariantId
product = self.getProductById(productId)
File "/root/brandcanyon/BrandCanyonApi/client.py", line 136, in getProductById
product = response.json()['data']
File "/usr/local/lib/python3.7/dist-packages/requests/models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The restClient.py File that the script is talking about is the following:
while True:
for product in page1:
for variant in product.attributes['variants']:
print(variant.attributes)
print(product.attributes['title'])
print(variant.attributes['option2'])
_product = Product(
name = product.attributes['title'],
size = variant.attributes['option2']
)
shopify.InventoryLevel.set(
location_id = location_id,
inventory_item_id = variant.inventory_item_id,
available = client.getStockAmount(_product)
)
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
if page1.has_next_page():
page1 = page1.next_page()
else:
break
print("Inventory Updated - Waiting 350 seconds for next Update")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
await asyncio.sleep(20)
loop = asyncio.get_event_loop()
task = loop.create_task(func())
try:
loop.run_until_complete(task)
except asyncio.CancelledError:
pass
Do you know the error? Can you help me out?
Thank you so much!

How to fix: 'TypeError: expected string or bytes-like object' when doing unit test on a views.py function

I'm writing a test for a function that returns a JSONResponse. The function works fine on the website but the test always raises a TypeError. It looks like the program fails to get an entry from the database and returns an error instead.
views.py:
def check_availability(request, id):
if request.method == "GET":
response_data = {}
event_date = request.GET.get('event_date', False)
check = None
try:
try:
speaker = Pembicara.objects.get(id = id)
filtered = Booking.objects.filter(speaker = speaker)
check = filtered.get(event_date = event_date)
except ObjectDoesNotExist as e:
pass
except Exception as e:
raise e
if not check:
response_data['available'] = 'ok'
else:
response_data['available'] = 'no'
except Exception as e:
raise e
return JsonResponse(response_data)
tests.py:
def test_date_availability_is_checked(self):
p = self.createPembicara()
c = Client()
date = datetime.date.today()
# request = c.get('/profile/1/check_availability/', event_date=date)
b = self.createBooking()
request = c.get('/profile/1/check_availability/', event_date='1999-12-20')
self.assertEqual(request.status_code, 200)
self.assertJSONEqual(request.content, {'available': 'ok'})
terminal:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
./Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/whitenoise/base.py:116: UserWarning: No directory at: /Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/BookaSpeakers/static/
warnings.warn(u"No directory at: {}".format(root))
E.......
======================================================================
ERROR: test_date_availability_is_checked (speaker_profile.tests.ProfileTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/tests.py", line 69, in test_date_availability_is_checked
request = c.get('/profile/1/check_availability/', event_date='2000-12-20')
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 535, in get
response = super().get(path, data=data, secure=secure, **extra)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 347, in get
**extra,
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/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 "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/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 "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 53, in check_availability
raise e
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 47, in check_availability
raise e
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 43, in check_availability
check = filtered.get(event_date = event_date)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
clone = self.filter(*args, **kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
split_subq=split_subq, simple_col=simple_col,
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1270, in get_prep_value
return self.to_python(value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1232, in to_python
parsed = parse_date(value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/utils/dateparse.py", line 74, in parse_date
match = date_re.match(value)
TypeError: expected string or bytes-like object
----------------------------------------------------------------------
Ran 9 tests in 0.211s
FAILED (errors=1)
Destroying test database for alias 'default'...
Any help would be appreciated, thank you!
The error likely happens because event_date ends up with the value False, which happens because there was no value for 'event_date' in request.GET.
According to the docs of Client.get(), you have to pass a dict with the GET/POST parameters of the request, not using kwargs.
Try by changing this line (which is using kwargs):
request = c.get('/profile/1/check_availability/', event_date='1999-12-20')
to this (now using a dict as the second parameter)
request = c.get('/profile/1/check_availability/', {'event_date': '1999-12-20'})

simplejson.errors.JSONDecodeError

I am trying to call API from postman but I am getting an error in my console.
In the below code, I am trying to decode it and process further according to it.
API- https://localhost:5005/abc/xyz
Method- POST
Data - {"q":"hi"}
server.py
def request_parameters(request):
if request.method.decode('utf-8', 'strict') == 'GET':
return {
key.decode('utf-8', 'strict'): value[0].decode('utf-8',
'strict')
for key, value in request.args.items()}
else:
content = request.content.read()
try:
return json.loads(content.decode('utf-8', 'strict'))
except ValueError as e:
logger.error("Failed to decode json during respond request. "
"Error: {}. Request content: "
"'{}'".format(e, content))
raise
Full stacktrace
Failed to decode json during respond request. Error: Expecting value: line 1 column 1 (char 0). Request content: 'b'''
2019-05-14 18:21:53+0530 [-] Unhandled Error
Traceback (most recent call last):
File "C:\Anaconda3\lib\site-packages\twisted\web\server.py", line 258, in render
body = resrc.render(self)
File "C:\Anaconda3\lib\site-packages\klein\resource.py", line 210, in render
d = defer.maybeDeferred(_execute)
File "C:\Anaconda3\lib\site-packages\twisted\internet\defer.py", line 151, in maybeDeferred
result = f(*args, **kw)
File "C:\Anaconda3\lib\site-packages\klein\resource.py", line 204, in _execute
**kwargs)
--- <exception caught here> ---
File "C:\Anaconda3\lib\site-packages\twisted\internet\defer.py", line 151, in maybeDeferred
result = f(*args, **kw)
File "C:\Anaconda3\lib\site-packages\klein\app.py", line 128, in execute_endpoint
return endpoint_f(self._instance, *args, **kwargs)
File "C:\Anaconda3\lib\site-packages\klein\app.py", line 227, in _f
return _call(instance, f, request, *a, **kw)
File "C:\Anaconda3\lib\site-packages\klein\app.py", line 50, in _call
result = f(*args, **kwargs)
File "server.py", line 61, in parse
request_params = request_parameters(request)
File "server.py", line 22, in request_parameters
return json.loads(content.decode('utf-8', 'strict'))
File "C:\Anaconda3\lib\site-packages\flask\json\__init__.py", line 205, in loads
return _json.loads(s, **kwargs)
File "C:\Anaconda3\lib\site-packages\simplejson\__init__.py", line 535, in loads
return cls(encoding=encoding, **kw).decode(s)
File "C:\Anaconda3\lib\site-packages\simplejson\decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "C:\Anaconda3\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
script.js
function respond(msg) {
data = {
query: msg //msg is getting from chatbot
}
fetch(`${url}/conversations/default/respond`, {
mode: 'no-cors',
method: 'POST',
// dataType:'jsonp',
q: data,
headers: {
'Content-Type': 'application/json',
},
})
You can get the content directly in json with request.get_json()

Categories