gpt4 book ai didi

Python Flask block 数据上传不起作用

转载 作者:行者123 更新时间:2023-12-03 17:00:05 24 4
gpt4 key购买 nike

我正在尝试从客户端(使用 Python request.post)上传一个大文件(比如 ~1GB)到 flask 服务器。

当客户端以 1024 block 为单位向服务器发送请求时,服务器不会读取整个文件并保存到服务器 0kb。

你能帮我调试一下我在这里的错误吗。

服务器 - Flask 代码:

from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = 'uploads/'

@app.route("/upload/<filename>", methods=["POST", "PUT"])
def upload_process(filename):
filename = secure_filename(filename)
fileFullPath = os.path.join(app.config['UPLOAD_FOLDER'], filename)

with open(fileFullPath, "wb") as f:
chunk_size = 1024
chunk = request.stream.read(chunk_size)
f.write(chunk)
return jsonify({'filename': filename})


if __name__ == '__main__':
app.run(host="0.0.0.0", port=int("8080"),debug=True)

客户端 - 请求代码

import os
import requests


def read_in_chunks(file_object, chunk_size=1024):
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data


def main(fname, url):
content_path = os.path.abspath(fname)
with open(content_path, 'r') as f:
try:
r = requests.post(url, data=read_in_chunks(f))
print "r: {0}".format(r)
except Exception, e:
print e


if __name__ == '__main__':
filename = 'bigfile.zip' # ~1GB
url = 'http://localhost:8080/upload/{0}'.format(filename)
main(filename, url)

最佳答案

请使用 'file.stream.read(chunk_size)' 而不是 request.stream.read(chunk_size)。它对我有用...!

关于Python Flask block 数据上传不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43383823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com