Home > Software design >  How to write user info to a text file from flask python
How to write user info to a text file from flask python

Time:12-07

I am working on a school assignment regarding writing user registration info to a .txt file. From there, when the user tries to register it will check if the email and username has already been used, if so it will tell the user the email and username is unavailable. When the user logs in, it will check the .txt file for the username and password match.

`


from datetime import datetime
from flask import Flask, render_template, request, flash
from passlib.hash import sha256_crypt

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    """
    main page of the website
    """
    return render_template('Header.html', datetime=str(datetime.now()))


@app.route('/main/', methods=['GET', 'POST'])
def main():
    return render_template('dashboard.html', datetime=str(datetime.now()))


@app.route('/PerfectGrade/', methods=['GET', 'POST'])
def perfect_grade():
    """
    page for perfect grade gundams
    """
    return render_template('perfectgrade.html', datetime=str(datetime.now()))


@app.route('/MasterGrade/', methods=['GET', 'POST'])
def master_grade():
    """
    page for master grade gundams
    """
    return render_template('mastergrade.html', datetime=str(datetime.now()))


@app.route('/RealGrade/', methods=['GET', 'POST'])
def real_grade():
    """
    page for real grade gundams
    """
    return render_template('realgrade.html', datetime=str(datetime.now()))


@app.route('/HighGrade/', methods=['GET', 'POST'])
def high_grade():
    """
    page for high grade gundams
    """
    return render_template('highgrade.html', datetime=str(datetime.now()))


@app.route('/Register/', methods=['GET', 'POST'])
def register():
    """
    

    """
    return render_template('register.html', datetime=str(datetime.now()))


@app.route('/LoginSuccess/', methods=['POST'])
def login_success():
    """
    
    """

    return render_template('loginsuccess.html', datetime=str(datetime.now()))


@app.route('/LoginFail/', methods=['POST'])
def login_fail():
    """
    
    """

    return render_template('loginfail.html', datetime=str(datetime.now()))


@app.route('/Login/', methods=['GET', 'POST'])
def login():
    """
    
    """
    username = request.form.get("username")
    password = request.form.get("password")

    for line in open('users.txt', 'r').readlines():
        info = line.split(',')
        hashpass = info[2]
        hashpass = hashpass.rstrip('\n')
        if username == info[0] and (sha256_crypt.verify(hashpass, password)):
            flash('You are logged in!')
            return render_template('header.html')
        else:
            flash('Incorrect Password')

    return render_template('login.html', datetime=str(datetime.now()))


@app.route('/success/', methods=['POST'])
def success():
    """
    
    """
    first_name = request.form.get("first_name")
    last_name = request.form.get("last_name")
    username = request.form.get("username")
    email = request.form.get("email")
    password = request.form.get("password")

    for line in open('users.txt', 'r').readlines():
        info = line.split(',')
        check_usn = info[0]
        check_email = info[1]
        if (check_usn == username) or (check_email == email):
            flash("Username or email already exists. Please try again.")
            return render_template('register.html')
        else:
            hash_pass = sha256_crypt.hash(password)
            with open('users.txt', 'a') as f:
                f.writelines(username   email   hash_pass   first_name   last_name)
                flash("Success!")
    return render_template('success.html', datetime=str(datetime.now()), first_name=first_name, last_name=last_name, username=username, email=email)

`

I am having issues saving the user info. It is not writing to the .txt file at all therefore I cant retrieve and check it.

I am not sure of where to go from here.

CodePudding user response:

If there is currently nothing in your users.txt file at all, then your for loop block (in the success function) will not execute at all (as there is nothing to iterate over).

Also you probably want to strip the line before calling split as you will get newline characters otherwise (and your string comparisons will not match). e.g.

info = line.strip().split(',')

You'll want to do this in the login function as well.

Your if block in the success function will keep appending to the users.txt file for every iteration that does not match the username and email address you are checking for! So you'll end up with multiple entries (and success messages) at some point.

Finally, when you want to write to the users.txt file you'll be wanting to put some commas in-between your variables. Also you might want to look into using open (whenever you open files) as so (as one abbreviated example):

with open('users.txt', 'r') as f:
    for line in f.readlines():
        ...

as the manager will look after closing the file for you.

  • Related