Jon*_*yan 3 python flask python-3.x flask-restful
我正在尝试使用 Flask 框架读取文本文件。这是我的代码
import os
from flask import Flask, request, redirect, url_for, flash,jsonify
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/index', methods=['GET'])
def index():
return 'Welcome'
@app.route('/getfile', methods=['POST'])
def getfile():
file = request.files['file']
with open(file,'r') as f:
file_content = f.read()
return jsonify(file_content)
if __name__ == '__main__':
app.run(host = '0.0.0.0')
Run Code Online (Sandbox Code Playgroud)
不幸的是它发送了错误的请求 400。我请求文件为request.file. .txt 位于我的磁盘中,位于 C:/Users/rbby/Desktop/Programs/hello.txt
GET 方法工作正常。POST 对我不起作用。我还应该从上面的代码中添加任何其他内容吗?
我参考了这个链接Using Flask to load a txt file through the browser and access its data for processing 我是否也需要添加这些行?我不明白这些
filename = secure_filename(file.filename)
# os.path.join is used so that paths work in every operating system
file.save(os.path.join("wherever","you","want",filename))
Run Code Online (Sandbox Code Playgroud)
假设您想要POST /getfile做的是返回文本文件的内容,那么您可以简单地将getfile()函数定义为:
def getfile():
file = request.files['file']
return file.read()
Run Code Online (Sandbox Code Playgroud)
还要确保在 Postman 中将文件的密钥设置为file(如下面的屏幕截图所示):
编辑:请注意,上面的方法只需要一个文件并返回其内容 - 它不接受filename,并返回其内容。