如何使用python通过hipchatapi发送文件?

2024-04-25 22:01:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用requests和{}库和hipcatapi将本地.csv文件上载到hipcatroom。这是我正在使用的代码:

import os
import re
import sys
import requests

from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase

from email import encoders


def hipchat_file(token, room, filepath, host='api.hipchat.com'):

    """ Send file to a HipChat room via API version 2
    Parameters
    ----------
    token : str
        HipChat API version 2 compatible token - must be token for active user
    room: str
        Name or API ID of the room to notify
    filepath: str
        Full path of file to be sent
    host: str, optional
        Host to connect to, defaults to api.hipchat.com
    """

    if not os.path.isfile(filepath): raise ValueError("File '{0}' does not exist".format(filepath))

    url = "https://{0}/v2/room/{1}/share/file".format(host, room)
    headers = {'Authorization': 'Bearer {}'.format(token),
               'Accept-Charset': 'UTF-8',
               'Content-Type': 'multipart/related'}

    related = MIMEMultipart('related')
    part    = MIMEBase('application', "octet-stream")
    part.set_payload(open(filepath, "rb").read())

    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(filepath)))
    related.attach(part)


    raw_headers, body = related.as_string().split('\n\n', 1)


    boundary = re.search('boundary="([^"]*)"', raw_headers).group(1)
    headers['Content-Type'] = 'multipart/related; boundary="{}"'.format(boundary)

    # r = requests.post(url, data = body, headers = headers)
    r = requests.put(url, data = body, headers = headers)
    r.raise_for_status()



    print('done')


my_token = 'f0rh4r4mb3'
my_room = 'test' 
my_file = r"L:\data\data\0\my_file.csv"
my_message = 'Check out this cool file'  # optional

try:
    hipchat_file(my_token, my_room, my_file)
except Exception as e:
        msg = "[ERROR] HipChat file failed: '{0}'".format(e)
        print(msg, file=sys.stderr)
        sys.exit(1)

但我一直收到错误代码:

^{pr2}$

当我转到那个链接时,我看到了:

{
  "error": {
    "code": 405,
    "message": "<p>The method is not allowed for the requested URL.</p>",
    "type": "Method Not Allowed"
  }
}

我想我已经尽力了,包括换岗换人,但都没用。我能试试什么?在


Tags: toimporttokenformatmyrequestsfileheaders