我正在尝试使用烧瓶框架读取文本文件。这是我的代码
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')
不幸的是,它发送了错误的请求 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 Do I need to add these lines too?我不明白这些
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))
原文由 Jonreyan 发布,翻译遵循 CC BY-SA 4.0 许可协议
假设您想要
POST /getfile
返回文本文件的内容,那么您可以简单地将getfile()
函数定义为:还要确保在 Postman 中将文件的密钥设置为
file
(如下面的屏幕截图所示):编辑: 请注意,上述方法只接受一个文件并返回其内容——它不接受 文件名 并返回其内容。