So I've been at it for hours, and there is something really weird going on.
I am looping through code to check if a table value has changed. And if so run some code.
When i run the following program everything works totally fine! The 'lock state' goes from Open to Closed as it should be doing.
import time
import mysql.connector
host = '...'
database = '...'
user = '...'
password = '...'
conn = mysql.connector.connect(host=host, database=database, user=user, password=password)
conn.start_transaction(isolation_level='READ COMMITTED')
state = 'Open'
def get_web_lock_request():
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM `doorlock`.`state`")
state = ''.join(cursor.fetchone())
cursor.close()
return state
except mysql.connector.Error as e:
print 'get_lock_state ' + format(e)
return ''
def set_web_lock_request():
try:
cursor = conn.cursor()
cursor.execute("UPDATE `doorlock`.`state` SET `state`='" + state + "'")
conn.commit()
cursor.close()
except mysql.connector.Error as e:
print 'set_lock_state: ' + format(e)
while 1:
dbstate = get_web_lock_request()
set_web_lock_request()
if state == 'Open':
state = 'Closed'
else:
state = 'Open'
time.sleep(2)
print dbstate
But in my main code this 'listening for a change' is in a thread. And for some reason the UPDATE statement does not work! even with the conn.commit()
import mysql.connector
conn = mysql.connector.connect(host=host, database=database, user=user, password=password)
conn.start_transaction(isolation_level='READ COMMITTED')
def get_web_lock_request():
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM `doorlock`.`state`")
state = ''.join(cursor.fetchone())
cursor.close()
return state
except mysql.connector.Error as e:
print 'get_lock_state ' + format(e)
return ''
def set_web_lock_request(state):
try:
cursor = conn.cursor()
cursor.execute("UPDATE `doorlock`.`state` SET `state`='" + state + "'")
conn.commit()
cursor.close()
except mysql.connector.Error as e:
print 'set_lock_state: ' + format(e)
def web_request_listener():
global updating
try:
while 1:
print 'get_web_lock_request : ' + get_web_lock_request()
print 'current_state : ' + current_state()
if get_web_lock_request() != current_state() and not updating:
if get_web_lock_request() == 'Open':
open_lock()
print 'DoorLock: State is now open'
elif get_web_lock_request() == 'Closed':
close_lock()
print 'DoorLock: State is now closed'
time.sleep(1)
except KeyboardInterrupt:
exit()
if __name__=='__main__':
try:
button_listener_thread = threading.Thread(target=button_listener)
web_request_listener_thread = threading.Thread(target=web_request_listener)
except KeyboardInterrupt:
exit()
I could really use some help, I have literallyhave nothing else to try :)
Floris
Related
When I run my python code that reads PostGresql database to read configuration from a table. I am using sqlalchemy engine.connect to establish the connection. I am closing the connection using conn.close() command. But still my Database is showing active database connections.
def get_postgres_data_df(self, table_name):
global read_conn
result_df = pd.DataFrame()
if self.debug:
print('Inside PostgreSQLOperations Class get_postgres_data_df method')
connection_string = 'postgresql://' + \
self.user + ':' + \
self.password + '#' + \
self.host + ':' + \
self.port + '/' + \
self.database
try:
if self.debug:
print('Trying to read from table {0}'.format(table_name))
engine = sqlalchemy.create_engine(connection_string)
read_conn = engine.connect()
print('Connected to database # ' + self.database)
if self.debug:
print(engine.table_names())
except Exception as e:
print('Failed to establish the connection', e)
read_conn.close()
query = ('SELECT * FROM ' + table_name)
try:
result_df = pd.read_sql(sql=query, con=read_conn)
if self.debug:
print('Read success for table # ', table_name)
print(result_df)
read_conn.close()
except Exception as e:
print('Read failed # ', e)
read_conn.close()
return result_df
servlet2.py
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='localhost',
database='*project',
user='*****',
password='*****',
)
print("Connection Established")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
c = connection.cursor()
def insertSQL(user):
mySql_insert_query = "INSERT INTO python_project.test (Name) VALUES (?)", (user)
print("user:", user)
c.execute(mySql_insert_query)
print(c.rowcount, "Record inserted successfully into test table")
def username():
user = input("Please Enter Your Name: " )
insertSQL(user)
test_script.py
import servlet2
servlet2.username()
I was able to established connection to the database, however, once I enter name. It will fail to connect and prompt this error.
OperationalError: Lost connection to MySQL server at 'localhost:3306', system error: Connection not available.
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='127.0.0.1',
database='python_project',
user='root',
password='catdog123',
)
print("Connection Established")
#cursor = connection.cursor()
#cursor.execute("""INSERT INTO test (Name) VALUES ('harry')""")
#connection.commit()
#cursor.close()
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
c = connection.cursor()
def insertSQL(user):
#mySql_insert_query = """INSERT INTO test (Name) VALUES (?)""", user
print("user:", user)
print(c.rowcount, "Record inserted successfully into test table")
c.execute("""INSERT INTO test (Name) VALUES ('{}')""".format(user))
connection.commit()
def username():
user = input("Please Enter Your Name:" )
insertSQL(user)
I manage to solve it by changing the insert statement VALUES to ('{}').format(user)
Good day. I wrote an application on python that collects call logs from the Avaya PBX and writes them to the mysql database. It works well, but sometimes the PBX sends an empty string for some reason and the program fails. I attach the screen and code below. I understand that you need to wrap the function in an exception: try except, but I don’t understand how to do it. Please tell me how to do this.enter image description here
def write_db(item, *agrs):
connection = pymysql.connect(host='localhost',
user='acdr',
password='it8ejokd',
db='avaya_cdr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
DBTBL = "cdr102019"
DBFLD = "Date_call, Time_call, `Sec_dur`, `clg_num_in_tag`, `dialed_num`, dep_called, dep_dialed"
dep_num_call = find_dep(item[3].replace(' ', ''))
name_dep_call = name_dep(dep_num_call)
dep_num_dial = find_dep(item[4].replace(' ', ''))
name_dep_dial = name_dep(dep_num_dial)
item.append(name_dep_call)
item.append(name_dep_dial)
item[1] = item[1] + "00"
try:
with connection.cursor() as cursor:
sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (item))
connection.commit()
finally:
connection.close()
# Задаем адрес сервера
SERVER_ADDRESS = ('', 5100)
# Настраиваем сокет
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(SERVER_ADDRESS)
server_socket.listen(5)
print('server is running, please, press ctrl+c to stop')
# Слушаем запросы и пишем в db
while True:
connection, address = server_socket.accept()
data = connection.recv(1024)
if not(b'\x00\x00\x00' in data) and not(b'1370' in data):
str = data.decode("utf-8")
item=[str[0:6],str[7:11],str[12:17],str[18:33],str[34:57]]
print(item)
write_db(item)
connection.close()
You'll have to catch the exception, so we can cater for a few types, but just to be sure and get you up and running, you could do the following :)
try:
with connection.cursor() as cursor:
sql = (
"INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES "
"(%s,%s,%s,%s,%s,%s,%s)"
)
cursor.execute(
sql,
(item),
)
connection.commit()
except Exception as e:
print("Error occurred: %s"% e)
finally:
connection.close()
This should do the trick. I've used all four elements of try/except/else/finally here, with brief explanations of when they're executed.
try:
with connection.cursor() as cursor:
sql = "INSERT INTO "+DBTBL+" ("+DBFLD+") VALUES (%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, (item))
except Exception: # If this code fails, ignore it
pass
else: # If the code inside 'try' succeeds, execute this code.
connection.commit()
finally: # Regardless of whether or not the code inside 'try' succeeds, execute this code
connection.close()
sorry for my english google translator.
I'm learning python and flask and I have a problem in a function.
#app.route('/addProperty',methods=['POST'])
def addProperty():
try:
if session.get('user'):
_tag = request.form['inputTag']
_idCategoria = request.form['inputIdCategoria']
_descricaoBem = request.form['inputDescricaoBem']
_valor = request.form['inputValor']
_fornecedor = request.form['inputFornecedor']
_nfNumero = resquest.form['inputNfNumero']
_nfSerie = request.form['inputNfSerie']
_dtCompra = resquest.form['inputDtCompra']
_departamento = request.form['inputDepartamento']
_local = request.form['inputLocal']
_responsavel = resquest.form['inputResponsavel']
_estadoBem = request.form['inputEstadoBem']
_dtUltimaRev = request.form['inputDtUltimaRev']
_dtProximaRev = request.form['inputDtProximaRev']
_idade = request.form['inputIdade']
_vidaUtil = request.form['inputVidaUtil']
_trocarReformar = request.form['inputTrocaReforma']
_valorTT = request.form['inputValorTT']
curDb.callproc('sp_addProperty',(_tag,_idCategoria,_descricaoBem,_valor,_fornecedor,
_nfNumero,_nfSerie,_dtCompra,_departamento,_local,
_responsavel,_estadoBem,_dtUltimaRev,_dtProximaRev,
_idade,_vidaUtil,_trocarReformar,_valorTT))
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_addProperty',(_departamento,_user))
data = cursor.fetchall()
if len(data) is 0:
conectaDb.commit()
return redirect('/userHome')
else:
return render_template('error.html',error = 'An error occurred!')
else:
return render_template('error.html',error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html',error = str(e))
finally:
cursor.close()
conn.close()
This function is returning the following error:
UnboundLocalError: local variable 'cursor' referenced before assignment
And the function below is the same structure and does not return error.
#app.route('/addStatus',methods=['POST'])
def addStatus():
try:
if session.get('user'):
_status = request.form['inputStatus']
_user = session.get('user')
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_addStatus',(_status,_user))
data = cursor.fetchall()
if len(data) is 0:
conn.commit()
return redirect('/userHome')
else:
return render_template('error.html',error = 'An error occurred!')
else:
return render_template('error.html',error = 'Unauthorized Access')
except Exception as e:
return render_template('error.html',error = str(e))
finally:
cursor.close()
conn.close()
I would be very grateful if someone can help me with this problem.
I was assigning the parameter request.form the aliases incorrectly.
Some aliases was getting request.form where the right would request.form
I am running into an issue with parts of my code i have added my errors at the bottom. The issue is arising around the sqllite3.operationError part. i attempted removing it but when i do another error occurs for line 68 'def getpath():', i cant see why the errors are showing up any and all help is appreciated as always thanks. My code is generally for taking Login data out of my database and displaying in an csv file
import os
import sys
import sqlite3
try:
import win32crypt
except:
pass
import argparse
def args_parser():
parser = argparse.ArgumentParser(description="Retrieve Google Chrome Passwords")
parser.add_argument("--output", help="Output to csv file", action="store_true")
args = parser.parse_args()
if args.output:
csv(main())
else:
for data in main():
print (data)
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print('[!] Make sure Google Chrome is not running in the background')
sys.exit(0)
elif (e == 'no such table: logins'):
print('[!] Something wrong with the database name')
sys.exit(0)
elif (e == 'unable to open database file'):
print('[!] Something wrong with the database path')
sys.exit(0)
else:
print (e)
sys.exit(0)
return info_list
def getpath():
if os.name == "nt":
# This is the Windows Path
PathName = os.getenv('localappdata') + '\\Google\\Chrome\\User Data\\Default\\'
if (os.path.isdir(PathName) == False):
print('[!] Chrome Doesn\'t exists')
sys.exit(0)
return PathName
def csv (info):
with open ('chromepass.csv', 'wb') as csv_file:
csv_file.write('origin_url,username,password \n' .encode('utf'))
for data in info:
csv_file.write(('%s, %s, %s \n' % (data['origin_url'], data['username'], data['password'])).encode('utf-8'))
print ("Data written to Chromepass.csv")
if __name__ == '__main__':
args_parser()
Errors
Traceback (most recent call last):
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 90, in <module>
args_parser()
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 19, in args_parser
for data in main():
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 35, in main
for information in value:
TypeError: 'builtin_function_or_method' object is not iterable
Right way is:
except sqlite3.OperationalError as e:
And you main() should be like:
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print '[!] Make sure Google Chrome is not running in the background'
sys.exit(0)
elif (e == 'no such table: logins'):
print '[!] Something wrong with the database name'
sys.exit(0)
elif (e == 'unable to open database file'):
print '[!] Something wrong with the database path'
sys.exit(0)
else:
print e
sys.exit(0)
return info_list