In: Computer Science
Could you modify my code so it meets the following requirement? (Python Flask)
I want the user to register for account using email and password, then store that data into a text file. Then I want the data to be read when logging in allowing the user to go to home page.
-------------Code--------------------
routes.py
from flask import Flask, render_template, redirect, url_for, request, session import json, re app = Flask(__name__) '''@app.before_request def before_request(): if 'visited' not in session: return render_template("login.html") else: pass''' def validate_password(password): reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{12,25}$" pattern = re.compile(reg) match = re.search(pattern, password) # validating conditions if match: return True else: return False # pages @app.route('/') @app.route('/index.html') def index(): if 'visited' not in session: return redirect(url_for('login')) return render_template('index.html', the_title='Console Wars: Xbox vs Playstation') @app.route('/xbox.html') def xbox(): if 'visited' not in session: return redirect(url_for('login')) return render_template('xbox.html', the_title='Console Wars: Xbox Specs') @app.route('/playstation.html') def playstation(): if 'visited' not in session: return redirect(url_for('login')) return render_template('playstation.html', the_title='Console Wars: Playstation Specs') @app.route('/login', methods=['GET', 'POST']) def login(): try: if request.method == 'POST': if request.form['email'] == 'admin' and request.form['password'] == 'password': session['visited'] = True return redirect(url_for('index')) else: error = "wrong credentials" return render_template("login.html", error=error) else: return render_template("login.html") except Exception as e: output = json.dumps({'Error': 'Internal Error'}) return output @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] if not validate_password(password): message = "Password does not met requirements" return render_template("register.html", error=message) return render_template("register.html", error="successfully registered") else: return render_template("register.html") @app.route('/logout', methods=['GET', 'POST']) def logout(): if 'visited' in session: session.pop('visited') message = "Logged out succesfully" return render_template("login.html", error=message) if __name__ == '__main__': app.run(debug=True)
register.html
{% extends 'base.html' %} {% block body %}
Register
{% if error %}
* {{ error }} {% endif %}
Have an Account?Login!
{% endblock %}
login.html
{% extends 'base.html' %} {% block body %}
Login
{% if error %}
* {{ error }} {% endif %}
Don't Have an Account?Register!
{% endblock %}
I am attaching the codes for /login and /register only where you want to store and retrieve data from .txt file. There are no changes to the remaining code.
@app.route('/login',methods=['GET','POST'])
def login():
try:
if request.method == 'POST':
f=open("database.txt","r") #open the file in read mode
data=f.readlines() #readlines() will give us all the lines, line by line in list format
f.close() #close the file
data=[x.split() for x in data] #We get the data in the format of strings. So each line should be splitted using space " " as delimiter
for item in data:
if request.form['username']== item[1].strip() and request.form['password'] == item[2].strip(): #Here strip() is used to overcome the space issues, if any. The spaces will be trimmed
session['visited']=True
return redirect(url_for('index'))
else:
error="wrong credentials"
return render_template("login.html",error=error)
else:
return render_template("login.html")
except Exception as e :
output=json.dumps({'Error':'Internal Error'})
return output
@app.route('/register',methods=['GET','POST'])
def register():
if request.method == 'POST':
name=request.form['name']
email=request.form['email']
password=request.form['password']
f=open("database.txt","a") #we open the file named database.txt in append mode.(Note: Please create an empty database.txt file because it is in append mode).
tname="" #Here i created a string tname representing total name, because when the user enters name as,say Mohak Raj; the name will be appended as two words seperated by spaces. This will be difficult while reading the data.
for sub in name.split(" "):
tname=tname+"_"+sub #append the seperator _ to the name which will become easy while reading the data fron the .txt file
if not validate_password(password):
message="Password does not match requirements"
return render_template("register.html",error=message)
else:
f.write("%s %s %s\n"%(tname,email,password)) #write the data into the database.txt file
f.close() #close the file
return render_template("register.html",error="successfully registered")
else:
return render_template("register.html")
I am glad to answer the question again for you. Please feel free to ask doubts if any, in the comments section.
Output Screenshots:
(Note: Please take care of CSS, the background color is black and the text is also black. I havent made any changes to CSS.)
This above page(index.html) will be displayed when the entered credentials are correct.
Please dont forget to upvote if you like my work. This will help me to provide better solutions with great effort. Thank you.