I am working on a flask file and I am trying to to take some of the functionality and methods and place them in a separate python file so that it is easier to work with and creates a file that is just for functionality in my flask app. I have looked up how to do but for some reason it is not working with me and I was hoping someone can help me. I have file snippets and github link below.
github: https://github.com/omar-jandali/RoadTripWebsite
original init.py file:
import modu
from flask import Flask, render_template, request, redirect, url_for, flash
from flask import escape, session
from datetime import datetime
from sqlalchemy import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Users, Groups, Records, Base
#app.route('/validate_registration', methods=['GET', 'POST'])
def Validate_Registration():
usernameMinChars = 4
usernameMaxChars = 12
passwordMinChars = 8
passwordMaxChars = 14
if request.method == 'POST':
# this is all of the fields in the form
username = request.form['username']
email = request.form['email']
password = request.form['password']
verify = request.form['verify']
check_username = db_session.query(Users).filter_by(Username = username).\
first()
check_email = db_session.query(Users).filter_by(Email = email).first()
if username != None:
if len(username) >= usernameMinChars:
if len(username) <= usernameMaxChars:
if check_username == None:
valid_username = username
else:
flash('The username ' + username + ' is already in use')
return redirect(url_for('Registration'))
else:
flash('The username is too long')
return redirect(url_for('Registration'))
else:
flash('The username is too short')
return redirect(url_for('Registration'))
else:
flash('Youh ave to enter a username to register')
return redirect(url_for('Registration'))
Changed server/init.py file (I want to chagne it so that I call a def in a different file in order to validate the username and submit the username if valid.)
Replace:
if username != None:
if len(username) >= usernameMinChars:
if len(username) <= usernameMaxChars:
if check_username == None:
valid_username = username
else:
flash('The username ' + username + ' is already in use')
return redirect(url_for('Registration'))
else:
flash('The username is too long')
return redirect(url_for('Registration'))
else:
flash('The username is too short')
return redirect(url_for('Registration'))
else:
flash('Youh ave to enter a username to register')
return redirect(url_for('Registration'))
with:
valid_username = modu.ValidateUsername(check_username)
** I have added a new file called modu in the same file directory that is imported at the top of the init.py file
Here is the modu.py file that was created to hold all of the defs in that can be called by the init.py file when needed:
from flask import Flask, render_template, request, redirect, url_for, flash
from flask import escape, session
from datetime import datetime
from sqlalchemy import *
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Users, Groups, Records, Base
def ValidateUsername(username):
if username != None:
if len(username) >= usernameMinChars:
if len(username) <= usernameMaxChars:
if check_username == None:
valid_username = username
return valid_username
else:
flash('The username ' + username + ' is already in use')
return redirect(url_for('Registration'))
else:
flash('The username is too long')
return redirect(url_for('Registration'))
else:
flash('The username is too short')
return redirect(url_for('Registration'))
else:
flash('Youh ave to enter a username to register')
return redirect(url_for('Registration'))
First, try not nesting things when you don't have to
Second, you're trying to return two different objects, so you'll need to catch that
def is_valid_user(username):
go_register = False
if not username:
flash('You have to enter a username to register')
go_register = True
if len(username) >= usernameMinChars:
flash('The username is too long')
go_register = True
if len(username) <= usernameMaxChars:
flash('The username is too short')
go_register = True
if not check_username:
flash('The username ' + username + ' is already in use')
go_register = True
# return two items, a redirect and the username
if go_register:
return redirect(url_for('Registration')), None
# If there was no error, you don't redirect
return None, username
For example,
go_register, valid_username = is_valid_user(username)
if go_register:
return go_register
else:
flash("valid " + valid_username)
Related
I have a Flask Webserver running with a site where you can create a user in my Windows Active-Directory. If I run the script as a separate file and set the variables manually it works as it should. But when I try to use input from the website in my script in my Flask program it does not work. I get the following error code: pywintypes.com_error: (-2147352567, 'Exception error occurred.', (0, None, None, 0, -2147221020), None). I am wondering that outside of the Flask script, it works. When I replace all varibles with strings it doesn't work either. So it seems to me that my function has a problem with Flask.
My Python code is the following:
from flask import Flask, redirect, url_for, render_template, request
from pyad import *
app = Flask(__name__)
def replaceUmlauts(string):
string = string.replace('ü', 'u')
string = string.replace('ö', 'o')
string = string.replace('ä', 'a')
string = string.replace('Ü', 'U')
string = string.replace('Ö', 'O')
string = string.replace('Ä', 'A')
return string
def createUser(firstname,lastname):
initials = replaceUmlauts(firstname)[0:1] + replaceUmlauts(lastname)[0:1]
loginName = replaceUmlauts(lastname)[0:4].lower() + replaceUmlauts(firstname)[0:2].lower()
email = replaceUmlauts(firstname).lower() + "." + replaceUmlauts(lastname).lower() + "#my.domain"
pyad.set_defaults(ldap_server="my.domain", username="Administrator", password="mypassword")
ou = pyad.adcontainer.ADContainer.from_dn("ou=OU1, ou=OU2, ou=OU3, dc=my, dc=domain")
new_user = pyad.aduser.ADUser.create(loginName, ou, password="Secret123", optional_attributes={
"givenName": firstname,
"sn": lastname,
"displayName": firstname + " " + lastname,
"mail": email,
"initials": initials
})
return True
#app.route("/")
def home():
return render_template("index.html")
#app.route("/addUser", methods=["POST", "GET"])
def addUser():
if request.method == "POST":
firstname = request.form["firstname"]
lastname = request.form["lastname"]
department = request.form["category"]
passwort = request.form["password"]
if len(firstname) == 0:
return redirect(url_for("addUser", error="The first name must not be empty!"))
exit(1)
elif any(chr.isdigit() for chr in firstname):
return redirect(url_for("addUser", error="The first name must not contain numbers!"))
exit(1)
elif len(lastname) == 0:
return redirect(url_for("addUser", error="The last name must not be empty!"))
exit(1)
elif any(chr.isdigit() for chr in lastname):
return redirect(url_for("addUser", error="The last name must not contain numbers!"))
exit(1)
elif len(passwort) < 6:
return redirect(url_for("addUser", error="The password must not have less than 6 characters!"))
exit(1)
createUser(firstname,lastname)
else:
return render_template("addUser.html")
if __name__ == "__main__":
app.run(debug=True)
I fixed the error by importing the libary called pythoncom and add the initialize command in my function, like this:
import pythoncom
def createUser(firstname, lastname):
pythoncom.CoInitialize()
And yes, it is a problem between pyad and Flask
I'm trying to complete this program I need to be able to update a password saved in txt file for a user already saved in the text file and I can't figure out how to do so.
Looking for help on tasks A-C
a. Password update Form – This Python form allows a previously registered user to reset their password after they have successfully logged in.
b. Authentication functions – These Python functions will check the following NIST SP 800-63B criteria are met upon password update:
Use the previous criteria for password length and complexity. (This work should already be
done.)
Compare the prospective secrets against a list that contains values known to be commonly-
used, expected, or compromised (Provided as CommonPasswords.txt).
If the chosen secret is found in the list, the application SHALL advise the subscriber that they
need to select a different secret.
c. Logger – Create a log to log all failed login attempts. The Log should include date, time and IP
address.
from datetime import datetime
from flask import Flask, flash, redirect, render_template, request, session, url_for
import re
from wtforms import Form, PasswordField
from wtforms.validators import DataRequired
app = Flask(__name__)
def validate_password(password):
SpecialSym = ['$', '#', '#', '%', '!', '&', '*']
val = True
if len(password) < 6:
print('length should be at least 6')
val = False
if len(password) > 20:
print('length should be not be greater than 8')
val = False
if not any(char.isdigit() for char in password):
print('Password should have at least one numeral')
val = False
if not any(char.isupper() for char in password):
print('Password should have at least one uppercase letter')
val = False
if not any(char.islower() for char in password):
print('Password should have at least one lowercase letter')
val = False
if not any(char in SpecialSym for char in password):
print('Password should have at least one of the symbols $##')
val = False
if val:
return val
else:
return False
now = datetime.now() # current date and time
date_time = now.strftime("%d/%m/%Y, %H:%M:%S")
# each route for the pages
#app.route("/")
def welcome():
"""the welcome page"""
return render_template("welcome.html")
#app.route("/home")
def home():
"""the home page"""
if not session.get('logged_in'):
return render_template('login.html')
else:
return redirect('home')
#app.route("/register", methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "a")
if not validate_password(password):
message = "Invalid Credentials"
return render_template("register.html", error=message)
else:
f.write("%s %s\n" % (email, password))
f.close()
flash("SUCCESSFUL REGISTERED *")
return render_template("homepage.html", error="SUCCESSFUL REGISTERED *")
else:
return render_template("register.html")
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "r")
data = f.readlines()
f.close()
data = [x.split() for x in data]
for item in data:
if request.form['email'] == item[0].strip() and request.form['password'] == item[1].strip():
session['logged_in'] = True
return render_template('homepage.html')
else:
error = "Wrong Credentials"
return render_template("login.html", error=error)
else:
return render_template("login.html")
#app.route("/reset", methods=['GET', 'POST'])
def reset():
"""reset page"""
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
f = open("/Users/Brian/PycharmProjects/StateList/Flask_Blog/static/database.txt", "a")
if not validate_password(password):
message = "Invalid Credentials"
return render_template("reset.html", error=message)
else:
f.write("%s %s\n" % (email, password))
f.close()
flash("Password Reset *")
return render_template("reset.html", error="Password Reset *")
My code is quite simple, and so the question, this is my code
import pandas as pd
import numpy as np
from io import StringIO
def main():
#usernames and passwords
users = "usernames,passwords\nSimone,123456"
#login
def login_system():
login = input("Login or SignUP: ")
if login == "Login" or login == "login":
#data reading
df = pd.read_csv(StringIO(users), usecols=["usernames", "passwords"])
username = input()
password = input()
#login if statement
if username == df["usernames"][0] and password == df["passwords"][0]:
print("Login Succeeded")
else:
print("Login Failed")
return
login_system()
return
main()
it compiles and everything the problem is that it doesn't do what it is supposed to, here is the answer that the compiler gives
Login or SignUP: Login
Simone
123456
Login Failed
Could someone explain to me why the if statement doesn't work
It looks like you want to look up whether the username and password matches the entry in the csv file that you read into the df. You can filter the df to check if any row matches both username and password. If there is any such row, you have a match. See this toy example:
row1list = ['Simone', 'password1']
row2list = ['YEETter', 'password2']
df = pd.DataFrame([row1list, row2list], columns=['usernames', 'passwords'])
username = 'Simone'
password = 'password1'
dfu = df[(df['usernames'] == username) & (df['passwords'] == password)]
print(dfu)
# usernames passwords
# 0 Simone password1
if len(dfu) > 0:
print("Login Succeeded")
else:
print("Login Failed")
This is the part where the user logs in into the game. The database is hosted on mlab, there is a collection of documents named loginInfo defined as mycol.
The problem that I am facing is that when it returns the id, I have no way of checking if it is a valid one since I would not be able to check with any sort of local list in Python. How do I fix it?
import pymongo
def login():
print('Login\nRegister\nPlay as Guest')
login_input = input('What would you like to do?')
if login_input == 'Login':
username = input('Username:')
username_fromDB = mycol.find({"username": username})
if username_fromDB == username:
password = input('Password:')
password_fromDB = mycol.find({"password": password})
if password == password_fromDB:
print('Login success!\n')
mainMenu()
elif login_input == 'Register':
new_username = input('Username:')
new_password = input('Password:')
tobeaddedtodb = {"username": new_username, "password": new_password}
adding = mycol.insert_one(tobeaddedtodb)
print("Registered!\n")
elif login_input == 'Play as Guest':
mainMenu()
username_fromDB = mycol.find({"username": username})
This is wrong because find() returns a cursor object, not the username as you expect.
Assuming that loginInfo collection contains unique usernames and respective passwords, there's no need to make 2 find() queries to database. You can just retrieve a user entity and check if input-provided password matches the one stored in database.
And since usernames are unique, you should use find_one() instead of find(). If user was successfully found it returns dict, otherwise you get None.
Try something like this:
import pymongo
def login():
print('Login\nRegister\nPlay as Guest')
login_input = input('What would you like to do?')
if login_input == 'Login':
username_inp = input('Username:')
pwd_inp = input('Password:')
user_found = mycol.find_one({"username": username_inp}) # query by specified username
if user_found: # user exists
if pwd_inp == user_found['password']:
print('Login success!\n')
mainMenu()
else:
print('Wrong password')
else:
print('User not found')
elif login_input == 'Register':
new_username = input('Username:')
new_password = input('Password:')
tobeaddedtodb = {"username": new_username, "password": new_password}
adding = mycol.insert_one(tobeaddedtodb)
print("Registered!\n")
elif login_input == 'Play as Guest':
mainMenu()
This question already has answers here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Flask view return error "View function did not return a response"
(3 answers)
ValueError: View function did not return a response in flask [duplicate]
(2 answers)
Closed 5 years ago.
This is my code:
#app.route('/registercheck', methods=['GET', 'POST'])
def registercheck():
checkusername = g.db.execute('select uname from users where uname = ?', (request.form['usernameR'], ))
checkpassword = g.db.execute('select pword from users where uname = ?', (request.form['usernameR'], ))
arraycheckr = checkpassword.fetchall()
if request.method == 'POST':
encryptpword = hashlib.md5()
encryptpword.update(request.form['passwordR'])
encryptpword.digest()
if len(arraycheckr) == 0 and checkpassword == encryptpword:
if len(request.form['usernameR']) < 6:
flash('Username must be at least 6 characters')
return redirect(url_for('register'))
if len(request.form['passwordR']) < 4:
flash('Password must be at least 4 characters')
return redirect(url_for(register))
if checkusername == request.form['usernameR']:
flash('Username is already taken')
return redirect(url_for(register))
else:
g.db.execute('insert into users (uname, pword) values (?, ?);', (request.form['usernameR'], encryptpword))
g.db.commit()
os.mkdir(os.path.join(app.config['UPLOAD_FOLDER'], request.form['usernameR']))
return redirect(url_for('upload'))
I looked at other posts similar to this but I still don't understand why it throws this problem. The redirections look fine (in the html aswell).
You accept a GET request witch you never check, at the end you should render a template.
#app.route('/registercheck', methods=['GET', 'POST'])
def registercheck():
checkusername = g.db.execute('select uname from users where uname = ?', (request.form['usernameR'], ))
checkpassword = g.db.execute('select pword from users where uname = ?', (request.form['usernameR'], ))
arraycheckr = checkpassword.fetchall()
if request.method == 'POST':
encryptpword = hashlib.md5()
encryptpword.update(request.form['passwordR'])
encryptpword.digest()
if len(arraycheckr) == 0 and checkpassword == encryptpword:
if len(request.form['usernameR']) < 6:
flash('Username must be at least 6 characters')
return redirect(url_for('register'))
if len(request.form['passwordR']) < 4:
flash('Password must be at least 4 characters')
return redirect(url_for(register))
if checkusername == request.form['usernameR']:
flash('Username is already taken')
return redirect(url_for(register))
else:
g.db.execute('insert into users (uname, pword) values (?, ?);', (request.form['usernameR'], encryptpword))
g.db.commit()
os.mkdir(os.path.join(app.config['UPLOAD_FOLDER'], request.form['usernameR']))
return redirect(url_for('upload'))
return render_template('some_file.html')