flask application: trying to jsonify a dictionary - python

Background Info
I'm trying to write my first flask / python REST API. So far, I have a GET that connects to a redis database and tries to convert a dictionary to json... and then return those results.
Problem
When I try to call jsonify on my dict object, it fails with the following error:
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/var/www/localhost/htdocs/widgets/widgets.py", line 51, in get_profile
return jsonify(res_dict)
File "/usr/lib/python3.6/site-packages/flask/json.py", line 263, in jsonify
(dumps(data, indent=indent, separators=separators), '\n'),
File "/usr/lib/python3.6/site-packages/flask/json.py", line 123, in dumps
rv = _json.dumps(obj, **kwargs)
File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/lib/python3.6/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/usr/lib/python3.6/json/encoder.py", line 430, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/usr/lib/python3.6/json/encoder.py", line 376, in _iterencode_dict
raise TypeError("key " + repr(key) + " is not a string")
TypeError: key b'email1' is not a string
The code looks like this:
20 def get_db_profile(mailbox):
21 """ connects to redis and queries for profile """
22 try:
23 my_redis = redis.Redis(connection_pool=POOL)
24 response = my_redis.hgetall(55555)
25 logging.info(response.keys())
26 logging.info(response.items())
27 #response = '123455555'
28 return response
29 except Exception as ex:
30 return "Error:", ex
47 #application.route("/widgets/api/<int:mailbox>", methods=['GET'])
48 def get_profile(mailbox):
49 res_dict = get_db_profile(mailbox)
50 # return application.response_class(jsonify(res_dict), content_type='application/json')
51 return jsonify(res_dict)
52 # return '12345'
53
I added some logging as you can see on line 25 to see what the keys() look like. this is what I see in the log file:
lab-1:/var/www/localhost/htdocs/widgets# cat /tmp/widgets.log
root - INFO - dict_keys([b'email1', b'email2'])
REDIS Data
This is how I created the redis data:
127.0.0.1:6379[5]> hmset 55555 email1 johndoe#hotmail.com email2 jd#yahoo.com
OK
127.0.0.1:6379[5]>
Questions
Should i be able to convert from dict object to json string?
What is the 'b' in the log files?
lab-1:/var/www/localhost/htdocs/widgets# cat /tmp/widgets.log
root - INFO - dict_keys([b'email1', b'email2'])
root - INFO - dict_items([(b'email1', b'johndoe#hotmail.com'), (b'email2', b'jd#yahoo.com')])
How do I send back a proper JSON response?
EDIT 1
I found this question/answer: How to parse python b' string containing dict
and based on that I tried to change my logic to look like this:
47 #application.route("/pvmailprofiles/api/<int:mailbox>", methods=['GET'])
48 def get_profile(mailbox):
49 res_dict = get_db_profile(mailbox)
50 # return application.response_class(jsonify(res_dict), content_type='application/json')
51 #return jsonify(res_dict)
52 return res_dict[b'email1']
53 # return '12345'
54
Line 52 - you can see that as a test I've hardcoded the 'b' and then the key name. And it works - it returns the specific email address.
But I need to find a way to "just" convert everything to json and return to callee.

Have you tried first importing json like so
import json
and then doing
json.dumps(myDict)
and then to load it again if needed.
json.loads(response.text)

Related

Python Flask TypeError: Object of type NoSectionError is not JSON serializable

I'm developing an application with python and Flask to automate sending emails.
When I run this application locally, there is no problem, but after deploying the application in Azure, this error appears
TypeError: Object of type NoSectionError is not JSON serializable
The function that is bursting the error is this, when I try to return the dictionary variable
#app.route('/send_email', methods=['POST'])
def get_parameters():
"""
It receives a JSON object, prints it, and then calls another function that sends an email
:return: The result of the function send_email_to_customer
"""
user_input = request.json
print("Conteudo ", user_input)
try:
user = get_config_data(iten_title='EMAIL_LOGIN', iten='email')
psw = get_config_data(iten_title='EMAIL_LOGIN', iten='password')
id_meeting = user_input['id']
list_of_recipients = user_input['recipients']
creator_name = user_input['creator_name']
date_list = user_input['meeting_day']
subject = f'Melhor data para a reuniao {id_meeting}'
url = "https://easy-meeting.azurewebsites.net/external_url?meeting_day="+",".join(date_list)
email_server = create_email_server(user, psw)
for recipients_dict in list_of_recipients:
email_msg = create_email_body(user, recipients_dict, creator_name, subject, url)
run(email_server, email_msg)
dictionary = {"Status":"Sucesso ao enviar o email"}
except Exception as email_error:
dictionary = {"Status":"Erro ao enviar o email", "Error Message": email_error}
print(email_error)
dictionary = jsonify(dictionary)
return dictionary
full error code
2022-11-26T02:26:55.182403211Z [2022-11-26 02:26:55,162] ERROR in app: Exception on /send_email [POST]
2022-11-26T02:26:55.182438711Z Traceback (most recent call last):
2022-11-26T02:26:55.182445810Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/app.py", line 2525, in wsgi_app
2022-11-26T02:26:55.182480710Z response = self.full_dispatch_request()
2022-11-26T02:26:55.182501610Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/app.py", line 1822, in full_dispatch_request
2022-11-26T02:26:55.182505610Z rv = self.handle_user_exception(e)
2022-11-26T02:26:55.182509810Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/app.py", line 1820, in full_dispatch_request
2022-11-26T02:26:55.182513410Z rv = self.dispatch_request()
2022-11-26T02:26:55.182516910Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/app.py", line 1796, in dispatch_request
2022-11-26T02:26:55.182520410Z return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
2022-11-26T02:26:55.182524010Z File "/tmp/8dacf551bd5f657/api_run.py", line 55, in get_parameters
2022-11-26T02:26:55.182527510Z dictionary = jsonify(dictionary)
2022-11-26T02:26:55.182531010Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/json/__init__.py", line 342, in jsonify
2022-11-26T02:26:55.182534510Z return current_app.json.response(*args, **kwargs)
2022-11-26T02:26:55.182538010Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/json/provider.py", line 309, in response
2022-11-26T02:26:55.182541510Z f"{self.dumps(obj, **dump_args)}\n", mimetype=mimetype
2022-11-26T02:26:55.182545110Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/json/provider.py", line 230, in dumps
2022-11-26T02:26:55.182548610Z return json.dumps(obj, **kwargs)
2022-11-26T02:26:55.182551910Z File "/opt/python/3.10.4/lib/python3.10/json/__init__.py", line 238, in dumps
2022-11-26T02:26:55.182555410Z **kw).encode(obj)
2022-11-26T02:26:55.182558710Z File "/opt/python/3.10.4/lib/python3.10/json/encoder.py", line 199, in encode
2022-11-26T02:26:55.182562210Z chunks = self.iterencode(o, _one_shot=True)
2022-11-26T02:26:55.182565610Z File "/opt/python/3.10.4/lib/python3.10/json/encoder.py", line 257, in iterencode
2022-11-26T02:26:55.182569210Z return _iterencode(o, 0)
2022-11-26T02:26:55.182572510Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/json/provider.py", line 122, in _default
2022-11-26T02:26:55.182576010Z raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
2022-11-26T02:26:55.182579609Z TypeEr
I already tried to add the jsonify flask function, but it didn't work
The goal is to make the dictionary variable just like local
enter image description here

Expected bytes, HTTPResponse found

