Python script 500 error - python

I am currently trying to run a fairly basic python script on my web server. I've gotten this same error when I try to import something that isn't installed on the server so like
import json
I've ran a basic script on the server before so I know that python can run on it. The script is working in my python IDE without any problems but when I put it into my server, I get a 500 error. Any ideas as to why this is occuring would be much appreciated. My webhost is JustHost.com and it uses the CPanel. I did contact them and they said it was something about my script.
#! /usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost", "username","password","database")
CUR = db.cursor()
def get_password(username):
sql = "select Password from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()[0]
if result == None:
return "User does not exist"
else:
return result[0]
def get_comment(username):
sql = "select Comments from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User has not updated comment"
else:
return result[0]
def get_email(username):
sql = "select Email from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User does not exist"
else:
return result[0]
def get_longitude(username):
sql = "select Longitude from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update location"
else:
return result[0]
def get_latitude(username):
sql = "select Latitude from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update location"
else:
return result[0]
def get_address(username):
sql = "select Address from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update email"
else:
return result[0]
def friends_list(username):
sql = "select all friend from accepted_req where userLoggedIn=%s"
CUR.execute(sql, [username])
result=[]
query = CUR.fetchall()
if query == None:
return "User has no friends"
else:
for friend in query:
result.append(friend[0])
return result
def markers_on_map(username):
friendsList = friends_list(username)
fullFriendsList = []
for friend in friendsList:
UserDictionary = {}
UserDictionary["Username"] = friend
UserDictionary["Comment"] = str(get_comment(friend))
UserDictionary["Latitude"] = get_latitude(friend)
UserDictionary["Longitiude"] = get_longitude(friend)
fullFriendsList.append(UserDictionary)
return fullFriendsList
print "Content-type: text/html\n\n"
print markers_on_map("brock")

I fixed it by making it looks exactly perfect in standards of my webhost. the new script now looks like this
#! /usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost", "username","password","database")
CUR = db.cursor()
def get_password(username):
sql = "select Password from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()[0]
if result == None:
return "User does not exist"
else:
return result[0]
def get_comment(username):
sql = "select Comments from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User has not updated comment"
else:
return result[0]
def get_email(username):
sql = "select Email from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User does not exist"
else:
return result[0]
def get_longitude(username):
sql = "select Longitude from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update location"
else:
return result[0]
def get_latitude(username):
sql = "select Latitude from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update location"
else:
return result[0]
def get_address(username):
sql = "select Address from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update email"
else:
return result[0]
def friends_list(username):
sql = "select all friend from accepted_req where userLoggedIn=%s"
CUR.execute(sql, [username])
result=[]
query = CUR.fetchall()
if query == None:
return "User has no friends"
else:
for friend in query:
result.append(friend[0])
return result
def markers_on_map(username):
friendsList = friends_list(username)
fullFriendsList = []
for friend in friendsList:
UserDictionary123 = {}
UserDictionary123["Username"] = friend
UserDictionary123["Comment"] = str(get_comment(friend))
UserDictionary123["Latitude"] = get_latitude(friend)
UserDictionary123["Longitiude"] = get_longitude(friend)
fullFriendsList.append(UserDictionary123)
return fullFriendsList

Related

MySQL: I don't understand why this is happening?

import sqlite3
import traceback
from time import sleep
import mysql.connector
def check_user(user_id):
conn = mysql.connector.connect(host='localhost', database='online', user='root1', password='rootRRR111_')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS online(id INT, last_online_date TEXT)')
conn.commit()
select = "SELECT * FROM online WHERE id = %s LIMIT 0, 1"
result = cur.execute(select, (user_id,))
if result is None:
insert = ('INSERT INTO online (id, last_online_date) VALUES (%s, %s)')
cur.reset()
cur.execute(insert, (user_id, online_time))
conn.commit()
def update_online_status(user_id, online_time):
conn = mysql.connector.connect(host='localhost', database='online', user='root1', password='rootRRR111_')
cursor = conn.cursor()
select = 'SELECT last_online_date FROM online WHERE id = %s'
result = cursor.execute(select, (user_id,))
old_online = result
online_time = f'{old_online},{online_time}'
cursor.reset()
cursor.execute('UPDATE online SET last_online_date = %s WHERE id = %s', (online_time, user_id))
conn.commit()
app = Client("my_account")
app.start()
while True:
try:
with open('ids.ini', 'r') as file:
users = file.read().splitlines()
for user in users:
result = app.get_users(user)
user_id = result['id']
if result['status'] == 'offline':
unix_timestamp = float(result['last_online_date'])
local_timezone = tzlocal.get_localzone()
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
online_time = local_time.strftime("%Y/%m/%d %H:%M:%S")
elif result['status'] == 'online':
now = datetime.now()
online_time = now.strftime("%Y/%m/%d %H:%M:%S")
check_user(user_id)
update_online_status(user_id, online_time)
# sleep(300)
except Exception:
traceback.print_exc()
continue
app.stop()
I am writing a program that would read the online status of a user in telegram.
Instead of writing online to an existing user, a huge number of identical rows appear in the database.
Example:
Table with repetitions
When I try to fix something, there are a lot of errors.
mysql.connector.errors.programmingerror: not all parameters were used in the sql statement
mysql.connector.errors.internalerror: unread result found
and other...
Pls help!!

