@app.route('/login', methods=['GET', 'POST']) # You should specify 'POST' method for form submission
def login():
if request.method == 'POST':
username = request.form.get('email')
password = request.form.get('password')
loginInfo = {'u': username, 'p': password}
# Open the file in 'w' mode to write data
with open('passwords.json', 'w') as file:
json.dump(loginInfo, file)
return render_template('login.html')
I don’t think you know Flask properly then because, yes, that will run. I have no clue where you even got that idea from. The return render_template('login.html') is at the end of the if statement; therefore, in that context, it means if the request method isn’t POST , it will return the login template. Also, if you just define POST as the method, it will automatically add GET as well.
I did try it; I do the same exact thing for some of the routes in my image hoster, and it works perfectly fine.
EDIT: I stand corrected; it does not work. I was looking at it wrong; my bad. Yeah, just include “GET” in the methods, and it will work, lol. I thought it was like a backend API; that’s why I only put POST and not GET. My code was still correct, just not in this context. In this context, /login is a frontend that’s simply sending a POST request to the same URL path and retrieving the form data, and then performing whatever is intended afterwards.
When you use <form action="/forum" method="post">, then it posts to /forum but your code to handle it is at /login. This means that none of the code that writes it to the json is executing.
Also, you currently have the forum route only accepting POST requests but you’re trying to return an html page which won’t work as it will return a 405 (Method not allowed error).
Another thing, you currently have with open('passwords.json', 'w') as file:. The W means “write” and it basically tells the program to write to the file. This works if you want it to re-write the file every time but if you want it to add new information and also keep old information then this won’t work.
Ok guys, I found the Solution myself: put the request and the writing in the /forum route, not /login.
P.S. This was before I checked @CosmicBear’s repl. I checked it just before I wrote this.