PostgreSQL + Python: Check if record exist using variables - python

referring to this documentation
Iam trying to compare JSON data
jsonResponse = json.loads(dataString) { 'login' : 'login' }
username_input = jsonResponse["login"] login
to database record using this call:
cur.execute("SELECT * FROM users WHERE username = '?'" % username_input)
than iam calling for specific one catched and use another variable
username_database = cur.fetchone()
to compare for executing loop
if username_input == username_database:
username_password = jsonResponse["password"]
cherrypy.log(str(username_password))
conn.commit()
But I am receiving None value from database username_database = None

Related

how do you auto generate a random ID for an SQLite database table

Im in the process of creating a website with python flask and html. I want it to have a register, login, edit, delete, and home page. I want to store the users login data in an sqlite database that can then be called to veify the login of the user. in order to have different users have the same username and/or password, I need to give each user a unique ID. I use this ID in the url, and I want the user to be able to use this ID for other things in the website. because of this, when a new user is added I need to give them a random (unique) ID (probably 8 digits). I saw a bunch of stuff about AUTO INCRAMENT being random, but I didnt understand it very much, and I tried it, and it gave me consecutive numbers (which is not what I want) I also tried RANDOM() and RAND() but they both threw syntax errors. can anyone tell me how to generate an sqlite column for an random unique 8 digit ID?
here's what I have:
schema.sql
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id INTEGER PRIMARY KEY --insert random generator here,
username TEXT NOT NULL,
password1 TEXT NOT NULL,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
heres the python that runs the schema:
init_db.py
import sqlite3
connection = sqlite3.connect('database.db')
with open('schema.sql') as f:
connection.executescript(f.read())
cur = connection.cursor()
cur.execute("INSERT INTO users (username, password1) VALUES (?, ?)",
('user1', 'pass1')
)
cur.execute("INSERT INTO users (username, password1) VALUES (?, ?)",
('user2', 'pass2')
)
connection.commit()
connection.close()
thanks in advance for any help
okay.
Ive fixed this by generating a random number in the python code. when a user registers, I take their username and password, then generate a random number between 10000000 and 99999999. then I check if its in the database already, and if so, generate another one, until I generate a unique number. then I add username, password and ID to the database at the same time.
heres what I have now
(disclaimer: i am only showing the relevant code, so some of it might not make sense)
CREATE TABLE users (
id INTEGER,
username TEXT NOT NULL,
password1 TEXT NOT NULL,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
the init_db.py is the same,
heres the python:
from flask import Flask, render_template, url_for, request, flash, redirect, abort#imports
import sqlite3
import random
app = Flask(__name__)
def get_db_connection():
conn = sqlite3.connect('database.db')
conn.row_factory = sqlite3.Row
return conn
def get_username(usernamex):#def and pass usernamex
validated_uname = False#reset progress variable
conn = get_db_connection()#connect to database
cur = conn.cursor()#create a cursor
try:
cur.execute('SELECT * FROM users WHERE username = ?',(usernamex,))#select the row in the users table where username == the usernamex variable
uname = cur.fetchone()[1]#uname = the second column of that row
validated_uname = True#update progress variable
except:#if the above failed: (most likely because usernamex was not in the database):
validated_uname = False#reset progress variable
if validated_uname == True:#if the try function passed:
return(uname)#update uname and send it back
conn.commit()#commit and close database
conn.close()
def get_password1(password1x):#def and pass password1x
validated_upass = False#reset progress variable
conn = get_db_connection()#connect to database
cur = conn.cursor()#create a cursor
try:
cur.execute('SELECT * FROM users WHERE password1 = ?',(password1x,))#select the row in the users table where password1 == the password1x variable
upass = cur.fetchone()[2]#upass = the third column of that row
validated_upass = True#update progress variable
except:
validated_upass = False#reset progress variable
if validated_upass == True:#if the try function passed:
return(upass)#update upass and send it back
conn.commit()#commit and close database
conn.close()
app.config['SECRET_KEY'] = '013ecbdd4aae3899c7feed1bf36dee4e'#secret key
#app.route("/register", methods=('GET', 'POST'))#url, and pass the get and post vaiables to make forms
def register():
if request.method == 'POST':#when request method is post in the html page: #(after they press submit)
usernamex = request.form['username']#take the username entered from html
password1x = request.form['password1']#same for pass1 and pass2
password2x = request.form['password2']
if not usernamex:#if nothing was entered for username:
flash('Username is required!')#error message
elif not password1x:#if nothing was entered for pass1:
flash('Password is required!')#error message
elif not password2x:#if nothing was entered for pass2:
flash('Valdiated password is required!')#error message
elif password1x != password2x:# if pass1 and pass2 dont match:
flash('Passwords do not match!')#error message
else:#otherwise
conn = get_db_connection()#connect to database
cur = conn.cursor()#create cursor
loop = True
while loop == True:
rand_id = random.randint(10000000, 99999999)#generate random number (8 digits)
try:
cur.execute('SELECT * FROM users where id = ?',(rand_id,))#select the row in the users table where id == the rand_id variable
r_id = cur.fetchone()[0]#r_id = the first column from that row ## this is just here to throw the error
except:
cur.execute('INSERT INTO users (id, username, password1) VALUES (?, ?, ?)',(rand_id, usernamex, password1x))#make a new row, and put in ID, username and password1 in their respective places
loop = False#break the loop
conn.commit()#commit and close database
conn.close()
id = rand_id#for the home url
#id = home_id(usernamex, password1x)#id = [call the home_id function {pass usernamex and password1x}]
return redirect(url_for('home', id=id))#go to the home page and pass id for the url
return render_template('register.html', title = 'Register')#render the template from register.html
thanks for everyones help :)

