如何在Flask中将数据写入文本文件?

时间:2018-06-20 23:42:26

标签: python file flask server writetofile

我们的目标是将名为“ inputed_email”的变量写入名为“ test3.txt”的文本文件中。因为这是在服务器上发生的,所以我们需要确保此Python脚本可以访问目录和文本文件。

@app.route('/', methods=['GET', 'POST'])
def my_form():
    inputed_email = request.form.get("email")
    if request.method == 'POST' and inputed_email:

        # write to file
        with open('/var/www/FlaskApp/FlaskApp/test3.txt', 'w') as f:
            f.write(str(inputed_email))

        return render_template('my-form.html', email=inputed_email)
    return render_template('my-form.html')

但是,写入“ test3.txt”的代码不起作用。运行时返回错误500(内部服务器错误)。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

我的猜测是您未指定正确的目录。如果flask就像Django,则该路径可能与应用程序正在运行的位置不同。尝试打印os.listdir()以查看您的位置。

from os import listdir

@app.route('/', methods=['GET', 'POST'])
def my_form():
    inputed_email = request.form.get("email")
    if request.method == 'POST' and inputed_email:
        print(listdir) ## print listdir python 2
        # write to file
        with open('/var/www/FlaskApp/FlaskApp/test3.txt', 'w') as f:
            f.write(str(inputed_email))

        return render_template('my-form.html', email=inputed_email)
    return render_template('my-form.html')

如果未在控制台上进行任何打印,则错误在行打印之前。

答案 1 :(得分:1)

尝试运行此

$ export FLASK_ENV=development
$ export FLASK_DEBUG=True
$ export FLASK_APP=<your .py file>
$ flask run

现在,服务器将响应回溯,而不仅仅是Internal Server Error。但是不要在生产中使用FLASK_DEBUG选项。