simplejson.errors.JSONDecodeError - python

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

Related

Getting error json.decoder.JSONDecodeError

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

InstaLoader simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I've been trying to fix this but couldn't find a fix anywhere, I'm using InstaLoader 4.5.5.
I am getting this error:
Traceback (most recent call last):
File "main.py", line 145, in <module>
attemptRoutine()
File "main.py", line 136, in attemptRoutine
routine()
File "main.py", line 90, in routine
scrapeVideos(username = IG_USERNAME,
File "/media/ubuntu/EE81-0482/Python/auto_Yt/scrape_videos.py", line 18, in scrapeVideos
L.login(username, password)
File "/home/ubuntu/.local/lib/python3.8/site-packages/instaloader/instaloader.py", line 483, in login
self.context.login(user, passwd)
File "/home/ubuntu/.local/lib/python3.8/site-packages/instaloader/instaloadercontext.py", line 224, in login
resp_json = login.json()
File "/usr/lib/python3/dist-packages/requests/models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3/dist-packages/simplejson/__init__.py", line 518, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3/dist-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/usr/lib/python3/dist-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)
I've been trying to scrape videos from meme pages for a youtube channel, Code taken from:
automated_youtube_channel Github

How do i correct JSONDecoderError?

import requests
I am trying to send data to an API which works fine but all of a sudden i start getting JSON error
This is the code
def payment(phone, receiver_phone, amount):
req_header = os.environ.get('APP_KEY')
payload = {
'receiver_phone': receiver_phone,
'amount': amount,
'payer_phone': phone
}
res = requests.post('https://sspay.com/payment?key={0}'.format(req_header), data=payload)
return res.json()
print(payment('07XXXXXX', '0XXXXXXXXX', '1'))
This is the output i get
Traceback (most recent call last):
File "test.py", line 25, in <module>
print(payment('07xxxxx', '09xxxxxxxx', '1'))
File "test.py", line 14, in payment
return res.json()
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/requests/models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/__init__.py", line 516, in loads
return _default_decoder.decode(s)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
use the code below - it will make you to find the issue
req_header = os.environ.get('APP_KEY')
res = requests.post('https://sspay.com/payment?key={0}'.format(req_header), data=payload)
if res.status_code == 200:
data = res.json()
return data
else:
print('We have a problem. status code : {}'.format(res.status_code))
you are not checking the API response (status code)
what if req_header is None

Convert MagicMock object to something I can use in my test