Python-MySQL query does not showing results including the previous import in same query

I have a function what is adding new records in to Mysql database after scanning a barcode. Function is working but there is a problem with returning result on the App screen.
When I scan the barcode first time it does not return any results even when i can see that the new record was created. But when i scan the barcode second time it returns only 1 record.
Edit:(added more about the issue)
And after that it is always -1 record, which would not be problem i could add +1 to all results but the problem is the first one, as it returns nothing at all.
I tried to use time.sleep(.3) between the queries but that did not have any effect.
I now wonder if the Python code is wrong or my SQL query should be somehow different.
def db_execute3(config, sql, val):
mydb = mysql.connector.connect(**config)
mycursor = mydb.cursor()
try:
mycursor.execute(sql, val)
mydb.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.CR_CONN_HOST_ERROR:
popip.open()
Clock.schedule_once(popip.dismiss, 3)
elif err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
popx.open()
Clock.schedule_once(popx.dismiss, 3)
elif err.errno == errorcode.ER_BAD_DB_ERROR:
popdb.open()
Clock.schedule_once(popdb.dismiss, 3)
elif err.errno == errorcode.ER_NO_REFERENCED_ROW_2:
popbr.open()
Clock.schedule_once(popbr.dismiss, 3)
else:
mycursor.close()
def inbsort_btndwn(self, _):
cont = self.container_no.text.upper()
barc = self.sku_barcode.text.upper()
sort_worknumb = self.sort_worknumb.text.upper()
val = (sort_worknumb, cont, barc)
valx = (cont,barc)
if barc is "" and cont is "":
errorsound.play()
self.pallet_sku.text = ""
self.number_sku.text = ""
Clock.schedule_once(self.focus_container_no, 0.2)
elif barc is "" and cont is not "":
errorsound.play()
self.pallet_sku.text = ""
self.number_sku.text = ""
Clock.schedule_once(self.focus_sku_barcode, 0.2)
else:
try:
mydb = mysql.connector.connect(**config)
checkupd = mydb.cursor(prepared=True)
sqlq = "select * from inb_container where `container_no` = %s and `sku_code` = %s;"
checkupd.execute(sqlq, valx)
record = checkupd.fetchone()
if record is None:
errorsound.play()
popuni.content.text = "No records for scanned Barcode!"
popuni.open()
Clock.schedule_once(popuni.dismiss, 2)
Clock.schedule_once(self.clear_barcode, .2)
Clock.schedule_once(self.focus_sku_barcode, 0.21)
else:
correctsound.play()
sql = "INSERT INTO inb_sor_con (`work_number`, `container_no`,`sku_barcode`) VALUES (%s, %s, %s)"
db_execute3(config, sql, val)
sqlz = "SELECT ic.sort_box,ic.sort_pallet FROM inb_container ic, " \
"inb_sor_con ib WHERE ic.container_no =ib.container_no and ic.sku_code = ib.sku_barcode " \
"and ic.container_no = %s and ic.sku_code = %s"
valz = (cont, barc)
checkupd.execute(sqlz, valz) #v289-ukan1012044-n10 #msku8416005
myresult = checkupd.fetchall()
for row in myresult:
xxx = "Scanned: {} of: {}".format(checkupd.rowcount, row[0])
zzz = "{}".format(row[1])
self.pallet_sku.text = zzz
self.number_sku.text = xxx
Clock.schedule_once(self.clear_barcode, 0.2)
Clock.schedule_once(self.focus_sku_barcode, 0.21)
except mysql.connector.Error as err:
print(err.errno)
pass
This is the database:
create table inb_container(
`container_no` varchar(25) NOT NULL,
`sku_code` varchar(40) NOT NULL,
`sort_box` int(5),
`sort_pcs` int(6),
`sort_pallet` varchar(3),
Unique (container_no,sku_code)
);
create table inb_sor_con(
`id_scan` int(6) auto_increment not null primary key,
`work_number` varchar(12),
`container_no` varchar(25) NOT NULL,
`sku_barcode` varchar(40) NOT NULL,
`sort_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (work_number) REFERENCES user_logins(work_number),
FOREIGN KEY (container_no) REFERENCES inb_container(container_no));
As mentioned, I'd suggest refactoring your code so it's not mixing UI code with database access. That way you can more easily test each bit of your program (either manually, from a separate module) or automatically using unit tests or such.
You can also freely create new cursors, don't reuse a single one.
Here's one such refactoring...
def find_container(db, *, container_no, barcode):
cursor = db.cursor()
cursor.execute(
"select * from inb_container where `container_no` = %s and `sku_code` = %s",
(container_no, barcode),
)
return cursor.fetchone()
def insert_sor_con(db, *, sort_worknumb, container_no, barcode):
cursor = db.cursor()
cursor.execute(
"INSERT INTO inb_sor_con (`work_number`, `container_no`,`sku_barcode`) VALUES (%s, %s, %s)",
(sort_worknumb, container_no, barcode),
)
db.commit()
def get_scan_results(db, *, container_no, barcode):
cursor = db.cursor()
cursor.execute(
"""
SELECT ic.sort_box,ic.sort_pallet
FROM inb_container ic, inb_sor_con ib
WHERE (
ic.container_no = ib.container_no AND
ic.sku_code = ib.sku_barcode AND
ic.container_no = %s AND
ic.sku_code = %s
)""",
(container_no, barcode),
)
return cursor.fetchall()
def show_error(message):
errorsound.play()
popuni.content.text = message
popuni.open()
Clock.schedule_once(popuni.dismiss, 2)
class SomeUI:
def inbsort_btndwn(self, _):
container_no = self.container_no.text.upper()
barcode = self.sku_barcode.text.upper()
sort_worknumb = self.sort_worknumb.text.upper()
if not (barcode and container_no):
errorsound.play()
self.pallet_sku.text = ""
self.number_sku.text = ""
if not barcode:
Clock.schedule_once(self.focus_sku_barcode, 0.2)
else:
Clock.schedule_once(self.focus_container_no, 0.2)
return
try:
with mysql.connector.connect(**config) as mydb:
container_record = find_container(
mydb, container_no=container_no, barcode=barcode
)
if container_record:
correctsound.play()
insert_sor_con(
mydb,
sort_worknumb=sort_worknumb,
container_no=container_no,
barcode=barcode,
)
scan_results = list(
get_scan_results(mydb, container_no=container_no, barcode=barcode)
)
for sort_box, sort_pallet in scan_results:
self.pallet_sku.text = "{}".format(sort_pallet)
self.number_sku.text = "Scanned: {} of: {}".format(
len(scan_results), sort_box
)
else:
show_error("No records for scanned Barcode!")
except Exception as exc:
# may want to use `traceback.print_traceback()` here for more detail
print(exc)
show_error(f"Error: {exc}")
Clock.schedule_once(self.clear_barcode, 0.2)
Clock.schedule_once(self.focus_sku_barcode, 0.21)

Python Unbound Local variabel

Why my check_email error, i dont know how to fix it
def getLoginDetails():
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
if 'email' not in session:
loggedIn = False
firstName = ''
noOfItems = 0
else:
loggedIn = True
cur.execute("SELECT userId, firstName FROM users WHERE email = '" + session['email'] + "'")
userId, firstName = cur.fetchone()
if 'email' == "admin#shop.com":
check_email = True
else:
check_email = False
cur.execute("SELECT count(productId) FROM kart WHERE userId = " + str(userId))
noOfItems = cur.fetchone()[0]
conn.close()
return (loggedIn, firstName, noOfItems, check_email)
#app.route("/")
def root():
loggedIn, firstName, noOfItems, check_email = getLoginDetails()
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute('SELECT productId, name, price, description, image, stock FROM products')
itemData = cur.fetchall()
cur.execute('SELECT categoryId, name FROM categories')
categoryData = cur.fetchall()
itemData = parse(itemData)
return render_template('home.html', itemData=itemData, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems, categoryData=categoryData, check_email=check_email)
This makes no sense to me as I clearly initialize check_email as one of the first lines of my code, and I even labeled it as global just to be safe and make sure it was within the scope of all my methods.
Error: UnboundLocalError: local variable 'check_email' referenced before assignment
You don't assign to check_email if 'email' not in session.

How to get multiple rows and columns using mysql db through django

Getting single row and single column below code is executed sucessfully. How to get multiple columns and rows?
views.py
def get_db_data(request):
conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject")
cursor = conn.cursor ()
cursor.execute ("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id %s.</body></html>" % email_address
else:
row = cursor.fetchone()
html = "<html><body>E-Mail address %s.</body></html>" % row[0]
return HttpResponse(html)
Please help me with this.
UPD:
def get_db_data(request):
conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject")
cursor = conn.cursor ()
cursor.execute ("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id %s.</body> <html>" % email_address
else:
html = "<html>"
for x in cursor.fetchone():
html += "<body>E-Mail address %s.</body>" % x
html += "<html>"
return HttpResponse(html)
All columns
cursor.execute("SELECT * FROM user")
All rows:
cursor.fetchall()
for row in cursor.fetchall():
html = ...
and there is one more thing it is not about your problem but you should keep in mind while write if
The values 0, None, False all are false for if statement so it's better to write if not cursor.rowcount instead if cursor.rowcount==0
you can use this.
import MySQLdb
import MySQLdb.cursors
def get_db_data(request):
conn = MySQLdb.connect(host="localhost", user="test_user", passwd="test_pwd", db="myproject", cursorclass=MySQLdb.cursors.DictCursor)
cursor = conn.cursor()
cursor.execute("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id.</body></html>"
else:
htm = "<html><body>"
for row in cursor.fetchall():
html += "Id - {id}, E-Mail address - {email_address}, Mobile Number - {mobile_number}, City - {city}, State {state}. </br>".format(**row)
html += "</body></html>"
return HttpResponse(html)

MysqlDb and Pyqt4 comparing variables

I have a database in mysql, and I'm working in a app in QT4, I'm using Mysqldb connector, I'm already successfully connected to the database, but when I'm querying the table t_usuarios I don't know how to eval it. Can you help me? Thanks in advance.
Part of my code:
def chequeouser(self):
passwdcheck = str(txt_password.text())
usuariover = str(txt_usuario.text())
# datosLogin = "SELECT * FROM t_usuarios WHERE id_usuario = 'usuario' AND pasword = 'password'
cursor = dbase.cursor()
cursor.execute("SELECT id_usuario, password FROM t_usuarios WHERE id_usuario = %s AND password = %s", (usuariover, passwdcheck))
checar = cursor.fetchone()
Thanks for the user who answer me ... I do it, but with some modification as follow ..
passwdcheck = str(txt_password.text())
usuariocheck = str(txt_usuario.text())
# datosLogin = "SELECT * FROM t_usuarios WHERE id_usuario = 'usuario' AND pasword = 'password'
cursor = dbase.cursor()
cursor.execute("SELECT id_usuario, password FROM t_usuarios WHERE id_usuario = %s AND password = %s", (usuariocheck, passwdcheck))
row = cursor.fetchone()
if row == None:
print "no data:"+ usuariocheck
return
if row[1] == passwdcheck:
print "user and password combination is correct" +usuariocheck
else :
print "your input is incorrect"
I'm thinking do this in answer but I not sure if this is correct or not.
fetchone() returns a row of data. The first item is row[0], 2nd item is row[1], etc.
Example:
def chequeouser(self):
passwdcheck = str(txt_password.text())
usuariover = str(txt_usuario.text())
# datosLogin = "SELECT * FROM t_usuarios WHERE id_usuario = 'usuario' AND pasword = 'password'
cursor = dbase.cursor()
cursor.execute("SELECT id_usuario, password FROM t_usuarios WHERE id_usuario = %s AND password = %s", (usuariover, passwdcheck))
row = cursor.fetchone()
if not row:
print "no rows!"
return
if passwdcheck == row[1]:
print 'MATCH for user', row[0]
else:
print 'uhoh'

Categories