简体   繁体   中英

Python Flask WTForms - appending files based on user input

I'm having some difficulties finding information about this:

I'm using FLASK and Python for this. I would like the user to input some text in an HTML form, and upon submission, the text to be sent to python and create/append a file. (WPA_SUPPLICANT) to ultimately connect the user to the wireless network.

Please help me out with the flask code for this action. this is the closest thing I could find! I can't figure out what the template for this code should look like.

from flask import Flask, render_template, request, redirect, url_for
import datetime
app = Flask(__name__)

@app.route("/")
def hello():
   now = datetime.datetime.now()
   timeString = now.strftime("%Y-%m-%d %H:%M")
   f=open('/boot/wpa_supplicant.conf','r')
   fp=f.read()
   templateData = {
      'title' : 'HELLO!',
      'time': timeString,
      'WPA': fp
      }
   f.close()
   return render_template('main.html', **templateData)

@app.route('/data', methods=['POST'])
def handle_data():
   newWPA=request.form['indexMain']
   print newWPA
   f=open('/boot/wpa_supplicant.conf','w')
   f.write(newWPA)
   f.close
   return redirect(url_for('hello'))

if __name__ == "__main__":
   app.run(host='0.0.0.0', port=80, debug=True)

Please advise! thank you.

Handling simple forms is prominently featured in the Flask docs and quickstart . Use request.form to access form data. Using WTForms is even simpler, and is clearly explained in the [docs] as well.

project/app.py :

from flask import Flask, request, redirect, url_for
from flask_wtf import Form
from wtforms.fields import PasswordField
from wtforms.validators import InputRequired

app = Flask(__name__)

class WifiForm(Form):
    password = PasswordField(validators=[InputRequired()])

@app.route('/wifi-password', methods=['GET', 'POST'])
def wifi_password():
    form = WifiForm()

    if form.validate_on_submit():
        password = form.password.data

        with open('/boot/wpa_supplicant.conf', 'w') as f:
            f.write('valid conf file with password')

        return redirect(url_for('index'))

    return render_template('wifi_password.html', form=form)

project/templates/wifi_password.html :

<html>
<head>
<title>WiFi Password</title>
</head>
<body>
    <form method="POST">
        {{ form.hidden_tag() }}
        {{ form.password }}
        <input type="submit"/>
    </form>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM