Question

In: Computer Science

Could you modify my code so it meets the following requirement? (Python Flask) I want the...

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 %}

Solutions

Expert Solution

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.


Related Solutions

Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
Python: I want to make the following code to prompt the user if want to run...
Python: I want to make the following code to prompt the user if want to run the software again. I am new to python, so i do not know if it works like c++. If can explain that would be much appreciated base = float(input("Enter base of the triagle: ")) Triangle_Right = float(input("Enter right side of the triagle: ")) Triangle_Left = float(input("Enter left side of the triagle: ")) height = float(input("Enter the height of the triangle: ")) perimiter = base...
In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
look this code is a correct but i want modify it to allow the client to...
look this code is a correct but i want modify it to allow the client to have three attempts to login to the server package hw2; import java.net.*; import java.util.Formatter; import java.util.Random; import java.util.Scanner; import java.io.*; public class Client {    Socket server;    int port;    Formatter toNet = null;    Scanner fromNet = null;    Scanner fromUser = new Scanner(System.in);    public Client() {        try {            // login at server at local host...
this is my code I want the opposite i want to convert a postfix expression to...
this is my code I want the opposite i want to convert a postfix expression to infix expression #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c; } char pop(Stack *st) {   char c = st->s[st->top];   st->top--;   //(A+B)*(C+D)   return c; } /* function to check whether a character is an operator or not. this function...
The code following is what I have so far. It does not meet my requirements. My...
The code following is what I have so far. It does not meet my requirements. My problem is that while this program runs, it doesn't let the user execute the functions of addBook, isInList or compareLists to add, check, or compare. Please assist in correcting this issue. Thank you! Write a C++ program to implement a singly linked list of books. The book details should include the following: title, author, and ISBN. The program should include the following functions: addBook:...
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
(Python) This is my code for printing a roster for a team. When I print to...
(Python) This is my code for printing a roster for a team. When I print to the console, it makes the first player's name show up as number 2, and it says [] (its just blank for 1). How can I fix that so the first player's name is 1, not skipping 1 and going to 2. def file_to_dictionary(rosterFile): myDictionary={} myDict=[]    with open(rosterFile,'r') as f: for line in f:    (num,first,last,position)=line.split() myDictionary[num]= myDict myDict=[first, last, position] print (myDictionary) return...
this is my code in python I am trying to open a file and then print...
this is my code in python I am trying to open a file and then print the contents on my console but when i run it nothing prints in the console def file_to_dictionary(rosterFile): myDictionary={}    with open(rosterFile,'r') as f: for line in f: myDictionary.append(line.strip()) print(myDictionary)             return myDictionary    file_to_dictionary((f"../data/Roster.txt"))      
This is my code I want the average temp for the week to be printed when...
This is my code I want the average temp for the week to be printed when the user types : 'week' currently when the user types  'week' it only prints  Monday - Sunday and the average temp for each day. import java.util.Arrays; import java.util.ArrayList; import java.util.Scanner; public class weeklytemps {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);                  ArrayList Day = new ArrayList(Arrays.asList(    "Monday","Tuesday","Wednesday","Thurday","Friday","Saturday","Sunday")); // Stores days of the week...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT