使用flask

时间:2018-12-06 03:00:48

标签: python flask

我已经尝试了现有代码,但是仍然失败。我的问题是如何使用Flask表单将数据插入.txt文件。

以下是我的app.py代码:

from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)

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

@app.route('/', methods=['GET', 'POST'])
def my_form_post():
    input_nopol = request.form.get['nopol']
    if request.method == 'POST' and input_nopol:
       print(listdir) 
       with open('/home/pi/web-server/nopol.txt', 'w') as f:
            f.write(str(input_nopol))   
    return render_template('index.html', nopol=input_nopol)


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

以下是模板文件夹中index.html上表单的简单代码:

<!DOCTYPE html>
   <head>
      <title>Hello</title>
   </head>

   <body>
      <form method="POST">
        <input name="text">
        <input type="submit">
      </form>   
   </body>
</html>

我非常感谢大家的帮助和解决方案。

2 个答案:

答案 0 :(得分:0)

如下更新代码

index.html

<!DOCTYPE html>
   <head>
      <title>Hello</title>
   </head>

   <body>
      <form action="" method="POST">
        <input name="text_box">
        <input type="submit">
      </form>
   </body>
</html>

app.py

from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)

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

    @app.route('/', methods=['POST'])
    def my_form_post():
        input_nopol = request.form['text_box']
        if request.method == 'POST':
           with open('nopol.txt', 'w') as f:
                f.write(str(input_nopol))
        return render_template('index.html', nopol=input_nopol)


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

答案 1 :(得分:0)

<!DOCTYPE html>
<head>
  <title>Hello</title>
</head>

<body>
  <form action="" method="POST">
    <input name="text_box">
    <input type="submit">
  </form>

from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)

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

@app.route('/', methods=['POST'])
def my_form_post():
    input_nopol = request.form['text_box']
    if request.method == 'POST':
       with open('nopol.txt', 'w') as f:
            f.write(str(input_nopol))
    return render_template('index.html', nopol=input_nopol)


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