Why is my python 3 EAN query not working? - python-3.x

today I tried to program a EAN query with an EAN database.
I tried to put the request into a json but every time I get an error.
If the query was succesful, you get the data in an MIME-Typ text/plain text format.
What can I do?
Here is my code:
import json
import requests
userid = "&queryid=400000000"
base_url = "http://opengtindb.org/?ean="
query = "&cmd=query"
while True:
print("Welcome to the EAN Database!")
print()
print("1: Search for API")
print("2: Exit")
choice = input("> ")
if choice == "2":
break
if choice == "1":
print("Enter the EAN Number")
print()
ean = input("> ")
ean_call = base_url + ean + query + userid
request = requests.get(ean_call)
print(request.raw)
print(request)
data = request.json()
print(data)
data = data['body']
print(ean)
print(data)
print(ean_call)
Here is the error:
Traceback (most recent call last):
File "/Users/leon/PycharmProjects/ean_api.py", line 28, in <module>
data = request.json()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.8/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 2 column 1 (char 1)

Related

An HTTP Client raised an unhandled exception: 'int' object is not callable

I'm facing the issue in two python libraries used in my code, Getting these randomly on prod on some of the pods and not all pods
Trace of The Error
Traceback (most recent call last):\n File \"/usr/local/lib/python3.10/site-packages/botocore/httpsession.py\",
line 448, in send\n
urllib_response = conn.urlopen(\n File \"/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py\",
line 703, in urlopen\n
httplib_response = self._make_request(\n File \"/usr/local/lib/python3.10/site-packages/newrelic/hooks/external_urllib3.py\",
line 32, in _nr_wrapper_make_request_\n
return wrapped(*args, **kwargs)\n
File \"/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py\",
line 386, in _make_request\n self._validate_conn(conn)\n
File \"/usr/local/lib/python3.10/site-packages/urllib3/connectionpool.py\",
line 1040, in _validate_conn\n
conn.connect()\n File \"/usr/local/lib/python3.10/site-packages/urllib3/connection.py\",
line 416, in connect\n
self.sock = ssl_wrap_socket(\n File \"/usr/local/lib/python3.10/site-packages/urllib3/util/ssl_.py\",
line 424, in ssl_wrap_socket\n context.set_alpn_protocols(ALPN_PROTOCOLS)\n
File \"/usr/local/lib/python3.10/ssl.py\",
line 566, in set_alpn_protocols\n
if len(b) == 0 or len(b) > 255:\nTypeError: 'int' object is not callable\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n
File \"/code/app/aws_utils/dynamo_db.py\", line 176, in update_multi_attributes\n
response = table.update_item(\n File \"/usr/local/lib/python3.10/site-packages/boto3/resources/factory.py\",
line 580, in do_action\n
response = action(self, *args, **kwargs)\n
File \"/usr/local/lib/python3.10/site-packages/boto3/resources/action.py\",
line 88, in __call__\n response = getattr(parent.meta.client, operation_name)(*args, **params)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/client.py\",
line 514, in _api_call\n
return self._make_api_call(operation_name, kwargs)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/client.py\",
line 921, in _make_api_call\n
http, parsed_response = self._make_request(\n
File \"/usr/local/lib/python3.10/site-packages/botocore/client.py\",
line 944, in _make_request\n
return self._endpoint.make_request(operation_model, request_dict)\n
File \"/usr/local/lib/python3.10/site-packages/newrelic/hooks/external_botocore.py\",
line 108, in _nr_endpoint_make_request_\n
result = wrapped(*args, **kwargs)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/endpoint.py\",
line 119, in make_request\n
return self._send_request(request_dict, operation_model)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/endpoint.py\",
line 231, in _send_request\n
raise exception\n File \"/usr/local/lib/python3.10/site-packages/botocore/endpoint.py\",
line 281, in _do_get_response\n
http_response = self._send(request)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/endpoint.py\",
line 377, in _send\n return self.http_session.send(request)\n
File \"/usr/local/lib/python3.10/site-packages/botocore/httpsession.py\",
line 493, in send\n
raise HTTPClientError(error=e)\nbotocore.exceptions.HTTPClientError: An HTTP Client raised an unhandled exception: 'int' object is not callable\n",
Getting this in all dynamodb calls , adding one of the codes here, exception comes in the packages and not in the code as far as i understood
def update_multi_attributes(
self,
table,
partition_key,
sort_key,
attr_value_dict,
delete_attr=[],
):
try:
if not partition_key or not sort_key:
return None
if not attr_value_dict and len(delete_attr) == 0:
return None
if not attr_value_dict and len(delete_attr) > 0:
return self.delete_attributes(
table=table,
partition_key=partition_key,
sort_key=sort_key,
delete_attr=delete_attr,
)
expression_attribute_values = {}
expression_attribute_names = {}
update_expression = "SET "
remove_attr_expression = "REMOVE "
index = 0
attr_value_dict.pop("partition_key", None)
attr_value_dict.pop("sort_key", None)
for key, value in attr_value_dict.items():
index += 1
var_name = "#var" + str(index)
var_value_name = ":var" + str(index)
expression_attribute_values[var_value_name] = value
expression_attribute_names[var_name] = key
if index < len(attr_value_dict.keys()):
update_expression = (
update_expression + var_name + "=" + var_value_name + ","
)
else:
update_expression = (
update_expression + var_name + "=" + var_value_name
)
index = 0
for attr in delete_attr:
index += 1
var_name = "#rvar" + str(index)
expression_attribute_names[var_name] = attr
if index < len(delete_attr):
remove_attr_expression = remove_attr_expression + var_name + ","
else:
remove_attr_expression = remove_attr_expression + var_name
if len(delete_attr) > 0:
update_expression = update_expression + " " + remove_attr_expression
response = table.update_item(
Key=self.get_key(partition_key, sort_key),
ExpressionAttributeNames=expression_attribute_names,
UpdateExpression=update_expression,
ConditionExpression="attribute_exists(partition_key)"
"and attribute_exists(sort_key)",
ExpressionAttributeValues=expression_attribute_values,
)
return response
except botocore.exceptions.ClientError as e:
logger.info(
"Dynamo: Error Update MultiAttribute boto3{} error{},{}for{},{}".format(
attr_value_dict,
e,
e.response["Error"],
partition_key,
traceback.format_exc(),
)
)
except Exception as e:
logger.info(
"Dynamo: Error Update MultiAttribute {} error {} for {}, {}".format(
attr_value_dict, e, partition_key, traceback.format_exc()
)
)
return None
Adding Package versions used
urllib3-1.26.8
botocore-1.27.77
boto3-1.24.77
Had put a trace print, thinking of upgrading the urllib version but not sure if that would solve the problem, Suddenly this error started coming up, code was working fine for a month after integration.`

IMAP4LIB When using the store command I get the error "BAD [b'Could not parse command']"

I am new to all of this so I'm sorry if I mess this up or have already made a mess. I have two classes a GUI and my MailSorter class in the GUI class I have method which logins, then one that fetches all the EmailIds then finally fetches all the From emails and stores it in a dict. which stores the From email and amount of times it appears and an array with the From email and the ID.
def fetchFrom(self,emailIDs):
EmailAmount = dict()
Email = []
count = 0
for emailId in emailIDs:
#Converts email into string
result2,email_data = self.mail.fetch(emailId,'(RFC822)')
try:
raw_email = email_data[0][1].decode("utf-8")
email_message = email.message_from_string(raw_email)
#Fetches email address sent from
From = email_message["From"]
Email.append((From,emailId))
#print(From)
if From in EmailAmount:
EmailAmount[From] = EmailAmount[From] + 1
else:
EmailAmount[From] = 1
count += 1
if count > 10:
break
except Exception as e:
self.log.append((emailId,e))
def mainScreenInterface(self):
#Process
print("Loading program")
EmailIds = self.Mail.fetchEmailId()
EmailDict, self.EmailArray = self.Mail.fetchFrom(EmailIds)
self.master.geometry("750x600")
self.master.title("Main Screen")
self.destoryWidget()
#New Frame
self.mainScreen = tk.Frame(self.master)
self.mainScreen.pack()
#Labels
mainText = tk.Label(self.mainScreen,text = "All Emails")
mainText.config(font=("Courier","25"))
#Buttons
delete = tk.Button(self.mainScreen,text="Delete", command = self.Delete)
deleteAll = tk.Button(self.mainScreen,text="Delete All", command = self.DeleteAll)
Help = tk.Button(self.mainScreen,text="Help", command = self.Help_)
#Scrollbar
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side="right",fill="y")
#Listbox
self.listbox = tk.Listbox(root,width = root.winfo_screenwidth(), height = 25)
#Attach a scrool wheel to the listbox
self.listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.listbox.yview)
#Add items to the list box
count = 1
for x,y in EmailDict.items():
self.listbox.insert(count,(x,y))
count += 1
#Placement
paddingValue = 40
mainText.pack(side="top")
self.listbox.pack(side="top")
delete.pack(side="left",padx=paddingValue)
deleteAll.pack(side="left",padx=paddingValue)
Help.pack(side="left",padx=paddingValue)
def Delete(self):
emailName = self.listbox.get(tk.ANCHOR)[0]
self.Mail.deleteEmail(emailName,self.EmailArray)
So the fetchFrom is from the mailSorter class and the other two are the GUI class, when I call the deleteEmail I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 197, in Delete
self.Mail.deleteEmail(emailName,self.EmailArray)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 66, in deleteEmail
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')
File "C:\Python\lib\imaplib.py", line 840, in store
typ, dat = self._simple_command('STORE', message_set, command, flags)
File "C:\Python\lib\imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python\lib\imaplib.py", line 1027, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: STORE command error: BAD [b'Could not parse command']
but when I run it as a text base with no GUI and use an example email it all works fine:
test = MailSorter("hamadnassor5#gmail.com","snerfulbubble1.")
test.login()
EmailIds = test.fetchEmailId()
EmailDict, EmailArray = test.fetchFrom(EmailIds)
test.displayEmails(EmailDict)
test.deleteEmail("Xbox <Xbox#outlook.com>",EmailArray)
test.closeCon()
DeleteMail code
def deleteEmail(self, emailName, EmailArray):
for Id in EmailArray:
if Id[0] == emailName:
print(Id[0])
print(emailName)
print(Id[1])
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')

How to resolve the error "IndexError: list index out of range"?

I'm using Odoo 11 and I have installed openHRMS module but every time when I press on the dashboard menu it appears an error on this method:
IndexError: list index out of range
Ps: i tried to install this module on bitnami VM and it works whithout any problem but when i tried to installe it on ubuntu 18.04 it shows error
Any ideas on how to fix it?
def join_resign_trends(self):
cr = self._cr
month_list = []
join_trend = []
resign_trend = []
for i in range(11, -1, -1):
last_month = datetime.now() - relativedelta(months=i)
text = format(last_month, '%B %Y')
month_list.append(text)
for month in month_list:
vals = {
'l_month': month,
'count': 0
}
join_trend.append(vals)
for month in month_list:
vals = {
'l_month': month,
'count': 0
}
resign_trend.append(vals)
cr.execute('''select to_char(joining_date, 'Month YYYY') as l_month, count(id) from hr_employee
WHERE joining_date BETWEEN CURRENT_DATE - INTERVAL '12 months'
AND CURRENT_DATE + interval '1 month - 1 day'
group by l_month;''')
join_data = cr.fetchall()
cr.execute('''select to_char(resign_date, 'Month YYYY') as l_month, count(id) from hr_employee
WHERE resign_date BETWEEN CURRENT_DATE - INTERVAL '12 months'
AND CURRENT_DATE + interval '1 month - 1 day'
group by l_month;''')
resign_data = cr.fetchall()
for line in join_data:
match = list(filter(lambda d: d['l_month'].replace(' ', '') == line[0].replace(' ', ''), join_trend))
match[0]['count'] = line[1]
for line in resign_data:
match = list(filter(lambda d: d['l_month'].replace(' ', '') == line[0].replace(' ', ''), resign_trend))
match[0]['count'] = line[1]
for join in join_trend:
join['l_month'] = join['l_month'].split(' ')[:1][0].strip()[:3]
for resign in resign_trend:
resign['l_month'] = resign['l_month'].split(' ')[:1][0].strip()[:3]
graph_result = [{
'name': 'Join',
'values': join_trend
}, {
'name': 'Resign',
'values': resign_trend
}]
return graph_result
def get_attrition_rate(self):
month_attrition = []
monthly_join_resign = self.join_resign_trends()
month_join = monthly_join_resign[0]['values']
month_resign = monthly_join_resign[1]['values']
sql = """
SELECT (date_trunc('month', CURRENT_DATE))::date - interval '1' month * s.a AS month_start
FROM generate_series(0,11,1) AS s(a);"""
self._cr.execute(sql)
month_start_list = self._cr.fetchall()
for month_date in month_start_list:
self._cr.execute("""select count(id), to_char(date '%s', 'Month YYYY') as l_month from hr_employee
where resign_date> date '%s' or resign_date is null and joining_date < date '%s'
""" % (month_date[0], month_date[0], month_date[0],))
month_emp = self._cr.fetchone()
# month_emp = (month_emp[0], month_emp[1].split(' ')[:1][0].strip()[:3])
match_join = list(filter(lambda d: d['l_month'] == month_emp[1].split(' ')[:1][0].strip()[:3], month_join))[0]['count']
match_resign = list(filter(lambda d: d['l_month'] == month_emp[1].split(' ')[:1][0].strip()[:3], month_resign))[0]['count']
month_avg = (month_emp[0]+match_join-match_resign+month_emp[0])/2
attrition_rate = (match_resign/month_avg)*100 if month_avg != 0 else 0
vals = {
# 'month': month_emp[1].split(' ')[:1][0].strip()[:3] + ' ' + month_emp[1].split(' ')[-1:][0],
'month': month_emp[1].split(' ')[:1][0].strip()[:3],
'attrition_rate': round(float(attrition_rate), 2)
}
month_attrition.append(vals)
return month_attrition
traceback
Traceback (most recent call last):
File "/opt/openhrms/odoo/http.py", line 651, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/opt/openhrms/odoo/http.py", line 310, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File "/opt/openhrms/odoo/tools/pycompat.py", line 87, in reraise
raise value
File "/opt/openhrms/odoo/http.py", line 693, in dispatch
result = self._call_function(**self.params)
File "/opt/openhrms/odoo/http.py", line 342, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/opt/openhrms/odoo/service/model.py", line 97, in wrapper
return f(dbname, *args, **kwargs)
File "/opt/openhrms/odoo/http.py", line 335, in checked_call
result = self.endpoint(*a, **kw)
File "/opt/openhrms/odoo/http.py", line 937, in __call__
return self.method(*args, **kw)
File "/opt/openhrms/odoo/http.py", line 515, in response_wrap
response = f(*args, **kw)
File "/opt/openhrms/addons/web/controllers/main.py", line 934, in call_kw
return self._call_kw(model, method, args, kwargs)
File "/opt/openhrms/addons/web/controllers/main.py", line 926, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/opt/openhrms/odoo/api.py", line 687, in call_kw
return call_kw_model(method, model, args, kwargs)
File "/opt/openhrms/odoo/api.py", line 672, in call_kw_model
result = method(recs, *args, **kwargs)
File "/opt/openhrms/openhrms/hrms_dashboard/models/hrms_dashboard.py", line 384, in get_attrition_rate
monthly_join_resign = self.join_resign_trends()
File "/opt/openhrms/openhrms/hrms_dashboard/models/hrms_dashboard.py", line 364, in join_resign_trends
match[0]['count'] = line[1]
IndexError: list index out of range

error:'builtin_function_or_method' object is not iterable

In some other tutorial the following python code for finding words from a json file which worked for them. but, not for me.
would you please help me to get rid of this error.
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def translate(word):
word = word.lower
if word in data:
return data[word]
elif len(get_close_matches(word, data.keys())) > 0:
yn=input ("did you mean %s instead? Enter Y if yes and N if no" % get_close_matches(word, data.keys())[0])
if yn == "Y":
return data[get_close_matches(word, data.keys())[0]]
elif yn == "N":
return("the word doesn't exist")
else:
print("we don't understand your entry")
else:
return("the word does't exist please crosscheck it")
word = input("enter a word: ")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)
This is the error I got:
Traceback (most recent call last):
File "pracjson.py", line 23, in <module>
output = translate(word)
File "pracjson.py", line 10, in translate
elif len(get_close_matches(word, data.keys())) > 0:
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 723, in get_close_matches
s.set_seq2(word)
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 279, in set_seq2
self.__chain_b()
File "C:\Users\Vishnu's World\AppData\Local\Programs\Python\Python37\lib\difflib.py", line 311, in __chain_b
for i, elt in enumerate(b):
TypeError: 'builtin_function_or_method' object is not iterable
Your error is in this line:
word = word.lower
.lower is a method, so it should be:
word = word.lower()
https://docs.python.org/3/library/stdtypes.html?highlight=lower#str.lower
I'm not familiar with get_close_matches. But according to the docs: https://docs.python.org/2/library/difflib.html, it seems like it needs a list (iterable object).
data.keys() returns a dictionary. Try converting that to a list first.
elif len(get_close_matches(word, list(data.keys()))) > 0:

Programming a discord bot in python, ran into the error "string index out of range"

I'm making a discord bot that spurts out randomly generated sentences into the chat every few seconds. Im trying to use the nltk module to make the sentences more coherent, but I'm caught up on an error and cant figure it out.
import asyncio
import random
import discord.ext.commands
import markovify
import nltk
import re
class POSifiedText(markovify.Text):
def word_split(self, sentence):
words = re.split(self.word_split_pattern, sentence)
words = ["::".join(tag) for tag in nltk.pos_tag(words) ]
return words
def word_join(self, words):
sentence = " ".join(word.split("::")[0] for word in words)
return sentence
with open("/root/sample.txt") as f:
text = f.read()
text_model = POSifiedText(text, state_size=1)
client = discord.Client()
async def background_loop():
await client.wait_until_ready()
while not client.is_closed:
channel = client.get_channel('channelid')
messages = [(text_model.make_sentence(tries=8, max_overlap_total=10,default_max_overlap_ratio=0.5))]
await client.send_message(channel, random.choice(messages))
await asyncio.sleep(10)
client.loop.create_task(background_loop())
client.run("token")
heres the error from the output log:
Traceback (most recent call last):
File "/root/untitled/Loop.py", line 21, in <module>
text_model = POSifiedText(text, state_size=1)
File "/usr/local/lib/python3.5/dist-packages/markovify/text.py", line 24, in __init__
runs = list(self.generate_corpus(input_text))
File "/root/untitled/Loop.py", line 11, in word_split
words = [": :".join(tag) for tag in nltk.pos_tag(words) ]
File "/usr/local/lib/python3.5/dist-packages/nltk/tag/__init__.py", line 129, in pos_tag
return _pos_tag(tokens, tagset, tagger)
File "/usr/local/lib/python3.5/dist-packages/nltk/tag/__init__.py", line 97, in _pos_tag
tagged_tokens = tagger.tag(tokens)
File "/usr/local/lib/python3.5/dist-packages/nltk/tag/perceptron.py", line 152, in tag
context = self.START + [self.normalize(w) for w in tokens] + self.END
File "/usr/local/lib/python3.5/dist-packages/nltk/tag/perceptron.py", line 152, in <listcomp>
context = self.START + [self.normalize(w) for w in tokens] + self.END
File "/usr/local/lib/python3.5/dist-packages/nltk/tag/perceptron.py", line 227, in normalize
elif word[0].isdigit():
IndexError: string index out of range
The fact that word[0].isdigit(): throws the error implies that word is an empty string. The most likely cause of this is that your regex split produces empty strings on occasion.
The solution would be to, after
words = re.split(self.word_split_pattern, sentence)
put the line
words = [w for w in words if len(w) > 0]

Resources