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...
How can i modify my c code so that each number stored in the array is...
How can i modify my c code so that each number stored in the array is not the array index but the value of the array index converted to radians. I have already made a function for this converion above main(). Below is the code: #include <stdio.h> #include <stdlib.h> #include <math.h> float Deg2Rad (float degrees) { // Calculate & return value float Result; Result = ((M_PI*degrees)/180.0); return (Result); } int main(void) { // Declare variables int Array[90]; int i; //...
In python I have my code written and I want just 4 functions to be fix...
In python I have my code written and I want just 4 functions to be fix in my code according to rule. My code is running but it has some problem regarding to rules. (I have did all the other things so you do not have to worry about other functions) 1) all the players has to play until he/she reaches to at least 500 points in first round. When user reach 500 points for the first time, user may...
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...
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...
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...
Hi, I have this code so far and need to modify it so that the output...
Hi, I have this code so far and need to modify it so that the output does not print something like 2x^0 but instead will just print 2. Currently it prints 2x^0. I also am having a problem with the output of Polynomial 1 - Polynomial 2. If both coefficient values for the polynomials are equal instead of Polynomial 1 - Polynomial 2 = 0 it outputs nothing. Just Polynomial 1 - Polynomial 2 = For example if I input...
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...
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:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT