簡體   English   中英

如何使用 tempfile.NamedTemporaryFile() 保存圖像?

[英]How to use tempfile.NamedTemporaryFile() to save an image?

我正在嘗試在 Python 中編寫代碼,該代碼將在畫面中獲取儀表板的圖片並將其發送到松弛通道。 第一部分完美運行並將圖像保存到我的本地筆記本電腦。 但是,當嘗試將圖像保存在臨時路徑中並將其發送到通道時,我收到錯誤消息:

---> 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')}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM