python - 创建一个最小的烧瓶/请求文件上传器
问题描述
我正在尝试创建一个最小的烧瓶服务器/客户端 python 电影文件上传器,但我的客户端代码似乎无法正常工作,我想知道我是否需要比我拥有的更多?
服务器.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST', 'PUT'])
def hello_world():
file = request.files
return(str(file))
运行方式:烧瓶运行
上传者.py
import requests
files = {'file': open("BigBuckBunny_320x180.mp4")}
r = requests.post("http://127.0.0.1:5000/", files)
print(r.text)
运行为:python Uploader.py
但是该hello_world
方法返回ImmutableMultiDict([])
出于调试目的,我使用了以下似乎可行的 curl 片段:
curl -i -X PUT -F filedata=@BigBuckBunny_320x180.mp4 "http://localhost:5000/"
并返回
ImmutableMultiDict([('file', <FileStorage: u'BigBuckBunny_320x180.mp4' ('application/octet-stream')>)])
任何想法为什么Uploader.py
失败?
解决方案
我尝试了你给我们的例子,我想我设法找到了解决方案。
经过一番挖掘,我发现您可以使用模块流式传输请求:requests
Requests 支持流式上传,允许您发送大型流或文件而无需将它们读入内存。
您只需要提供一个要流式传输的文件并以读取二进制模式打开它,rb
.
应用程序.py
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST', 'PUT'])
def hello_world():
# 'bw' is write binary mode
with open("BigBuckBunny_320x180_flask_upload.mp4", "bw") as f:
chunk_size = 4096
while True:
chunk = request.stream.read(chunk_size)
if len(chunk) == 0:
return 'Done'
f.write(chunk)
if __name__ == '__main__':
app.run()
上传者.py
import requests
# Give proper path to your file, I used mine from flask app directory
with open('BigBuckBunny_320x180.mp4', 'rb') as f:
requests.post('http://127.0.0.1:5000/', data=f)
检查这篇文章。
推荐阅读
- python - bmi 计算器如何重新启动计算器以返回顶部的是/否
- java - Spring Boot 2.3 数据源注入
- php - TYPO3 v10 如何在 FrontEnd 中获取对象的 crdate 或 tstamp
- excel - 使用格式和布局将多个表从 Access DB 导出到 Excel 工作簿
- django - NoReverseMatch 与 unittest
- vue.js - 如何使用路由器链接自定义导航而不是`to`道具
- vuejs2 - 如何在 vue/cli 4 应用程序的 cypress 中使用混合?
- vba - 保存类模块后解决一次访问中的写入冲突错误
- python - Matplotlib 对数图,set_xlim
- javascript - 自定义反应钩子不更新它的价值