I want to use linebot to make an object detection application, and when I retrieve the url which is a http type, the system called an error.
[2022-11-23 19:13:12,335] ERROR in app: Exception on /callback [POST]
Traceback (most recent call last):
File "C:\officiallandprice\myproject\myenv\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\officiallandprice\myproject\myenv\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\officiallandprice\myproject\myenv\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\officiallandprice\myproject\myenv\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "part1deploy_3.py", line 55, in callback
handler.handle(body, signature)
File "C:\officiallandprice\myproject\myenv\lib\site-packages\linebot\webhook.py", line 259, in handle
self.__invoke_func(func, event, payload)
File "C:\officiallandprice\myproject\myenv\lib\site-packages\linebot\webhook.py", line 271, in __invoke_func
func(event)
File "part1deploy_3.py", line 201, in handle_content_message
text_detected1=text_detected(user.user_id)
File "part1deploy_3.py", line 81, in text_detected
image = vision.Image(content=input_file)
File "C:\officiallandprice\myproject\myenv\lib\site-packages\proto\message.py", line 604, in __init__
super().__setattr__("_pb", self._meta.pb(**params))
TypeError: expected bytes, HTTPResponse found
127.0.0.1 - - [23/Nov/2022 19:13:12] "POST /callback HTTP/1.1" 500 -
I do not have ideas which part of the code below requires a byte type file to make a detection(the PIL module?).
Is it necessary to change to the byte type, when it comes to an object detection?
def text_detected(user_id):
input_file=urllib.request.urlopen (
'https://storage.googleapis.com/
img_platecapture/{}.jpg'.format(user_id))
image = vision.Image(content=input_file)
response = vision_client.text_detection(image=image)
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
img = Image.open(input_file)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("simsun.ttc", 18)
for text in response.text_annotations[1::]:
ocr = text.description
draw.text((bound.vertices[0].x-25, bound.vertices[0].y-25),ocr,fill=(255,0,0),font=font)
draw.polygon(
[
bound.vertices[0].x,
bound.vertices[0].y,
bound.vertices[1].x,
bound.vertices[1].y,
bound.vertices[2].x,
bound.vertices[2].y,
bound.vertices[3].x,
bound.vertices[3].y,
],
None,
'yellow',
)
texts=response.text_annotations
a=str(texts[0].description.split())
b=re.sub(u"([^\u4e00-\u9fa5\u0030-u0039])","",a)
b1="".join(b)
print("偵測到的地址為:",b1)
return b1
#handler.add(MessageEvent, message=ImageMessage)
def handle_content_message(event):
message_content = line_bot_api.get_message_content(event.message.id)
user = line_bot_api.get_profile(event.source.user_id)
data=b''
for chunk in message_content.iter_content():
data+= chunk
global bucket_name
bucket_name = 'img_platecapture'
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(f'{user.user_id}.jpg')
blob.upload_from_string(data)
text_detected1=text_detected(user.user_id) ####Here's the problem
line_bot_api.reply_message(
event.reply_token,
messages=TextSendMessage(
text=text_detected1
))

Unit tests are failing after adding environment variable to main file

I'm currently using an environment variable to hide my API's key. My unit test that is testing the API route is now failing. However, when the key was hard-coded into the main file, the tests passed. Here is my code:
import os
import requests
key = os.environ.get('key')
def test_code(state, API_BASE_URL):
url = f'https://covid-19-testing.github.io/locations/{state.lower()}/complete.json'
res = requests.get(url)
testing_data = res.json()
latsLngs = {}
for obj in testing_data:
if obj["physical_address"]:
for o in obj["physical_address"]:
addy = o["address_1"]
city = o["city"]
phone = obj["phones"][0]["number"]
location = f'{addy} {city}'
location_coordinates = requests.get(API_BASE_URL,
params={'key': key, 'location': location}).json()
lat = location_coordinates["results"][0]["locations"][0]["latLng"]["lat"]
lng = location_coordinates["results"][0]["locations"][0]["latLng"]["lng"]
latsLngs[location] = {'lat': lat, 'lng': lng, 'place': location, 'phone': phone}
return latsLngs
Here is the unit test:
from unittest import TestCase, mock
from models import db, User
from sqlalchemy.exc import InvalidRequestError
class UserViewTestCase(TestCase):
"""Test views for users."""
def setUp(self):
"""Create test client, add sample data."""
db.drop_all()
db.create_all()
self.app = create_app('testing')
self.client = self.app.test_client()
self.testuser = User.signup('test',
'dummy',
'test123',
'dummytest#test.com',
'password',
None,
"Texas",
None,
None)
self.uid = 1111
self.testuser.id = self.uid
db.session.commit()
def test_map_locations(self):
"""Does the map show testing locations?"""
with self.client as c:
resp = c.get('/location?state=California')
html = resp.get_data(as_text=True)
self.assertEqual(resp.status_code, 200)
self.assertIn('San Francisco', html)
I also think it's important to note that the application runs fine in the browser. It's just that the unit tests are not passing anymore.
UPDATE
Here is the full traceback:
ERROR: test_map_locations (test_user_views.UserViewTestCase)
Does the map show testing locations?
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/build/azaria-dedmon/covid-19/tests/test_user_views.py", line 157, in test_map_locations
resp = c.get('/location?state=California')
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 1006, in get
return self.open(*args, **kw)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/testing.py", line 227, in open
follow_redirects=follow_redirects,
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 970, in open
response = self.run_wsgi_app(environ.copy(), buffered=buffered)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 861, in run_wsgi_app
rv = run_wsgi_app(self.application, environ, buffered=buffered)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/werkzeug/test.py", line 1096, in run_wsgi_app
app_rv = app(environ, start_response)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/travis/build/azaria-dedmon/covid-19/app/__init__.py", line 111, in show_state_locations
latsLngs = test_code(state, API_BASE_URL)
File "/home/travis/build/azaria-dedmon/covid-19/app/refactor.py", line 22, in test_code
params={'key': key, 'location': location}).json()
File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/requests/models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "/opt/python/3.7.1/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/opt/python/3.7.1/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/opt/python/3.7.1/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)
I think it's most likely that your test framework is loading just the test_code() function from your test file, and not the fact that key is set up in the main body of the code. Perhaps moving your key = os.environ.get("key") into test_code() will solve your issue.
The environment variable needs to be set in the project's repository in travis CI so that all files have access to it. Here is the documentation on how to achieve this https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-settings

