我正在尝试使用.csv
和requests
库以及HipChat API将本地email
文件上传到hipchat房间。这是我正在使用的代码:
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)
但我一直收到错误代码:
'405 Client Error: Method Not Allowed for url: https://api.hipchat.com/v2/room/test/share/file'
当我转到那个链接时,我看到了这一点:
{
"error": {
"code": 405,
"message": "<p>The method is not allowed for the requested URL.</p>",
"type": "Method Not Allowed"
}
}
我认为我已经尽力而为,包括更改帖子以获取和放置,但没有任何效果。我该怎么办?