问题
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')
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!
回答1:
My guess is you are not specifying the correct directory. If flask is like Django, the path may be in different place with app is running. Try printing os.listdir() to see where you are.
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')
If it is printing nothing to the console, then the error is before the line print.
回答2:
Try running this
$ export FLASK_ENV=development
$ export FLASK_DEBUG=True
$ export FLASK_APP=<your .py file>
$ flask run
Now the server will respond with a traceback, not just Internal Server Error
. But don't use FLASK_DEBUG
option in production.
来源:https://stackoverflow.com/questions/50958510/how-to-write-data-to-a-text-file-in-flask