How do i go about something like this, I want to check if a user exists against a table in python, and if the user exists , it should report that the particular user exists, else if the user does not, it should register (insert the user into the mysql database)
So far, this is what my code is looking like
#app.route('/api/user',methods=['POST'])
def create_user():
_json = request.json
_email = _json['email']
_phone = _json['phone']
_password = _json['password']
fullname = 'NULL'
custID = '123456'
#conn = mysql.connect()
#cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor = mysql.connection.cursor()
checkuser = 'select email from accounts where email = %s' # check if user exists here.
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
#query = "update empData set name = %s, email = %s, phone = %s, address = %s, salary = %s"
bindData = (_email, _phone, _password , fullname , custID)
cursor.execute(query,bindData)
mysql.connection.commit()
cursor.close()
output = {'email':_email, 'phone':_phone, 'fullname':fullname, 'custID':custID, 'message':'ok'}
return jsonify({'result':output}),200
How do I go about something like this, I started out flask a week ago.
Edits
This is what i been working on, but it complains about indentation. Code is looking like so
#app.route('/api/user', methods=['POST'])
def create_user():
_json = request.json
_email = _json['email']
_phone = _json['phone']
_password = _json['password']
fullname = 'NULL'
custID = '123456'
cursor = mysql.connection.cursor()
checkuser = 'select email from accounts where email = %s'
bindData = (_email)
cursor.execute(query,bindData)
acc = cursor.fetchone()
if acc:
return jsonify({'message':'User exists, Please Login'})
elif:
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
bindData = (_email, _phone, _password , fullname , custID)
cursor.execute(query,bindData)
mysql.connection.commit()
cursor.close()
output = {'email':_email, 'phone':_phone, 'fullname':fullname, 'custID':custID, 'message':'ok'}
return jsonify({'result':output}),200
Edits 2
So I made some Edits for the second time, it just fires back Error 500 when i am testing with Postman.
My code is looking Thus
#app.route("/api/user", methods=["POST"])
def create_user():
_json = request.json
_email = _json["email"]
_phone = _json["phone"]
_password = _json["password"]
fullname = "NULL"
custID = "123456"
cursor = mysql.connection.cursor()
cursor.execute('select * from accounts where email = %s', _email)
acc = cursor.fetchone()
if acc:
return jsonify({"message": "User exists, Please Login"})
else:
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
bindData = (_email, _phone, _password, fullname, custID)
cursor.execute(query, bindData)
mysql.connection.commit()
cursor.close()
output = {
"email": _email,
"phone": _phone,
"fullname": fullname,
"custID": custID,
"message": "ok",
}
return jsonify({"result": output}), 200
it says this is where the Error is according to the Log
which is here cursor.execute('select * from accounts where email = %s', _email) Is there something i missed?
I did a similar program a few weeks ago which is the same concept but a slightly rudamentary approach, I hope it helps.
Assuming the SQL connection was properly setup and in my case using the table "userdata" and searching the column "username"
def login(user):
cursor.execute("SELECT * FROM userdata WHERE username = '%s';" %(user,))
record = cursor.fetchone()
if record != None: # record = ('<user>','<password>')
if record[1]==password:
login_success()
else:
login_failed()
else:
data_not_found()
This activates after the button press.
login_btn = Button(root,text='Login',command=lambda:[del_failed_msg(),get_input(),login(name)])
So, here, the search result in the database should be a single record which I have stored under a variable 'record' using fetchone() function.
The fetchone() function has returned a tuple of my desired search which I can traverse to get my desired values within the record.
I got it to work!
I had to do some reading and searching thru, this gave me an idea of what to do. Its like searching thru a List or something in the Database to get adequate results
So i saw this,https://stackoverflow.com/questions/21740359/python-mysqldb-typeerror-not-all-arguments-converted-during-string-formatting
Then changed my code from this
cursor.execute('select * from accounts where email = %s', _email
to this :
cursor.execute('select * from accounts where email = %s', [_email]
And it gave the actual response I wanted it to give. Just in case it should help someone.
Thanks everyone.
Edit
Below is what the code Looks like after the work arounds.
#app.route("/api/user", methods=["POST"])
def create_user():
_json = request.json
_email = _json["email"]
_phone = _json["phone"]
_password = _json["password"]
fullname = "NULL"
custID = "123456"
cursor = mysql.connection.cursor()
cursor.execute("select * from accounts where email = %s", [_email])
acc = cursor.fetchone()
if acc:
return jsonify({"message": "User exists, Please Login"})
else:
query = "insert into accounts (email,phone,fullname,password,custID) values (%s, %s,%s, %s,%s)"
bindData = (_email, _phone, fullname, _password, custID)
cursor.execute(query, bindData)
mysql.connection.commit()
cursor.close()
output = {
"email": _email,
"phone": _phone,
"fullname": fullname,
"custID": custID,
"message": "ok",
}
return jsonify({"result": output}), 200
Related
I'm trying to run a function to add a user to a flask website built with python
here is the function
def add_user(self, name, email, password, is_admin):
query = f"""
SELECT name FROM loginUsers WHERE email='{email}';
"""
response = self.conn.execute(query)
existing_user = [rec for rec in response]
if not existing_user:
created_on = datetime.utcnow()
user = User(name=name, email=email, created_on=created_on, is_admin=is_admin).set_password(password)
print(user)
query = f"""
INSERT INTO loginUsers
(name, email, created_on, password, is_admin)
VALUES
('{name}', '{email}', '{created_on}', '{pass_hashed}', {is_admin});
"""
cursor = self.conn.cursor()
cursor.execute(query)
self.conn.commit()
print('New user created')
cursor.close()
return f'User {name} - {password} is already exist'
I've tried putting in my own values multiple times and its not adding to the loginUsers table. PLEASE HELP!!!! Can this be demonstrated with example?
def add_user(self, name, email, password, is_admin):
query = f"""
SELECT name FROM loginUsers WHERE email='{email}';
"""
response = self.conn.execute(query)
existing_user = [rec for rec in response]
if not existing_user:
created_on = datetime.utcnow()
user = User(name=name, email=email, created_on=created_on, is_admin=is_admin).set_password(password)
print(user)
query = f"""
INSERT INTO loginUsers
(name, email, created_on, password, is_admin)
VALUES
('{name}', '{email}', '{created_on}', '{pass_hashed}', {is_admin});
"""
cursor = self.conn.cursor()
cursor.execute(query)
self.conn.commit()
print('New user created')
cursor.close()
return f'User {name} - {password} is already exist'
enter image description here
I dont know whats wrong most likely a problem in the code, i have had my teacher look ober it and he can't se the problem ether
if row_count == 1:
event3, values3 = bank_win.read(timeout=100)
bank_win_active = True
sql = "SELECT username FROM user WHERE username =%s AND password = %s"
print(username)
mycursor.execute(sql, (username, pw))
myresult = mycursor.fetchone()
myid = myresult[0]
logg_inn_win.Hide()
bank_win.UnHide()
sql = f"SELECT money FROM user WHERE username ='{myid}'"
print(myid)
mycursor.execute(sql, myid)
myresult = mycursor.fetchone()
print(myresult)
I want to prevent duplicate usernames when people register.
Here is my code snippet:
def submit(self):
username_info = username.get()
username_password = password.get()
#connect to db
db = mysql.connector.connect(host = 'localhost', user = 'root', password = '', database = 'user')
#create a cursor
mycursor = db.cursor()
#insert to db
sql = ("INSERT INTO useraccess (user_type, password) VALUES (%s, %s)")
query = (username_info, username_password)
mycursor.execute(sql, query)
#commit
db.commit()
#create a messagebox
messagebox.showinfo("Registration", "Successfully Register")
#if username has been used
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
user_query = (username_info)
mycursor.execute(find_user, user_query)
#if (username == username_info):
if mycursor.fetchall():
messagebox.showerror("Registration", "The username chosen is already used. Please select another username")
else:
messagebox.showinfo("Registration", "Account Created!")
But every time I run it, although the username has been registered in the db, it only shows the successfully created messagebox and error:
ValueError: Could not process parameters.
Anyone can help me to solve this problem?
I believe the source of the problem is in the line
user_query = (username_info)
It should be
user_query = (username_info,)
The trailing comma is the syntactic difference between an expression in parentheses and a tuple.
Another issue with code is the query:
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
Which should be:
find_user = ("SELECT * FROM useraccess WHERE user_type = %s")
Have you checked these variables,
username_info = username.get()
username_password = password.get()
are they in proccesable formats? (i.e. can you directly put the username.get() into user_type ?)
I'm not familiar with this way of passing a parameter
find_user = ("SELECT * FROM useraccess WHERE user_type = ?")
have you double checked this? (why not the %s method?)
also, you probably get the "Account Created!" because mycursor.fetchall() fails.
I am currently having major issues writing foods from a JSON to my database. The GET method works just fine. However, when I receive a JSON, it is not properly writing to the database.
What I do is the following
Write a new meal to the database (creates a new meal/cart id via autoincrement)
Utilize the LAST_INSERT_ID() command to write new foods to that meal/cart.
Once I get here writing one food is fine, however if there is numerous foods, I can't seem to get it to write the other foods from the JSON to the database.
The JSON I am receiving is as follows:
Endpoint: /meallog
Request params:{
method: ”post”,
headers: headers,
url: string,
data:{
userId: string,
date: string,
mealData:{
mealName: String,
food: [
{
id:string,
foodname:string,
numCal:int,
servingSize:int,
servingSizeUnit:string,
totalCalories:int
},
{
(repeat above)
}
]
}
}
}
Response: (JSON Object)
{
code: 200/400,
message: String
}
The Code I currently have for my post is below:
elif request.method == 'POST':
jsondata = {}
code={}
user_id = request.json['user_id']
date = request.json['date']
mealName = request.json['mealName']
food_id = request.json['id']
food_name = request.json['foodname']
food_cal = request.json['numCal']
serving_size = request.json['servingSize']
serving_unit = request.json['servingSizeUnit']
totalCal = request.json['totalCalories']
postmeal = conn.cursor()
INS_meal = "INSERT INTO user_cart (user_id, datetime, cart_cal, cart_name) VALUES (%s, %s, %s, %s);"
postmeal.execute(INS_meal, (user_id, date, totalCal, mealName))
conn.commit()
postfood = conn.cursor()
INS_food = "INSERT INTO food_log VALUES (LAST_INSERT_ID(), %s, %s, %s, %s, %s);"
postfood.execute(INS_food, (food_id, food_name, food_cal, serving_size, serving_unit))
conn.commit()
if postfood.execute and postmeal.execute:
code['code'] = '200'
code['message'] = 'Success! INSERTED values into both food_log and user_cart'
else:
code['code'] = '400'
code['message'] = 'Error Connecting to DB. Cant insert into food_log and-or user_cart'
jsondata['code'] = code['code']
jsondata['message'] = code['message']
return(json.dumps(jsondata))
Essentially I'd like it to gather every food that comes in, and write the entire food objects in the array to the food table seamlessly.
I fixed my issue and utilized LAST_INSERT_ID() in a more structured way, as well as to properly loop through the foods incoming.
elif request.method == 'POST':
jsondata = {}
code={}
#with open('inc.json') as json_data:
#d = json.load(json_data)
#print(d)
user_id = request.json['userId']
date = request.json['date']
mealName = request.json['mealData']['mealName']
foodlist = request.json['mealData']['food']
postmeal = conn.cursor()
INS_meal = "INSERT INTO user_cart (user_id, datetime, cart_name) VALUES (%s, %s, %s);"
postmeal.execute(INS_meal, (user_id, date, mealName))
conn.commit()
postmeal.execute("select LAST_INSERT_ID();")
SEL_MEAL_ID = postmeal.fetchone()[0]
food_str = ""
for food in foodlist:
print (food)
food_str+="({}, '{}', '{}', {}, {}, '{}', {}), ".format(SEL_MEAL_ID, food['id'], food['foodname'], food['numCal'], food['servingSize'], food['servingSizeUnit'], food['totalCalories'])
postfood = conn.cursor()
INS_food = "INSERT INTO food_log VALUES {};".format(food_str[:-2]) # To exclude the last comma in the food string
postfood.execute(INS_food)
conn.commit()
if postfood.execute and postmeal.execute:
code['code'] = '200'
code['message'] = 'Success! INSERTED values into both food_log and user_cart'
else:
code['code'] = '400'
code['message'] = 'Error Connecting to DB. Cant insert into food_log and-or user_cart'
jsondata['code'] = code['code']
jsondata['message'] = code['message']
return(json.dumps(jsondata))
I have tried 3 different variations of sqlite3 statement to SELECT a data:
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
References for these statements are from 1 2. However, none of them worked. I suspect that I am doing something really silly but can't seem to figure this out.
I want to be able to print out the data of username "monkey". Appreciate any help to point out my silly mistake.
import sqlite3
import datetime
def get_user(connection, rows='all', username=None ):
"""Function to obtain data."""
#create cursor object from sqlite connection object
cursor = connection.cursor()
if rows == 'all':
print("\nrows == 'all'")
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()
for row in data:
print(row)
if rows == 'one':
print("\nrows == 'one'")
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
#cursor.execute('''SELECT * FROM users WHERE username = ?;''', (username,))
#cursor.execute('SELECT * FROM users WHERE username = "monkey1" ')
data = cursor.fetchone()
print('data = ',data)
cursor.close()
return data
def main():
database = ":memory:"
table = """ CREATE TABLE IF NOT EXISTS users (
created_on TEXT NOT NULL UNIQUE,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL UNIQUE
); """
created_on = datetime.datetime.now()
username = 'monkey'
email = 'monkey#gmail'
created_on1 = datetime.datetime.now()
username1 = 'monkey1'
email1 = 'monkey1#gmail'
# create a database connection & cursor
conn = sqlite3.connect(database)
cursor = conn.cursor()
# Insert data
if conn is not None:
# create user table
cursor.execute(table)
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on, email, username))
cursor.execute('INSERT INTO users VALUES(?,?,?)',(
created_on1, email1, username1))
conn.commit()
cursor.close()
else:
print("Error! cannot create the database connection.")
# Select data
alldata = get_user(conn, rows='all')
userdata = get_user(conn, rows='one', username=username )
print('\nalldata = ', alldata)
print('\nuserdata = ', userdata)
conn.close()
main()
Your table definition has the fields in order created_on, username, email but you inserted your data as created_on, email, username. Therefore the username of the first row was 'monkey#gmail'.
A good way to avoid this kind of mistake is to specify the columns in the INSERT statement rather than relying on getting the order of the original table definition correct:
INSERT INTO users (created_on, email, username) VALUES (?,?,?)