My app is/isn't writing to the DB under the right conditions so that's all working fine. It's checking one table for PSIReg number and if it exists in pharmaValidate table and if it exists, writing the record into pharmacies table.
The last little step where it renders a page in the case of the reg number being invalid is returning:
TypeError: The view function for 'PharmaReg' did not return a valid response. The function either returned None or ended without a return statement.
The desired behaviour is that it renders PharmaRegFail.html in the case of invalid PSIReg number and the record not writing to the DB (the latter part is already happening)
#app.route('/PharmaReg', methods=["POST", "GET"])
def PharmaReg():
msg = "msg"
with sqlite3.connect("mypharmaSQLite3.db") as con:
if request.method == "POST":
try:
PSIReg = request.form["PSIReg"]
PharmaName = request.form["PharmaName"]
PharmaPhone = request.form["PharmaPhone"]
PharmaAddress = request.form["PharmaAddress"]
PharmaEmail = request.form["PharmaEmail"]
realPharma = con.execute('select * from pharmaValidate where PSIReg = ?', [PSIReg])
validPharma = realPharma.fetchone()
if validPharma:
with sqlite3.connect("mypharmaSQLite3.db") as con:
cur = con.cursor()
cur.execute("INSERT into pharmacies (PSIReg, PharmaName, PharmaPhone, PharmaAddress, PharmaEmail) values (?,?,?, ?, ?)", (PSIReg, PharmaName, PharmaPhone, PharmaAddress, PharmaEmail))
con.commit()
msg = "Pharmacy successfully registered"
con.close()
return render_template("successRegPharm.html", msg=msg)
except:
return render_template("PharmaRegFail.html")
#app.route('/pharmaRegFail.html')
def pharmaRegFail():
return render_template("pharmaRegFail.html")
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 :)
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)
Im making a login system as a data base Im using SQLite.
def loginfunction(self):
user = self.emailfield.text()
password = self.passwordfield.text()
if len(user)==0 or len(password)==0:
self.error.setText("Please input all fields.")
else:
conn = sqlite3.connect("shop_data.db")
cur = conn.cursor()
query = 'SELECT password FROM login_info WHERE username =\''+user+"\'"
cur.execute(query)
result_pass = cur.fetchone()[0]
if result_pass == password:
print("Successfully logged in.")
self.error.setText("")
else:
self.error.setText("Invalid username or password")
When I run it if the password does not match with the username from the data base it works but if I type a wrong username the app closes and prints out this
main.py", line 38, in loginfunction
result_pass = cur.fetchone()[0]
TypeError: 'NoneType' object is not subscriptable
Here is what SQLite log says + what the data base looks like data base
fetchone does
Fetches the next row of a query result set, returning a single
sequence, or None when no more data is available.
For any
'SELECT password FROM login_info WHERE username =\''+user+"\'"
there is not matching row in data if user provided username not present in username column. You should do something like
query_result = cur.fetchone()
if result_pass is None:
print("Username with given name is not known")
# action to undertake in such case
result_pass = query_result[0]
then continue as earlier
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)