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.
Related
The level system does not work
#bot.event
async def on_message(message):
user = message.author.id
conn = sqlite3.connect('server.db')
cur = conn.cursor()
cur.execute('SELECT xp, lvl FROM users WHERE id = ?')
results = cur.fetchone()
row = results[0]
old_xp = row[0]
old_level = row[1]
new_xp = old_xp + 1
if new_xp == 2:
new_level = 1
else:
new_level = old_level
cur.execute('UPDATE users SET xp = ?, level = ? WHERE id = ?', (new_xp, new_level, user)
)
conn.commit()
conn.close()
Error:
cur.execute('SELECT xp, lvl FROM users WHERE id = ?')
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.
You need to pass a value for the id.
#bot.event
async def on_message(message):
user = message.author.id
conn = sqlite3.connect('server.db')
cur = conn.cursor()
cur.execute('SELECT xp, lvl FROM users WHERE id = ?', (user,))
results = cur.fetchone()
Note that you need to put a comma here: (user,)
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)
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
This is my Bottle code
import sqlite3
import json
from bottle import route, run, request
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def db_connect():
conn = sqlite3.connect('inventory.db')
conn.row_factory = dict_factory
return conn, conn.cursor()
#route('/inventory', method='GET')
def get_inventory():
conn,c=db_connect()
c.execute("SELECT id, name, category, location, date, amount FROM inventory")
result = c.fetchall()
json_result=json.dumps(result)
return json_result
#route('/inventory/get/:id', method='GET')
def get_item(id):
conn,c=db_connect()
c.execute("SELECT id, name, category, location, date, amount FROM inventory WHERE id=?",(id, ))
result=c.fetchall()
json_result=json.dumps(result)
return json_result
#route('/inventory/new', method='POST')
def add_item():
name = request.POST.get('name')
category = request.POST.get('category')
location = request.POST.get('location')
date = request.POST.get('date')
amount = request.POST.get('amount')
conn,c=db_connect()
c.execute("INSERT INTO inventory (name, category, location, date, amount) VALUES (?,?,?,?,?)", (name,category,location,date,amount))
new_id = c.lastrowid
conn.commit()
c.close()
return '<p>The entry with id %d has been added to the database</p>' %new_id
#route('/inventory/delete/:id', method='DELETE')
def delete_item(id):
conn,c=db_connect()
c.execute("DELETE FROM inventory WHERE id =?", (id, ))
conn.commit()
c.close()
return 'The entry with id %s has been deleted from the database' %id
#route('/inventory/edit/:id', method='PUT')
def edit_item(id):
name = request.PUT.get('name')
category = request.PUT.get('category')
amount = request.PUT.get('location')
location = request.PUT.get('date')
date = request.PUT.get('amount')
conn,c=db_connect()
c.execute("UPDATE Inventory SET name=?, category=?, location=?, date=?, amount=? WHERE id=?", (name, category, location, date, amount,id))
conn.commit()
c.close();
return '<p>The entry with id %s has been edited in the database</p>' %id
run(reloader=True)
I am trying to make the make the edit_item method to work.
When I call it with curl
curl -X PUT -d "name=aa&category=bb&amount=23&location=xx&date=21-10-2014" http://localhost:8080/inventory/edit/2
I get a server error which says
raise AttributeError('Atrribute %r is not defined.' % name)
AttributeError: Attribute 'PUT' not defined'
What should i do ?
Instead of this,
name = request.PUT.get('name')
use this:
name = request.params.get('name')
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'