首页 > 解决方案 > 我无法让这个简单的表单更新程序工作

问题描述

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

以前,这些函数(例如 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 的数据显示在它应该的两个地方。当表单被更改并提交时,数据被覆盖(即删除)但不会被替换。我怀疑这与我在更新函数中调用表单数据的方式有关,但我不知道。我几周前才拿起这个,我没有太多时间去修补。不过,我已经为这个问题困扰了一天多。

请帮忙!

标签: pythonflask

解决方案


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

这是我重新创建的应用程序的最小工作版本。它更新text.html表单提交并使用会话向用户发送消息。

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()

运行应用程序后,您将获得如下页面:

在此处输入图像描述

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

在此处输入图像描述


推荐阅读