I am creating a simple flask website with a login and register page. The login page works fine with login information stored in a csv file. On the register page, after validating username and password, my code fails when attempting to append the csv file with the username and password the user inputs. I get OSError: [Errno 9] Bad file descriptor during the open csv for append line. My code isn't elegant, but it mostly works for me now and I don't have time to make major changes.
method to verify input data I edited the previous post to show my minimal reproducible code.
@app.route('/register',methods=["GET","POST"])
def register():
if request.method == "POST":
import csv
import os
username = request.form['username']
pwd = request.form['password']
with open('username_pw.csv', 'a') as read:
reader = csv.writer(read,delimiter=",")
reader.writerow([username,pwd])
return render_template('login.html',msg=msg)
return render_template('register.html')
Traceback (I reposted the new traceback which looks the same to me)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\robms\Documents\School\Python\Lib\site-packages\flask\app.py", line 2528, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\robms\Documents\School\Python\Lib\site-packages\flask\app.py", line 1825, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\robms\Documents\School\Python\Lib\site-packages\flask\app.py", line 1823, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\robms\Documents\School\Python\Lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\robms\Documents\School\Python\Programs\flask\wk_7_lab\wk_7_lab.py", line 77, in register
with open('username_pw.csv', 'a') as read:
OSError: [Errno 9] Bad file descriptor
127.0.0.1 - - [03/Mar/2023 17:22:04] "POST /register HTTP/1.1" 500 -
I've tried closing my read file and using pandas, but I keep getting errors. I've also searched scoured much of google.
For those in search of an answer to this problem, I couldn't figure out how to do it. I switched to a txt file and used the code below for a simple username/password storage. If time permitted, I definitely would have pursued a DB type login system like SQLite.
To append the file
file = open("user_pw.txt","a")
file.write(username+" "+pwd+"\n")
To read the file
for line in open("user_pw.txt","r").readlines():
login_info = line.split()
if username == login_info[0] and pwd == login_info[1]:
return True
return False