python - 使用 python request.put 上传 csv 类型数据而不读取保存的 csv 文件?

标签 python python-requests

我有一个 api 端点,我正在其中使用 python 上传数据。终点接受

putHeaders = {
    'Authorization': user,

    'Content-Type': 'application/octet-stream' }

我当前的代码正在执行此操作

.将字典另存为 csv 文件

.将 csv 编码为 utf8

dataFile = open(fileData['name'], 'r').read()).encode('utf-8')

.上传文件到api端点

fileUpload = requests.put(url,
                          headers=putHeaders,
                          data=(dataFile))

我想要实现的是

加载数据而不保存

到目前为止我已经尝试过

使用

将我的字典转换为字节

data = json.dumps(payload).encode('utf-8')

并加载到 API 端点。这可行,但 api 端点中的输出不正确。

enter image description here

问题

有人知道如何上传 csv 类型数据而不实际保存文件吗?

最佳答案

编辑:使用io.StringIO()当你将 dict 写入 csv 时,作为你的类似文件的对象。然后调用get_value()并将其作为数据参数传递给 requests.put() .

有关更多详细信息,请参阅此问题:How do I write data into CSV format as string (not file)?

旧答案:

如果你的字典是这样的:

my_dict = {'col1': 1, 'col2': 2}

然后你可以将其转换为 csv 格式,如下所示:

csv_data = ','.join(list(my_dict.keys()))
csv_data += ','.join(list(my_dict.values()))
csv_data = csv_data.encode('utf8')

然后做你的requests.put()调用 data=csv_data .

关于python - 使用 python request.put 上传 csv 类型数据而不读取保存的 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60445837/

相关文章:

python - 使用 python 请求在 HTTP POST 上规避错误 414

python - BeautifulSoup 最低共同祖先

python - Keras ModelCheckpoint 不会在 Windows 上保存任何文件

Python 单元测试和对象初始化

python - Django 测试 : DatabaseError: no such table for ManyToManyField

python - 请求有效而 URLFetch 无效

python - MaxRetryError : HTTPConnectionPool: Max retries exceeded (Caused by ProtocolError ('Connection aborted.' ,错误(111, 'Connection refused')))

python - 雅虎状态检测

Python 发布请求更改日期

python - 网站不允许右键单击,网络抓取不显示正文标签之间的文本