Key error when clicking on /viewcart in python flask

I am working with sessions. When the user clicks on /viewtask I want it to validate if there is an email in session. If there isnt my program should redirect the user to the login page.
If there is then I want the user to view the cart. When I test this I get a 'Key error : Email'
I think its ignoring the if statement.
I have no issue assigning a session something but I keep getting errors when checking the session.
App.py
#app.route("/viewcart")
def viewcart():
if session.get("Email") == None:
return redirect(url_for(loginform))
else:
conn = sqlite3.connect("data.db")
c = conn.cursor()
c.execute("SELECT ID FROM Users WHERE Email = '" + session['Email'] + "'")
UserID = c.fetchone()[0]
c.execute("SELECT Products.Name , Products.Price , Products.Image , Cart.Size FROM Products,Cart WHERE Products.ID == Cart.ProductID AND Cart.UserID == ?",(str(UserID)))
products = c.fetchall()
return render_template("cart.html",products = products)

How to use flask variable in calling SELECT query in MariaDB

What is the correct syntax for calling a SELECT query in MariaDB from a Registration Form.
Specifically, in the WHERE clause. I've been looking all over the net to debug this and it does not seem to work (semantically).
Here is the code in my python flask.
#app.route('/check_email', methods = ['POST', 'GET'])
def chck_Email():
if request.method == 'POST':
visEmail = request.form['email']
conn = mariadb.connect(**config)
print(f"WE ARE CONNECTED ORAYT")
# create a connection cursor
cur = conn.cursor()
# execute an SQL statement
try:
print(visEmail)
#sql = " INSERT INTO visitor (Visitor_ID, Visitor_Name) VALUES( NULL, '{}')".format(Visitor_ID, Visitor_Name)
current_Email= cur.execute("SELECT user_Email FROM user_account WHERE user_Email = ?",(visEmail,))
print(current_Email)
if current_Email != None:
print('Email Invalid: Email already exists!')
form = Registration_Form()
exists = {
"email_exists": True
}
return render_template(exists,'register.html', form = form )
""The visEmail is the variable that is supposed to be holding the email address given by the user upon clicking submit, the program then checks in the database if the given email address already exists in the DB.
I printed the data in the visEmail variable to see the string(Which is fine), but the execution in the database returns me with "None" (It should not be returning a None since I already have the given email address on the DB). It is supposed to return the error "Email Already exists"
THank you very much
You're not fetching the row of results. cur.execute() doesn't return anything, you have to call cur.fetchone() to get the results, and assign that to current_Email.
try:
print(visEmail)
#sql = " INSERT INTO visitor (Visitor_ID, Visitor_Name) VALUES( NULL, '{}')".format(Visitor_ID, Visitor_Name)
cur.execute("SELECT user_Email FROM user_account WHERE user_Email = ?",(visEmail,))
current_Email = cur.fetchone()
print(current_Email)
if current_Email != None:
print('Email Invalid: Email already exists!')
form = Registration_Form()
exists = {
"email_exists": True
}
return render_template(exists,'register.html', form = form )

How to query an NDB database by string value

