html 如何从flask python将用户信息写入文本文件

ipakzgxi  于 2022-12-09  发布在  Python
关注(0)|答案(1)|浏览(106)

我正在做一个关于将用户注册信息写入.txt文件的作业。从那里,当用户试图注册时,它会检查电子邮件和用户名是否已被使用,如果是,它会告诉用户电子邮件和用户名不可用。当用户登录时,它会检查.txt文件中的用户名和密码是否匹配。
`

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)

`
我在保存用户信息时遇到问题。它根本没有写入.txt文件,因此我无法检索和检查它。
我不知道从这里去哪里。

tsm1rwdh

tsm1rwdh1#

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.

相关问题