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...
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...
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):      ...
can you please create the code program in PYTHON for me. i want to create array...
can you please create the code program in PYTHON for me. i want to create array matrix Nx1 (N is multiple of 4 and start from 16), and matrix has the value of elements like this: if N = 16, matrix is [ 4 4 4 4 -4 -4 -4 -4 4 4 4 4 -4 -4 -4 -4] if N = 64, matrix is [8 8 8 8 8 8 8 8 -8 -8 -8 -8 -8 -8 -8...
hi i do not know what is wrong with my python code. this is the class:...
hi i do not know what is wrong with my python code. this is the class: class Cuboid: def __init__(self, width, length, height, colour): self.__width = width self.__length = length self.__height = height self.__colour = colour self.surface_area = (2 * (width * length) + 2 * (width * height) + 2 * (length * height)) self.volume = height * length * width def get_width(self): return self.__width def get_length(self): return self.__length def get_height(self): return self.__height def get_colour(self): return self.__colour def set_width(self,...
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...
Working with Python. I am trying to make my code go through each subject in my...
Working with Python. I am trying to make my code go through each subject in my sample size and request something about it. For example, I have my code request from the user to input a sample size N. If I said sample size was 5 for example, I want the code to ask the user the following: "Enter age of subject 1" "Enter age of subject 2" "Enter age of subject 3" "Enter age of subject 4" "Enter age...
I have an unexpected indent with my python code. please find out whats wrong with my...
I have an unexpected indent with my python code. please find out whats wrong with my code and run it to show that it works here is the code : def main(): lis = inputData() customerType = convertAcct2String(lis[0]) bushCost = getBushCost(lis[0],int(lis[1],10)) flowerCost = getFlowerBedCost(int(lis[2],10),int(lis[3],10)) fertiCost = getFertilCost(int(lis[4],10)) totalCost = calculateBill(bushCost,fertiCost,flowerCost) printReciept(customerType,totalCost,bushCost,fertiCost,flowerCost) def inputData(): account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage = input("Please enter values").split() return [account, number_of_bushes,flower_bed_length,flower_bed_width,lawn_square_footage] def convertAcct2String(accountType): if accountType== "P": return "Preferred" elif accountType == "R": return "Regular" elif accountType == "N": return...
my topic is "mudguard fender of motorbike" this is the product i seleted. so i want...
my topic is "mudguard fender of motorbike" this is the product i seleted. so i want " Cost estimation " for mudguard fender of motorbike
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT