How to write data to a text file in Flask? [duplicate]

社会主义新天地 提交于 2019-12-11 08:42:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!