SQL Lite3 Add User - python

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

Related

Check if user exists before inserting into Mysql

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

SQL not updating a previous entry

Still new to API's so please excuse any novice mistakes
This is where I receive the input from another port and then it gets sent to PUT method
#app.route('/PUT', methods=['POST'])
def PUT_link():
first_name = request.form['fname']
last_name = request.form['lname']
number = request.form['number']
Methods.PUT(first_name, last_name, number)
return 'success'
This is the method that should update the number but it doesn't.
#classmethod
def PUT(cls, first_name, last_name, number):
connection = sqlite3.connect('data.db')
cur = connection.cursor()
query = "UPDATE contacts SET number=? WHERE firstname=? AND lastname=?"
cur.execute(query, (first_name, last_name, number))
connection.commit()
connection.close()
return 'Contact number updated'

User authentication not working in flask and sqlite

What I am trying to do is to get the email id and compare against the SQLite table.
If email exists in the table then I update the table with the emailid and random generated password and mail them.
If email does not exists in the table then I use insert query to enter the email as well as random generated password into the table.
After the insert or the update query is fired I mail them the generated password using Flask-mail
However I am unable to execute it
def sqliteconfig():
try:
conn = sqlite3.connect('auth.db',check_same_thread=False)
cur = conn.cursor()
conn.execute('CREATE TABLE IF NOT EXISTS auth (AID INTEGER PRIMARY KEY AUTOINCREMENT, emailid TEXT UNIQUE, otp TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP)')
cur.close()
except Exception as e:
print(e)
return 'DatabaseDown'
# return 'DatabaseDown'
return conn
#bp.route('/')
def index_redirect():
return redirect(url_for('devcon.login'))
#bp.route('/login',methods=['GET','POST'])
def login():
conn = sqliteconfig()
cur = conn.cursor()
if request.method == 'POST':
emailid = request.form['emailid']
if emailid != "":
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
passlen = 8
password = "".join(random.sample(s,passlen ))
conn.execute('select count(*) from auth where emailid=(?)',[emailid])
rows = cur.fetchall();
if len(rows) == 0:
conn.execute('insert into auth(email,otp) values(?,?)',[emailid,password])
conn.commit()
elif len(rows)==1:
conn.execute('update auth SET otp=(?) where emailid=(?)',[emailid,password])
conn.commit()
return str(rows)
return render_template("login/login.html")
The Particular problem I am facing right know is SELECT COUNT query returns nothing and INSERT query throws constraint violation error of unique emailid.
I am looking forward if there is any better way to do this
For the first error where SELECT COUNT returns nothing, in Sqlite3 select * is used instead of select count(*). Therefore your code should be:
rows = conn.execute('SELECT * FROM auth WHERE emailid = ?',(emailid,)).fetchall()
For the second insertion error, you may already have an equivalent emailid value stored into auth. That is the only reason why you would have a constraint violation of an unique emailid.
Another (potential) error is that you set otp to emailid and password to emailid, while the order should be reversed:
conn.execute('update auth SET otp=(?) where emailid=(?)',[emailid,password])
Instead, do this:
conn.execute('UPDATE auth SET otp = ? WHERE emailid = ?',(password, emailid))
Final code:
def sqliteconfig():
try:
conn = sqlite3.connect('auth.db',check_same_thread=False)
cur = conn.cursor()
conn.execute('CREATE TABLE IF NOT EXISTS auth (AID INTEGER PRIMARY KEY AUTOINCREMENT, emailid TEXT UNIQUE, otp TEXT, created_at TEXT DEFAULT CURRENT_TIMESTAMP)')
cur.close()
except Exception as e:
print(e)
return 'DatabaseDown'
# return 'DatabaseDown'
return conn
#bp.route('/')
def index_redirect():
return redirect(url_for('devcon.login'))
#bp.route('/login',methods=['GET','POST'])
def login():
conn = sqliteconfig()
cur = conn.cursor()
if request.method == 'POST':
emailid = request.form['emailid']
if emailid != "":
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
passlen = 8
password = "".join(random.sample(s,passlen ))
rows = conn.execute('SELECT * FROM auth WHERE emailid = ?',(emailid,)).fetchall()
if len(rows) == 0:
conn.execute('INSERT into auth (email, otp) VALUES (?, ?)',(emailid, password))
conn.commit()
elif len(rows)==1:
conn.execute('UPDATE auth SET otp = ? WHERE emailid = ?',(emailid, password))
conn.commit()
return str(rows)
return render_template("login/login.html")

SQLITE3 FROM table Select column WHERE Boolean statement

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 (?,?,?)

Why is my web application generating a 1064 (42000) error when trying to POST an INSERT query? [duplicate]

This question already has answers here:
How to create a "singleton" tuple with only one element
(4 answers)
Closed 6 years ago.
I'm trying to create a user registration page using Flask, MySQL and HTML forms. I'm running into this error when I try to post data from the form to the database. Can anyone see where I might have gone wrong with the SQL?
The full error received is:
1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1
My connection function is:
import mysql.connector
from flask import *
def connection():
conn = mysql.connector.connect(host="localhost", db="user_login",user="root",
password="password")
c = conn.cursor()
return c, conn
This is imported in the init.py file and called below:
class RegistrationForm(Form):
firstName = StringField('First Name', [validators.Length(min = 3, max = 25)])
lastName = StringField('Surname', [validators.Length(min = 3, max = 25)])
username = StringField('Username', [validators.Length(min = 4, max = 25)])
email = StringField('Email Address', [validators.Length(min = 6, max = 50)])
password = PasswordField('Password', [validators.required(),
validators.EqualTo('confirm', message = 'Passwords must match')])
confirm = PasswordField('Repeat Password')
#app.route('/register/', methods = ['GET', 'POST'])
def register_page():
try:
form = RegistrationForm(request.form)
if request.method == "POST" and form.validate():
firstName = form.firstName.data
lastName = form.lastName.data
username = form.username.data
email = form.email.data
password = form.password.data
is_admin = 0
c, conn = connection()
x = c.execute("SELECT * FROM users WHERE username = %s",(username))
if int(x) > 0:
flash("That username is already taken, please choose another")
return render_template('register.html', form = form)
else:
c.execute("""
INSERT INTO users (firstName, lastName, username, email, password, is_admin)
VALUES (%s, %s, %s, %s, %s, %s)
""",(firstName, lastName, username, email, password, is_admin))
conn.commit()
flash("Thanks for registering!")
c.close()
conn.close()
gc.collect()
session['logged_in'] = True
session['username'] = username
return redirect(url_for('dashboard'))
return render_template('register.html', form = form)
except Exception as e:
return(str(e))
I think your issue is the SELECT, not the INSERT. You are passing (username) as a parameter -- this is not a tuple. You need to use a trailing comma:
x = c.execute("SELECT * FROM users WHERE username = %s", (username,))

Categories

Resources