local variable 'servers' referenced before assignment - python

def websvc(currency):
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM myform_composantsserveur"
try:
cursor.execute(sql)
results = cursor.fetchall()
currency_in = currency
req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to=%s') % (currency_in)
req1 = req.read()
rate = int(req1['rate'])
# rate = 0.77112893299999996
servers = []
for row in results:
result = {}
result['1'] = row[1]
result['3'] = int(row[2])
result['4'] = int(row[3])
result['5'] = int(row[4])
result['6'] = row[5]
result['7'] = int(row[6])
result['8'] = row[7]
result['9'] = row[8]
p = rate * calculations_metric (int(row[2]), int(row[3]), int(row[4]), int(row[6]), row[7])
result['2'] = p
keys = result.keys()
keys.sort()
servers.append(result)
except:
print "Error: unable to fetch data"
db.close()
return servers
but i have this error while compiling the code :
Exception Type: UnboundLocalError
Exception Value: local variable
'servers' referenced before assignment
Exception Location: /home/amine/PFE Directory/mysite1/myform/Webservice.py in websvc, line 43 Python Executable: /usr/bin/python2.7
this code works normally before i added a parameter in this function

Your code not able to reach servers initialization and that is why you getting error. Simply move initialization before try..except. Change this way:
def websvc(currency):
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM myform_composantsserveur"
servers = []
try:
cursor.execute(sql)
results = cursor.fetchall()
currency_in = currency
req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to=%s') % (currency_in)
req1 = req.read()
rate = int(req1['rate'])
# rate = 0.77112893299999996
for row in results:
result = {}
result['1'] = row[1]
result['3'] = int(row[2])
result['4'] = int(row[3])
result['5'] = int(row[4])
result['6'] = row[5]
result['7'] = int(row[6])
result['8'] = row[7]
result['9'] = row[8]
p = rate * calculations_metric (int(row[2]), int(row[3]), int(row[4]), int(row[6]), row[7])
result['2'] = p
keys = result.keys()
keys.sort()
servers.append(result)
except:
print "Error: unable to fetch data"
db.close()
return servers

I see the problem now you have edited it to add the missing parts. It's the exception handler.
If you have an error after try and before servers=[] it will jump to the except clause, then see return servers and fail.
You might want to use a list(), instead of using a dict() to emulate a list ...

You can make the empty variable also in the try block if you check against the globals() variables any time after the try block. This is no game changer in this code since making a new empty list will never fail, but I could use it to have the opening of a connection into the try block so that it would be caught in the exception, and I could close that object in the finally block without having to make an empty object before the try/except/finally block (tested).
def websvc(currency):
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM myform_composantsserveur"
try:
servers = []
cursor.execute(sql)
results = cursor.fetchall()
currency_in = currency
req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to=%s') % (currency_in)
req1 = req.read()
rate = int(req1['rate'])
# rate = 0.77112893299999996
for row in results:
result = {}
result['1'] = row[1]
result['3'] = int(row[2])
result['4'] = int(row[3])
result['5'] = int(row[4])
result['6'] = row[5]
result['7'] = int(row[6])
result['8'] = row[7]
result['9'] = row[8]
p = rate * calculations_metric (int(row[2]), int(row[3]), int(row[4]), int(row[6]), row[7])
result['2'] = p
keys = result.keys()
keys.sort()
servers.append(result)
except:
print "Error: unable to fetch data"
db.close()
if 'servers' in globals():
return servers
else:
return []
This is untested. If it crashes at servers.append(result), try if 'servers' in globals(): right before that as well. Which would blow up the code of the try block, therefore, I hope that it is not needed, and in my example, I also did not have to do that when I used the called connection afterwards in the try block.
Side remark: append() makes a full copy. Try servers.extend([result]) instead if you grow a large list (not likely if you just count up just a few servers).

Related

Insert List valuesinto SQlite3 database with Python error

