python - 我无法让这个简单的表单更新程序工作

标签 python flask

我正在尝试编写一个简单的脚本,该脚本将通过表单接受用户的更改,然后将这些更改写入文件中当前的内容。然后,使用当前更新的数据直接在表单下方调用该文件。这基本上就是我目前正在写的内容。我想要一个文本框,我可以将文本放入其中,然后该文本将覆盖该文件中当前的任何文本。

以前,这些函数(例如 request.form)在我修改过的其他示例中效果很好,但当我将它们放在一起以应对自己的挑战时,似乎没有什么能像它应该的那样工作。

from flask import Flask, render_template, request
import html

app = Flask(__name__)

@app.route('/', methods=['POST']) 
def home():
    with open('text.html') as contents:
        data = contents.read()

    return render_template('test_form.html',
                           the_title = 'Test Form',
                           the_contents = data)


@app.route('/update', methods=['POST', 'GET'])
def update():
    contents = request.form['letters']
    with open('text.html', 'w') as file:
        print(contents, file=file)

    return render_template('test_form.html',
                           the_title = 'Update complete!',
                           the_contents = contents,)


app.run()

这是 test_form.html 文件:

{% extends 'base.html' %}

{% block body %}

<h2>{{ the_title }}</h2>

<form method='POST' action='update'>

    <table>
    <p>Use this form to edit the below text:</p>
        <tr>
            <td><input name='letters' type='TEXTAREA' value='{{ the_contents }}'></td>
        </tr>
        <tr>
            <td>{{ the_contents }}</td>
        </tr>
    </table>

<p>When you're ready, click this button:</p>
<p><input value='Do it!' type='SUBMIT'></p>
</form>

{% endblock %}     

最终发生的事情是页面将正常加载,其中 text.html 中的数据显示在它应该显示的两个位置。当表单更改并提交时,数据会被覆盖(即删除),但不会被替换。我怀疑这与我在更新函数中调用表单数据的方式有关,但我不知道。我几周前才拿起这个,我没有太多时间去修补。不过,我已经被这个问题困扰了一天多了。

请帮忙!

最佳答案

您的应用程序的问题似乎是 update 路由允许 get 请求,因此如果您访问该网址 /update 而不提交表单,内容将为空并且该文件将被重置。您应该从该方法列表中删除 GET 方法

这是我重新创建的应用程序的最小工作版本。它在表单提交时更新 text.html 并使用 session 向用户闪现消息。

https://flask.palletsprojects.com/en/1.0.x/patterns/flashing/#message-flashing-pattern

from flask import Flask, render_template_string, request, redirect, url_for, flash

app = Flask(__name__)
# https://flask.palletsprojects.com/en/1.0.x/patterns/flashing/#message-flashing-pattern
app.secret_key = 'SECRET KEY CHANGE THIS'


def read_contents():
    try:
        with open('text.html') as f:
            return f.read()
    except FileNotFoundError:
        return ''


def save_contents(contents: str):
    with open('text.html', 'w') as f:
        f.write(contents)


@app.route('/', methods=['GET'])
def home():
    html = '''
    {% for m in get_flashed_messages() %}
        <p>{{ m }}</p>
    {% endfor %}

    <form action="/update" method="POST">
        <textarea name="letters" rows="10">{{ contents }}</textarea>
        <button>Submit</button>
    </form>

    {% if contents %}
        <h2>Contents</h2>
        <pre>{{ contents }}</pre>
    {% endif %}
    '''
    contents = read_contents()
    return render_template_string(html, contents=contents)


@app.route('/update', methods=['POST'])
def update():
    contents = request.form['letters']
    save_contents(contents)
    flash('Update complete')
    return redirect(url_for('home'))


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

运行应用程序后,您会看到如下页面:

enter image description here

提交一些内容后,它会将您重定向回主页,并显示一条消息和显示内容的页面:

enter image description here

关于python - 我无法让这个简单的表单更新程序工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57065183/

相关文章:

javascript - 如何使用 Zapier 的 Twitter API 进行身份验证?

python - 使用 SQLalchemy 将数据从一个数据库移动到另一个备份数据库的最简单方法是什么?

python - 如何使用 Python 替换 XML 中的节点值

python - 如何阻止 PyCharm 在格式化代码时插入空格以进行精确对齐?

python - Flask-WTForms使用jQuery移至下一个表单字段

python - Flask - 防止多个打开的 mysql 连接?

python - Pandas 错误转义 %s"% escape, len(escape)

python - 如何在 jinja2 模板中显示日期时间字段? ( flask )

python - uwsgi + Flask + virtualenv ImportError : no module named site

python - 当通过不允许的方法(如 PUT、DELETE...)请求应用程序时,如何返回 json 输出?