Unable to render output in flask. Exception with returning flask json.dumps on list of lists

I am having trouble in displaying output in JSON using Flask. I am calling a function that returns a list of lists which looks as:
[[["High", 0], ["Medium", 1], ["Low", 2], ["Unknown", 3]], ["test_data", [4155, 1, 25, 9.1, 2, "2.40"]], ["label", 1]]
However, in my flask application, I am unable to jsonify or json.dumps. I do like this:
def remotely_call_func(json_lol):
# print('inside remotely')
# abc =[]
# abc=ext.call_func(json_lol) # I tried to jsonify abc
# print(abc) # print the
return json.dumps(ext.call_func(json_lol)) # throws an exception
# return ext.call_func(json_lol)
#app.route('/api/v1/engine/label', methods=['POST'])
def labelJsonHandler():
if request.is_json:
# Parse the JSON into a Python dictionary
print('request is json')
content = request.get_json() # --works
app.logger.info("labelJsonHandler()..", content)
return access_data_api(content['orderId']), 200 # Return a string along with an HTTP status code
else:
return "Request was not JSON", 400
The exception that I get is:
INFO:werkzeug:127.0.0.1 - - [23/Apr/2020 05:20:34] "POST /api/v1/engine/label HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 1953, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 1968, in finalize_request
response = self.make_response(rv)
File "C:\Users\nma\Anaconda3\lib\site-packages\flask\app.py", line 2098, in make_response
"The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
I am able to receive the exact list of lists in my flask application. How can render this as JSON to POST using my flask?

How to check if the url contains JSON file

I'm working with League of Legends API, and I'm trying to get Ranked Datas from JSON file. But, if the player is not Level 30, he doesn't have his file.
So here
def getRankedData(region, ID, APIkey):
URL = "https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/" + ID + "/entry?api_key=" + APIkey
response = requests.get(URL)
return response.json()
It won't get JSON file, because it doesn't exist. How do i can do, that if the URL doesn't exist and doesn't have the JSON file, it returns the string.
Here, I'm returning the datas to HTML page. But this isn't work too.
region = request.form['region']
summonerName = request.form['summonerName']
APIkey = "45afde27-b628-473f-9a94-feec8eb86094"
types = request.form['types']
responseJSON = getData(region, summonerName, APIkey)
ID = responseJSON[summonerName]['id']
ID = str(ID)
responseJSON2 = getRankedData(region, ID, APIkey)
if not responseJSON2:
divisionName = "Unranked"
else:
divisionName = responseJSON2[ID][0]['name']
responseJSON3 = getChallengerPlayers(region, str(types), APIkey)
challengerPlayers = responseJSON3['entries'][0]['wins']
#print challengerPlayers
return render_template('form_action.html', ID = ID, divisionName = divisionName, challengerPlayers = challengerPlayers)
I'm getting this error:
Traceback (most recent call last)
File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Hanisek\Documents\Visual Studio 2015\Projects\FlaskWebProject2\FlaskWebProject2\FlaskWebProject2\views.py", line 53, in hello
responseJSON2 = getRankedData(region, ID, APIkey)
File "C:\Users\Hanisek\Documents\Visual Studio 2015\Projects\FlaskWebProject2\FlaskWebProject2\FlaskWebProject2\views.py", line 21, in getRankedData
Open an interactive python shell in this framereturn response.json()
File "C:\Python27\lib\requests\models.py", line 805, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
dont know a ton about LOL but is there a reason that you cant have your program use and if/then statement to check the level of the player and then only check for the json file if the player is a high enough level to have one?
You can try checking if the URL exists, JSON is proper format or if the page throws 40X status codes
try:
r = requests.get("URL")
assert r.status_code < 400
return r.json()
except (ValueError, ConnectionError, AssertionError):
return ''
It's always a good idea to check what the api url is returning by running it in your browser. I'm guessing that it's returning a 404 error because the information doesn't exist.
In that case, I recommend checking to see if there is a 404 error before proceeding with the JSON parsing.
Request has a function called status_code that will return the 404 error if there is one.
Example code:
r = request.get("API STRING")
if r.status_code != 404:
r.json()

Categories

Resources