ctime = []
name = []
minprice = []
maxprice = []
stock = []
historical_sold = []
sold = []
option_name = []
option_stock = []
option_price = []
#Connect to SQL database
conn = sqlite3.connect('etracker.db')
#Create cursor to work with database
c = conn.cursor()
c.execute('''Create TABLE if not exists server("prices")''')
with open('eurls.csv', 'r') as f:
csv_reader = csv.reader(f)
for row in csv_reader:
asins.append(row[0])
asin = asin
date = datetime.datetime.today().strftime("%d/%m/%Y %H:%M:%S")
url = f"https://e.{tld}/api/item/get"
querystring = {"itemid":f"{itemid}","shopid":f"{shopid}"}
payload = ""
headers = {
"cookie": "SPC_SI=9egeYgAAAABlNUJsazZUbPQ60gAAAAAAeVpFRmJWb00%3D; REC_T_ID=c56cc396-9f13-11ec-b054-2cea7fad64d2;",
}
response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
# json object
result_json = response.json()
# starting point
result = result_json['data']
# These are the results from the API based on starting point ['data']
name = result['name']
minprice = result['price_min']/100000
maxprice = result['price_max']/100000
stock = result['normal_stock']
historical_sold = result['historical_sold']
sold = result['sold']
# starting point
option_items = result_json['data']['models']
for option_item in option_items:
# option name
try:
option_name.append(option_item['name'])
except:
option_name.append('')
# option stock
try:
option_stock.append(option_item['normal_stock'])
except:
option_stock.append('')
# option price
try:
option_price.append(option_item['price']/100000)
except:
option_price.append('')
print(option_name, option_stock, option_price)
print(date, name, minprice, maxprice, stock, historical_sold, sold, asin)
c.execute('''INSERT INTO prices VALUES(?,?,?,?,?,?,?,?,?,?,?)''', (date, name, minprice, maxprice, stock, historical_sold, sold, asin))
print(f'Added data for {name}, {minprice}')
#Insert links into table
def data_entry():
for item in option_name:
c.execute("INSERT INTO server(prices) VALUES(?)", (option_name))
#conn.commit()
data_entry() # ==> call the function
conn.commit()
I am getting an error and unable to add those to the SQL database as some products may have 3 options some may have 20 options
How do I handle that? I read that I need to loop through the list and insert it but when I tried it I get this error
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 11, and there are 8 supplied.
Thank you

How can i run all my code in one function