I'm trying to create a user login system with flask-login, however i am having difficulties with querying email addresses using Google's query functions.
I can grab the ID, but since a user wont know their ID when logging in, this isn't very useful.
An overview of what the code excerpt is trying to do (I've hardcoded values for the purpose of getting a proof-of-concept working):
username = 'abc#gmail.com'
check database for username
Return true if match is found
In this guide, at 9'48", the user writes (what I assume is) a sqlAlchemy query. What would be the equivalent of this query using Googles NDB query functions?
class User(ndb.Model):
name = ndb.StringProperty()
email = ndb.StringProperty()
password = ndb.StringProperty()
#login_manager.user_loader
def load_user(user_id):
return User.get_by_id(int(user_id))
#app.route('/', methods=['GET', 'POST'])
def testlogin():
#user = User.query(getattr(User, 'email') == 'abc#gmail.com')
#login_user(user)
check = 'abc#gmail.com'
query = User.query(User.email == check)
#print query
#query = User.query()
#queryuser = User.query().filter(User.email == 'abc#gmail.com')
#login_user(queryuser)
checkTable = User.get()
#checkTable.email = check
checkTable_key = checkTable
#query = checkTable_key.get()
print str(checkTable_key)
results = User.query().fetch() #this returns a list / array
#print(results)
#print "query all" + str(queryall)
#for result in results:
#print "query all" + str(result.email)
return "logged in "
check = 'abc#gmail.com'
query = User.query(User.email == check).get() # this returns the User object, or None if not found
if query:
return True
else:
return False
# or try
return (query != None)
# or, just return the User object?
# if you just want to see if the user exists, you should do a keys_only query, which is free:
query = User.query(User.email == check).fetch(1, keys_only=True)

Django write in database when form is submit

i want to use html form to be able to send back information to my view.py, the goal is to get the data, use it as arguments in a call to a stored procedure.
def mouvementCreation(request):
idMI = 0
especes = TbEspece.objects.order_by('id')
#Get Mouvement informations
#Connection to 'erp-site' DB
cursor = connections['erp-site'].cursor()
try:
#Get Produits list from Espece
query = "{CALL SP_webGET_PRODUIT_FROM_ESPECE(%s,%s,%s,%s,%s)}"
arguments = (2016, 'C', 0, 10, 'A',)
cursor.execute(query, arguments)
produits = dictfetchall(cursor)
#Get Transporters list
cursor.execute("{CALL SP_webGET_TRANSPORT}")
transporters = dictfetchall(cursor)
#Get Livreur list
cursor.execute("{CALL SP_webGET_LIVREUR}")
livreurs = dictfetchall(cursor)
finally:
cursor.close()
cursor = connections['site'].cursor()
try:
#Get Circuit list
cursor.execute("{CALL SP_webGET_CIRCUIT_FOR_MVT}")
circuits = dictfetchall(cursor)
#Get Source list
cursor.execute("{CALL SP_webGET_SOURCE_FOR_MVT}")
mvtsources = dictfetchall(cursor)
#Get Dest list
cursor.execute("{CALL SP_webGET_DEST_FOR_MVT}")
destinations = dictfetchall(cursor)
#Get PontBascule list
cursor.execute("{CALL SP_webGET_PBASCULE}")
pontBascules = dictfetchall(cursor)
finally:
cursor.close()
reg_normes = TbRegauxnormes.objects.all()
ordreexecs = TbOrdreexecution.objects.all()
form = mouvementForm(request.POST or None)
if form.is_valid():
pont = form.cleaned_data['pont']
dateheure = form.cleaned_data['dateheure']
poid = form.cleaned_data['poid']
dsd = form.cleaned_data['dsd']
typepesee = form.cleaned_data['typepesee']
#Connection to 'erp-site' DB
cursor = connections['pontbascule'].cursor()
try:
#Get Produits list from Espece
query = "{CALL SP_ADD_MANUAL_PESEE(%s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s,%s,%s,%s, %s,%s)}"
arguments = (pont, '11', dateheure, poid, dsd,typepesee, '','','','','','','','','','','','','','','','')
cursor.execute(query, arguments)
finally:
cursor.close()
return render(request, 'mouvementCreation.html', {'form': form, 'especes' : especes, 'produits' : produits, 'transporters' : transporters, 'livreurs' : livreurs, 'circuits' : circuits, 'mvtsources' : mvtsources, 'destinations' : destinations, 'pontBascules' : pontBascules} )
The stored procedure is supposed to create a new entry.
What i want to do, but i'm not sure if possible would be :
Fill form => retrieve data in view => call stored procedure with the retrieved data => get the ID of the new entry so the user can be redirected to a another view that take the id in url parameters.
Would this be possible to do ?
Edit : I managed to get the post request working aswell as my stored procedure, my problem is now for the last part, redirecting the user on the right page after submiting the form.
the current page is /gestion_mouvement/mouvementCreation and i want the user to be redirected on /gestion_mouvement/mouvementDetails/{{ID}}
Problem is it seem that the query is too slow, because by the time i submit the form the user gets redirected to /gestion_mouvement/mouvementDetails/
and not recieving the ID.
What about creating a new cursor to fetch your last id created?
cursor.execute("SELECT max(id) from MANUAL_PESEE")
return {rec[0] for rec in cursor}
I've had the same issue recenly. Here is what I did.
Query concerned object model just after insert (after form.save()) and get the max(id) generated
form.save()
#mynewid = Msg.objects.all().order_by("-id")[0].id
mynewid = Msg.objects.latest('id').id
return redirect('/msg/{0}/edit/'.format(mynewid))

Categories