1

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
JavaNewb
  • 23
  • 5
  • do you have it open in excel also? – Joran Beasley Mar 03 '23 at 05:47
  • Please include the full traceback message. – tdelaney Mar 03 '23 at 05:57
  • I've added the traceback. As for the other question, no. I know I've opened it up multiple times, but I tend to close it right after. – JavaNewb Mar 03 '23 at 12:26
  • Hm. EBADF is a pretty specific error; the _easiest_ ways to make it happen involve using `os.fdopen()` instead of `open()`, or using `os.close()`, or using file descriptor settings that make a file handle not survive through a `fork()` operation. Can you make sure you're providing us a [mre]? It would be a lot easier to dig into this if the code you were giving us were complete enough that running it _without any changes or additions at all_ caused the problem you're asking about; that's not the case now -- if nothing else it's depending on Flask. – Charles Duffy Mar 03 '23 at 17:38
  • You have a race condition on your file as many requests can ask for opening it in the same time while the resource can be written by only one thread at the time. You need at least a lock on this critical section to make your code safe and avoid error due to this race condition. Bad file descriptor are such kind of error that race condition creates. Clearing the race condition would probably solve your issue. – jlandercy Mar 03 '23 at 21:52
  • How do i go about clearing the race condition? – JavaNewb Mar 03 '23 at 21:53
  • Using a lock should solve the problem. See built-in `threading.Lock` object and encompasses the critical section with an extra context manager. – jlandercy Mar 03 '23 at 21:54
  • Sorry, i'm still new to programming. I'm not sure what you mean or how to use a lock. – JavaNewb Mar 03 '23 at 21:55
  • https://docs.python.org/3/library/threading.html?highlight=lock#threading.Lock – jlandercy Mar 03 '23 at 21:57
  • Also consider using SQLite instead of a file to store your data. As I imagine the login endpoint also makes use of the critical resource. File System are not the best solution for that usage where Database offers integrity and handle concurrent r/w access. – jlandercy Mar 03 '23 at 22:01
  • I added a lock acquire before and release after the file open, but it's still giving me the same error. As for our SQLite recommendation, it's too late for me to jump into that. Im late with this assignment and have very little time to complete my next assignment. I also can't copy/paste a pre-built login scenario. I do appreciate your help though. – JavaNewb Mar 03 '23 at 22:24
  • This traceback is unreadable, and I can't easily fix it. Please use the same formatting for tracebacks that you would for multi-line code, and check the post preview before submitting. Tracebacks are carefully designed to look right in a monospace font; that's what all the `^`s are about - they're underlining code on the previous line. – Karl Knechtel Mar 03 '23 at 23:49
  • I added the traceback as code. Also, I noticed that if I delete the CSV, then let the program create it, it works fine. The moment i open it and save it again, it starts giving me the error. – JavaNewb Mar 04 '23 at 00:32

0 Answers0