My python code doesnt work. I get an output for only success mysql connection.
I want to print group id, hostname and other variables. The only output i get is
('Connected to MySQL Server version ', u'5.7.36-0ubuntu0.18.04.1')
("You're connected to database: ")
I cannot print group id or anything else. Im a newbie in python :(
import os
import mysql.connector
import json
execfile("/home/manager/test/mysqlconnector.py")
active_ip = ""
hostname = ""
group_id = 0
def my_funciton():
query = "select value_oid from snmp_trap where name_oid = '1.3.6.1.4.1.14823.2.3.3.1.200.1.17.0'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
mac = cursor.fetchone()
mac_string = mac.values()
mac_str = json.dumps(mac_string)
mac_ = mac_str.replace(':','')
mac_ = mac_.replace('"','')
mac_ = mac_.replace(']','')
mac_ = mac_.replace('[','')
return mac_
active_mac = my_function()
query = "select epp_active_ip, epp_hostname, epp_group_id from epp_inventory where epp_active_mac = + 'active_mac.upper()'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
rows = cursor.fetchall()
#active_ip = ""
#hostname = ""
#group_id = 0
for row in rows:
active_ip = row["epp_active_ip"]
hostname = row["epp_hostname"]
group_id = row["epp_group_id"]
print(group_id)
query = "select wmic_id from group_wmic where group_id = " + str(group_id)
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
wmic_ids = cursor.fetchall()
for row in wmic_ids:
query = "select command_line from wmic_commands where id = " + row["wmic_id"]
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
command_line = cursor.fetchone()
os.system(command_line)
os.system("ls -al")
#os.system(command)
my_funciton()
Apart from naming and indentation issues, which you should really fix, because it will make your code a nightmare to maintain - the issue is quite simple:
Consider:
def some_function():
print('this prints')
return
print('this does not')
Your code has the exact same problem. In your function my_funciton, you have the following line:
return mac_
Nothing after that will ever execute. You need to put the return statement in the position of the function's code where you expect it to actually return. You cannot put it just anywhere and expect the function to execute the rest of the code.

python Commands out of sync; you can't run this command now"

I am trying to run this small python script which inserts data to mySql database under MacOs however it gives me following error:
File "inserter.py", line 58, in
cursor.execute('SELECT countryId from searcher_country');
File "build/bdist.macosx-10.9-intel/egg/MySQLdb/cursors.py", line 205, in execute
File "build/bdist.macosx-10.9-intel/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
Script :
from openpyxl import load_workbook;
import MySQLdb;
import random;
connection = MySQLdb.connect(host='localhost',user='root',passwd='testpassword',db='test');
cursor = connection.cursor();
fileLoc = "data.xlsx";
wb = load_workbook(fileLoc);
ws = wb.active;
#outFile = raw_input("Where do you want your count to go? ");
countryCountProc = """ CREATE PROCEDURE countProc (OUT param1 INT)
BEGIN
SELECT COUNT(*) INTO param1 FROM searcher_country;
END;"""
readyFunction = """
CREATE FUNCTION ready(id INT)
returns CHAR(50)
return 'The program has been initialized';
"""
cursor.execute(countryCountProc);
cursor.execute(readyFunction);
outFile = '/tmp/testingCount';
print cursor.execute('CALL countProc(#a); SELECT #a INTO OUTFILE \'{0}\';'.format(outFile));
yearIndex = 2;
while True:
value = str(ws.cell(row=1,column=yearIndex).value);
try:
sql = 'INSERT INTO searcher_year (year) values (\'{0}\')'.format(value.encode("utf8"))
cursor.execute(sql);
except Exception as e:
print sql
print e
yearIndex = yearIndex + 1
if value == '2011':
print yearIndex-1;
break;
countryIndex = 2;
while True:
value = ws.cell(row=countryIndex,column=1).value.replace('\'','\\\'');
try:
sql = 'INSERT INTO searcher_country (country) values (\'{0}\')'.format(value.encode("utf8"))
cursor.execute(sql);
except Exception as e:
print sql
print e
countryIndex+=1
if value == "Saba":
print countryIndex-1;
break;
cursor.execute('SELECT countryId from searcher_country');
results = [int(item[0]) for item in cursor.fetchall()]
minCountryId = min(results);
maxCountryId = max(results);
cursor.execute('SELECT yearId from searcher_year');
results = [int(item[0]) for item in cursor.fetchall()]
minYearId = min(results);
maxYearId = max(results);
for i in xrange(500):
yearId = random.randint(350,370);
countryId = random.randint(3800,3820)
data = round(random.random()*10,2);
sql = 'INSERT INTO searcher_data (country_id,year_id,stat) values ({0},{1},\'{2}\')'.format(countryId,yearId,str(data))
cursor.execute(sql);
connection.execute('SELECT ready(1) INTO OUTFILE {0}'.format(outFile))
connection.commit();
cursor.close();
You are not releasing the cursor after query execution. Kindly include
connection.commit(); cursor.close(); after each execution stateement

"KeyError: 0" when reading a fetched row

I retrieve the data from database and retrun it from this method.
def _db_execute(s, query, data=None, return_data=False):
con = mdb.connect(s.sql_detail['host'], s.sql_detail['user'], s.sql_detail['pass'], s.sql_detail['db'], cursorclass=mdb.cursors.DictCursor)
with con:
cur = con.cursor()
if type(data) in [ list, tuple ] and len(data) != 0:
if data[0] in [ list, tuple ]:
cur.executemany(query, (item for item in data))
else:
cur.execute(query, data)
elif data != None:
cur.execute(query, [data])
else:
cur.execute(query)
if return_data:
data = cur.fetchall()
if len(data) == 0:
data = None
return data
Following method retrieve data.
def retrieve_portal_credetials(self):
if(self.valid_user()):
query2 ='''SELECT `group`,`username`,`password` FROM db.users u, db.groups g, db.user_groups i where u.userid=i.user_id and g.group_id = i.groupd_id and u.username=%s'''
portal_data= self._db_execute(query=query2, data = self.username, return_data = True)
return portal_data
I try to assign the data to variables here
rows = auth_usr.retrieve_portal_credetials()
#list_of_portaldata = list(portal_data)
#s.data.update({'groups_list': [val]})
#val= list_of_portaldata
for row in rows:
portal_group = row[0]
portal_username = row[1]
portal_password = row[2]
When I debug through the code, I found it breaks here portal_group = row[0] and I got the error KeyError: 0
What I understood was, row doesn't has 0 key. That's why I get this error. However, in the debugger it shows 3 variables under row. Can anybody give any hint to fix this?
After inspecting the datastructure shows in the debugger.
I use the following syntax to access the data.
portal_group = row['group']
portal_username = row['username']
portal_password = row['password']

Python loop through json array

I'm a new to python and I need some help with one loop. Here is the code:
def show_result(self):
listed = self.listed
res = {}
for key in listed:
query_result = 0
is_listed = 0
rbl = key
if not listed[key].get('ERROR'):
query_result = "success"
if listed[key]['LISTED']:
is_listed = 1
else:
is_listed = 0
else:
query_result = "error"
pass
res[key] = [ ['rbl', rbl], ['host', listed['SEARCH_HOST']], ['lookup', query_result], ['is_listed', is_listed] ]
return res
try:
con = db.connect(db_server, db_user, db_password, db_name)
cur = con.cursor()
#hosts = json array with Hosts and IP's
for host in hosts:
searcher = checkHost(host, rbls, report)
result = searcher.show_result()
#
# Need to loop through result to get rbl, host, lookup and is_listed variables
# to be able to execute the query and commit it later when loop is finished
#
cur.execute("INSERT INTO checks_reports_df8 (`rbl`, `host`, `lookup`, `is_listed`) VALUES(%s, %s, '%s')", (rbl, host, lookup, is_listed))
con.commit()
except db.Error, e:
if con:
con.rollback()
finally:
if con:
con.close()
If I pprint result from searcher.show_result() here is what I've get:
{u'0spam-killlist.fusionzero.com': [['rbl', u'0spam-killlist.fusionzero.com'],
['host', u'127.0.0.2'],
['lookup', 'success'],
['is_listed', 0]],
u'zen.spamhaus.org': [['rbl', u'zen.spamhaus.org'],
['host', u'127.0.0.2'],
['lookup', 'success'],
['is_listed', 1]]}
My problem is that I don't know how to loop through the result from searcher.show_result(). If my approach is wrong, the result returned from searcher.show_result() can be changed.

Categories