Вставьте или запишите данные в .txt файл с колбой - PullRequest
0 голосов
/ 06 декабря 2018

Я пробовал существующий код, но он все равно не работает.Моя проблема заключается в том, как вставить данные в файл .txt с помощью формы Flask.

Ниже приведен мой код 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>

Я очень благодарен за помощь и решение от всех вас.

1 Ответ

0 голосов
/ 06 декабря 2018

Обновите ваш код, как показано ниже

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...