如何在Flask中将数据写入文本文件? [英] How to write data to a text file in Flask?
问题描述
我们的目标是将一个名为"inputed_email"的变量写入一个名为"test3.txt"的文本文件中.因为这是在服务器上发生的,所以我们需要确保此Python脚本可以访问目录和文本文件.
Our goal is to write a variable called "inputed_email" into a text file named "test3.txt". Because this takes place on the server, we need to make sure that this Python script can access the directory and text file.
@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(内部服务器错误).感谢您的帮助!
However, the code that writes to the "test3.txt" does not work. It returns error 500 (internal server error) when ran. Any help is appreciated!
推荐答案
尝试运行此
$ export FLASK_ENV=development
$ export FLASK_DEBUG=True
$ export FLASK_APP=<your .py file>
$ flask run
现在,服务器将响应回溯,而不仅仅是Internal Server Error
.但是不要在生产中使用FLASK_DEBUG
选项.
Now the server will respond with a traceback, not just Internal Server Error
. But don't use FLASK_DEBUG
option in production.
这篇关于如何在Flask中将数据写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!