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)
Related
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)
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 )
I have a method in this I am extracting email id and mobile number from the database.
I am using POSTGRES as database and using python language.I need to pass the value to the second method for the OTP purpose but I am running into an error.
#app.route("/", methods=['GET', 'POST'])
def userlogin():
sql_mobile_query = """SELECT users.phone FROM users WHERE users.email = %s"""
cursor.execute(sql_mobile_query, record_to_search)
mobile = cursor.fetchone()
mobile_new = mobile[0]
sql_email_query = """SELECT users.email FROM users WHERE users.email = %s"""
cursor.execute(sql_email_query, record_to_search)
email = cursor.fetchone()
email_new = email[0]
connection.commit()
if(role == ('Admin',) and eotp == ('False',) and motp == ('False')):
return "No need of OTP"
else:
return redirect(url_for('otp', email=email_new , mobile=mobile_new))
connection.commit()
print("Logged in sucessfully")
I have another method I need to access the email id and mobile number in this method that is passed from the above userlogin() method
#app.route("/otp/<email>/<mobile>", methods=['GET', 'POST'])
def otp(email, mobile):
email = email
mobile = mobile
print(email, mobile)
return render_template("otp_screen.html")
Right now I am getting this error during execution
Solved. I just don't have to assign new variable in this method #app.route("/otp/<email>/<mobile>", methods=['GET', 'POST'])
I created a CRUD endpoint wit Flask but when I try to GET data, I receive a 404 error. I tried to access this endpoint with 'http://127.0.0.1:5002/albums/beck//' and 'http://127.0.0.1:5002/albums/beck' but still get a 404. Since I supplied 'beck' as the artist name I thought the get method would run fine. I think I added the resource incorrectly.
class Artistdetails(Resource):
def get(self, artist_name):
conn = db_connect.connect()
# Protect against SQL injection
restricted_char = "!=<>*0&|/\\"
for char in restricted_char:
artist_name = artist_name.replace(char, "")
query_db = conn.execute("SELECT DISTINCT album FROM album WHERE artist='{0}'".format(artist_name.title()))
result = jsonify({'artistAlbumList': [i[0] for i in query_db.cursor.fetchall()]})
return result
def put(self, artist_name, album_name, album_name_new):
conn = db_connect.connect()
# Protect against SQL injection
restricted_char = "!=<>*0&|/\\"
for char in restricted_char:
artist_name = artist_name.replace(char, "")
query_db = conn.execute("UPDATE album SET album='{0}' WHERE artist='{1}' AND"
" album='{2}'".format(artist_name.title(), album_name.title(), album_name_new.title()))
result = jsonify({'putAlbumId': [i[0] for i in query_db.cursor.fetchall()]})
return result, 201
def post(self, artist_name, album_name):
conn = db_connect.connect()
# Protect against SQL injection
restricted_char = "!=<>*0&|/\\"
for char in restricted_char:
artist_name = artist_name.replace(char, "")
query_db = conn.execute("INSERT INTO album (album, artist) VALUES"
" ({0},{1})".format(artist_name.title(), album_name.title()))
result = jsonify({'postAlbumId': [i[0] for i in query_db.cursor.fetchall()]})
return result, 201
def delete(self, artist_name, album_name):
conn = db_connect.connect()
# Protect against SQL injection
restricted_char = "!=<>*0&|/\\"
for char in restricted_char:
artist_id = artist_name.replace(char, "")
album_id = album_name.replace(char, "")
query_db = conn.execute("DELETE FROM album WHERE"
" artist_id='{0}' AND album_id='{1}'".format(artist_name, album_name)
)
result = jsonify({'deleteAlbumId': [i[0] for i in query_db.cursor.fetchall()]})
return result, 204
Create API routes
api.add_resource(Api, '/')
api.add_resource(Albums, '/albums')
api.add_resource(Artistdetails, '/albums/<string:artist_name>/<string:album_name>/<string:album_name_new>')
api.add_resource(Genreyear, '/albums/yr')
api.add_resource(Genrenum, '/albums/genre')
api.add_resource(Artists, '/artists')
This line:
api.add_resource(Artistdetails,
'/albums/<string:artist_name>/<string:album_name>/<string:album_name_new>')
It adds a path to the Flask router that makes it expect /albums/<artist_name>/<album_name>/<album_name_new>, whereas you're trying to request /albums/<artist_name>, which doesn't match anything.
A quick fix for you would be:
api.add_resource(Artistdetails, '/albums/<string:artist_name>')
However, you might instead want to support query string parameters for your search interface so that requests look more like this:
/albums?artist=<string>&album_name=<string>
To do that, the documentation for Flask-RESTful reqparse would be useful.
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