Python, Flask, MySQL - Check if email exists in database - python

I'm pretty new to SQL but I need it for a school project. I'm trying to make a (python) web-app which requires accounts. I'm able to put data into my SQL database but now I need some way to verify if an e-mail (inputted via html form) already exists inside the database. Probably the easiest query ever but I haven't got a single clue on how to get started. :(
I'm sorry if this is a duplicate question but I can't find anything out there that does what I need.

if you are using SQLAlchemy in your project:
#app.route("/check_email")
def check_email():
# get email from you form data
email = request.form.get("email")
# check if someone already register with the email
user = Users.query.filter_by(email=email).first()
if not user:
# the email doesnt exist
pass
else:
# the email exists
pass
Users.query.filter_by(email=email).first() equal to SQL:
SELECT * from users where email="EMAIL_FROM_FORM_DATA"
if you are using pymsql(or something like that):
import pymsql
#app.route("/check_email")
def check_email():
# get email from you form data
email = request.form.get("email")
conn = connect(host='localhost',port=3306,user='',password='',database='essentials')
cs1 = conn.cursor()
params = [email]
# cursor return affected rows
count = cs1.execute('select * from users where email=%s', params) # prevent SqlInject
if count == 0:
# count 0 email
else:
# the email exists
# and if you want to fetch the user's info
user_info = cs1.fetchall() # the user_info should be a tuple
# close the connection
cs1.close()
conn.close()

I was able to solve my issue by simply using
INSERT IGNORE and after that checking if it was ignored with the primary key.
Thank you for everyone that helped out though!

Related

Python Dash - Basic Authentication with multiple usernames filtering database based on user input in username

I have an SQL database that stores all my data. I have a column there called “client_name” where I have client1, client2, etc.
I have created a basic dash authentication where as soon as my dash application loads, it asks the user for a username and password.
How can I make it work that if the user inputs “client1” as username, the app will automatically filter my SQL database to only read rows that belong to client1 and thus all visuals will display client1’s data?
Sample code
# User dictionary
USERNAME_PASSWORD_PAIRS = {
'client1': 'client1'
, 'client2': 'client2'
}
# Basic authentication
auth = dash_auth.BasicAuth(
app,
USERNAME_PASSWORD_PAIRS
)
# Connect and read data from SQL server
odbc_params = f'DRIVER={driver};SERVER=tcp:{server};PORT=1433;DATABASE={database};UID={username};PWD={password}'
connection_string = f'mssql+pyodbc:///?odbc_connect={odbc_params}'
engine = create_engine(connection_string)
query = "SELECT * FROM [dbo].[test]" # database with all client data
df = pd.read_sql(query, engine)
engine.dispose()
So I want the “df” to read the filtered dataframe based on wether “client1” or “client2” was used to log in.
Thanks for the help
You have a column in df which is named "client" or something alike. You need to get the name of the logged in user, and then filter the df for it:
username = auth.get_username()
df_filtered_for_client = df[df["client"].isin([username])

SQLITE3 query in Python using current_user.email

I need to fetch rows of a table called records in SQLite based on a conditional query that selects only records that match value of email column = current_user.email. Current_user is the proxy for current logged in user, so I want this table to filter records only showing the records applicable to this user.
rows = c.execute("select * from records where email = current_user.email").fetchall()
There is no problem is resolving value of current_user.email. I can print it and it shows me the email. The problem is in the query the way and the way I am implementing it, does not filter the records. However when I replace current_user.email with the actual email id in quotes, for example "xyz#xyz.com", it filters perfectly.
So my question is how can I filter Sqlite column based on a value that is another variable (here: email = current_user.email), and not email = "xyz#xyz.com?
Use a ? placeholder in the sql statement, then pass the specific value you're looking for as an extra argument.
rows = c.execute("select * from records where email = ?", [current_user.email]).fetchall()
You need to add the content of the variable to your string. Right now, your SQL driver just sees "select * from records where email = user.email"
The code below should help.
rows = c.execute("select * from records where email = %(username)", {"username": current_user.email}).fetchall()
Bad Code that is vulnerable to SQL injection.
rows = c.execute("select * from records where email = {}".format(current_user.email)).fetchall()
Thanks to John Gordon for pointing it out.

Type check validation in Python - stuck in a loop

I am currently working on a database application using Python and SQLite3, alongside Tkinter to create the user interface. The application has a login function, where the user inputs their StaffID and password, and the program authenticates the user by searching a login table for the data input. I am trying to add a type check validation to the StaffID, where it can only be an integer, however, upon running the program, it seems to get stuck in a loop displaying the following output:
I have attached a snippet of the code below:
def UserLogin(self): #Login function for staff members
while True:
try:
staffid = int(self.Entry1.get())
password = self.Entry2.get()
with sqlite3.connect("LeeOpt.db") as db: #Connects to the database file
cursor = db.cursor()
find_user = ('SELECT * FROM Login WHERE StaffID = ? AND Password = ?')
cursor.execute(find_user, [(staffid),(password)])
results = cursor.fetchall()
if results:
for i in results:
self.Access()
MainMenu.create_Toplevel1(root)
self.quit()
else:
tkinter.messagebox.showerror("Error", "The staffID or password is incorrect, please try again.")
time.sleep(1)
return("exit")
break
except:
tkinter.messagebox.showerror("Validation Error","Please enter the correct data type for StaffID")
self.ClearEntries()
I am relatively new to Python, so any help is really appreciated, even if it is just to improve my code in general. Thanks in advance :)

MySQL python connector: "not all arguments converted during bytes formatting"

I have a mysql database in which 'user' table having f_name,l_name,password email(pk) by which session is created and table 'friendgroup' having fg_name(pk), email((pk),users.email(FK)) and table 'member' having email(pk,user.email(fk)), owner_email(pk,friendgroup.email(fk)), fg_name(pk,friendgroup.fg_name(fk)), and a python flask file below.
After login account, I wish to add a friend in chat. I tried to fix it from session['email']
def add_friend():
user = session['email']
friendgroups = _get_own_friendgroups(user) return
render_template('addFriend.html', friendgroups=friendgroups)
def _get_own_friendgroups(user):
cursor = mysql.connection.cursor()
#find all friendgroups that the user owns
find_owned_friendgroups = 'SELECT fg_name, description FROM friendgroup WHERE owner_email = %s ORDER BY fg_name ASC'
cursor.execute(find_owned_friendgroups, (user))
owned_friendgroups = cursor.fetchall()
cursor.close()
return owned_friendgroups
I expect output will be an open window and actively use of add friend when needed but showing error:
MySQLdb._exceptions.ProgrammingError: not all arguments converted during bytes formatting
A common error in python is to use (bar) instead of (bar,) the former not being a tuple.
Try with:
cursor.execute(find_owned_friendgroups, (user,))

How to query a MySQL database via python using peewee/mysqldb?

I'm creating an iOS client for App.net and I'm attempting to setup a push notification server. Currently my app can add a user's App.net account id (a string of numbers) and a APNS device token to a MySQL database on my server. It can also remove this data. I've adapted code from these two tutorials:
How To Write A Simple PHP/MySQL Web Service for an iOS App - raywenderlich.com
Apple Push Notification Services in iOS 6 Tutorial: Part 1/2 - raywenderlich.com
In addition, I've adapted this awesome python script to listen in to App.net's App Stream API.
My python is horrendous, as is my MySQL knowledge. What I'm trying to do is access the APNS device token for the accounts I need to notify. My database table has two fields/columns for each entry, one for user_id and a one for device_token. I'm not sure of the terminology, please let me know if I can clarify this.
I've been trying to use peewee to read from the database but I'm in way over my head. This is a test script with placeholder user_id:
import logging
from pprint import pprint
import peewee
from peewee import *
db = peewee.MySQLDatabase("...", host="localhost", user="...", passwd="...")
class MySQLModel(peewee.Model):
class Meta:
database = db
class Active_Users(MySQLModel):
user_id = peewee.CharField(primary_key=True)
device_token = peewee.CharField()
db.connect()
# This is the placeholder user_id
userID = '1234'
token = Active_Users.select().where(Active_Users.user_id == userID)
pprint(token)
This then prints out:
<class '__main__.User'> SELECT t1.`id`, t1.`user_id`, t1.`device_token` FROM `user` AS t1 WHERE (t1.`user_id` = %s) [u'1234']
If the code didn't make it clear, I'm trying to query the database for the row with the user_id of '1234' and I want to store the device_token of the same row (again, probably the wrong terminology) into a variable that I can use when I send the push notification later on in the script.
How do I correctly return the device_token? Also, would it be easier to forgo peewee and simply query the database using python-mysqldb? If that is the case, how would I go about doing that?
The call User.select().where(User.user_id == userID) returns a User object but you are assigning it to a variable called token as you're expecting just the device_token.
Your assignment should be this:
matching_users = Active_Users.select().where(Active_Users.user_id == userID) # returns an array of matching users even if there's just one
if matching_users is not None:
token = matching_users[0].device_token

Categories