python - 如何使用 tempfile.NamedTemporaryFile() 保存图像?
问题描述
我正在尝试用 Python 编写一个代码,该代码将在 tableau 中获取仪表板的图片并将其发送到松弛通道。第一部分完美运行并将图像保存到我的本地笔记本电脑。但是,当尝试将图像保存在临时路径中并将其发送到通道时,我收到错误消息:
---> 45 f = {'file': (temp_file.name, open(temp_file.name, 'rb'), 'png')}
46 response = requests.post(url='slack./com/api/files.upload', data= 47 {'token': bot_token, 'channels': slack_channels, 'media': f,'initial_comment' :''},
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Userlogin-~1\\AppData\\Local\\Temp\\tmp3fzm10gj.png'
这是代码:
import requests
from slack import WebClient
from datetime import date, timedelta, datetime
import tableauserverclient as TSC
from tableau_api_lib import TableauServerConnection
from tableau_api_lib.utils.querying import get_views_dataframe, get_view_data_dataframe
req_option = TSC.RequestOptions().page_size(1000)
image_req_option = TSC.ImageRequestOptions(imageresolution=TSC.ImageRequestOptions.Resolution.High)
with server.auth.sign_in(tableau_auth):
all_workbooks, pagination_item = server.workbooks.get(req_option)
workbook_id_ = [workbook.id for workbook in all_workbooks if workbook.name == workbook_name][0]
workbook = server.workbooks.get_by_id(workbook_id_)
all_views= workbook.views
for view_item in all_views:
if view_item.name == view_name:
with tempfile.NamedTemporaryFile(suffix='.png', delete=True) as temp_file:
server.views.populate_image(view_item, req_options=image_req_option)
temp_file.write(view_item.image)
print('image is created')
# I get the error after the print
f = {'file': (temp_file.name, open(temp_file.name, 'rb'), 'png')}
response = requests.post(url='https://slack./com/api/files.upload', data=
{'token': bot_token, 'channels': slack_channels, 'media': f, 'initial_comment' :''},
headers={'Accept': 'application/json'}, files=f)
print('the image is in the channel')
解决方案
发生错误是因为您试图在此处重新打开已打开的文件:
f = {'file': (temp_file.name, open(temp_file.name, 'rb'), 'png')}
请尝试:
temp_file.file.seek(0) # change the position to the beginning of the file
f = {'file': (temp_file.name, temp_file, 'png')}
推荐阅读
- pandas - pandas 从 apply 函数返回多个 DataFrame
- substrate - 第一个教程:启动你的节点
- javascript - 选择单选按钮时添加弹出下拉列表
- git - Flutter Project size exceeding limit on Git
- sql - Query first slow gets faster after expanding indexes via SMSS
- c# - C# PerformClick method in invisible form
- angular - connection refused from frontend to backend in k8s cluster
- apache-spark - How to pivot pyspark dataframe rows to columns
- postgresql - postgres transactions rate slows after a while
- postgresql - 订单数据 - 重叠的用户 ID