I'm not familiar with Python testing, particularly with using mocks so this may be completely wrong.
I have this code in my test:
import os
import mock
from mock import Mock
from tests import unittest
from datetime import datetime
from ibm_botocore.session import Session
import logging
class TestS3Parameters(unittest.TestCase):
def setUp(self):
super(TestS3Parameters, self).setUp()
# Set the config file to something that doesn't exist so
# that we don't accidentally load a config.
os.environ['AWS_CONFIG_FILE'] = '~/.aws/config-missing'
def create_session(self, *args, **kwargs):
"""
Create a new session with the given arguments. Additionally,
this method will set the credentials file to the test credentials
used by the following test cases.
"""
kwargs['session_vars'] = {
'credentials_file': (
None, None,
os.path.join(os.path.dirname(__file__), 'test-credentials'),
None)
}
return Session(*args, **kwargs)
#mock.patch('ibm_botocore.credentials.Credentials')
def test_extended_endpoint(self, my_mock):
now = datetime.utcnow().strftime("%Y%m%d")
extended_listing_mock_response_basic = {
"IsTruncated": False,
"Buckets": [
{
"Name": "bucketnamefoo",
"CreationDate": str(now),
"LocationConstraint": "bar-standard"
}
],
"Owner": {
"DisplayName": "ownerfoo",
"ID": "idfoo"
}
}
s = self.create_session()
client = s.create_client('s3', region_name='us-east-1', aws_access_key_id='foo',
aws_secret_access_key='bar')
# Create a mock response.
self.mock_response = Mock()
self.mock_response = extended_listing_mock_response_basic
request = my_mock.list_bucket()
self.assertEquals(request['httpRequest']['method'], 'GET')
self.assertEquals(request['httpRequest']['path'], '/?extended')
if __name__ == "__main__":
unittest.main()
When I run it I get this error:
Traceback (most recent call last):
File "/core/.tox/py33/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "/core/tests/unit/test_s3_param.py", line 56, in test_extended_endpoint
request = client.list_bucket()
File "/core/ibm_botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/core/ibm_botocore/client.py", line 648, in _make_api_call
operation_model, request_dict, request_context)
File "/core/ibm_botocore/client.py", line 667, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "/core/ibm_botocore/endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "/core/ibm_botocore/endpoint.py", line 132, in _send_request
request = self.create_request(request_dict, operation_model)
File "/core/ibm_botocore/endpoint.py", line 116, in create_request
operation_name=operation_model.name)
File "/core/ibm_botocore/hooks.py", line 356, in emit
return self._emitter.emit(aliased_event_name, **kwargs)
File "/core/ibm_botocore/hooks.py", line 228, in emit
return self._emit(event_name, kwargs)
File "/core/ibm_botocore/hooks.py", line 211, in _emit
response = handler(**kwargs)
File "/core/ibm_botocore/signers.py", line 90, in handler
return self.sign(operation_name, request)
File "/core/ibm_botocore/signers.py", line 157, in sign
auth.add_auth(request)
File "/core/ibm_botocore/auth.py", line 425, in add_auth
super(S3SigV4Auth, self).add_auth(request)
File "/core/ibm_botocore/auth.py", line 368, in add_auth
signature = self.signature(string_to_sign, request)
File "/core/ibm_botocore/auth.py", line 349, in signature
request.context['timestamp'][0:8])
File "/core/ibm_botocore/auth.py", line 169, in _sign
sig = hmac.new(key, msg.encode('utf-8'), sha256).digest()
File "/Users/me/.pyenv/versions/2.7.8/lib/python2.7/hmac.py", line 136, in new
return HMAC(key, msg, digestmod)
File "/Users/me/.pyenv/versions/2.7.8/lib/python2.7/hmac.py", line 75, in __init__
self.outer.update(key.translate(trans_5C))
TypeError: must be convertible to a buffer, not MagicMock
How do I convert this to a type I can use?
I tried using request = my_mock.list_bucket() but it give me this error:
AssertionError: <MagicMock name='Credentials.list_buckets_extended().__getitem__().__getitem__()' id='4459954832'> != 'GET'
What I'm trying to do is create a mock client which I can use for my list_bucket call. I then hope to check it to ensure the request is a GET and the /?extended endpoint is used.

POST request raises AssertionError

I'm doing a POST request to an API, the code looks like this:
#gen.coroutine
def call():
...
response = yield AsyncHTTPClient().fetch(
HTTPRequest(
url='https://api.mywebsite.com/v1/users',
headers=headers,
method='POST',
body=json.dumps(body),
validate_cert=False
)
)
print response, response.body
if __name__ == "__main__":
tornado.ioloop.IOLoop.current().run_sync(call)
The server responds first time with 201 Created and the second time with 200 OK.
But for that code I get this error for the first time. The second time works
Traceback (most recent call last):
File "t.py", line 49, in <module>
tornado.ioloop.IOLoop.current().run_sync(call)
File "/usr/lib/python2.7/dist-packages/tornado/ioloop.py", line 389, in run_sync
return future_cell[0].result()
File "/usr/lib/python2.7/dist-packages/tornado/concurrent.py", line 129, in result
raise_exc_info(self.__exc_info)
File "/usr/lib/python2.7/dist-packages/tornado/stack_context.py", line 302, in wrapped
ret = fn(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 574, in inner
self.set_result(key, result)
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 500, in set_result
self.run()
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 529, in run
yielded = self.gen.throw(*exc_info)
File "t.py", line 43, in call
validate_cert=False
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 520, in run
next = self.yield_point.get_result()
File "/usr/lib/python2.7/dist-packages/tornado/gen.py", line 409, in get_result
return self.runner.pop_result(self.key).result()
File "/usr/lib/python2.7/dist-packages/tornado/concurrent.py", line 131, in result
return super(TracebackFuture, self).result(timeout=timeout)
File "/usr/lib/python2.7/dist-packages/concurrent/futures/_base.py", line 401, in result
return self.__get_result()
File "/usr/lib/python2.7/dist-packages/concurrent/futures/_base.py", line 360, in __get_result
raise self._exception
AssertionError
Looks like you are using sync function HTTPRequest in future
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPResponse
def call():
response = None
http_client = AsyncHTTPClient()
try:
body = json.dumps(body)
response: HTTPResponse = yield http_client.fetch('https://api.mywebsite.com/v1/users', method='POST', body=str(body), headers=headers, request_timeout=5)
except Exception as e:
print('get_request error:{0}'.format(e))

Categories