【问题标题】:Python: How to send file to hipchat?Python:如何将文件发送到 hipchat?
【发布时间】:2017-07-05 16:40:02
【问题描述】:

如何使用 python API 将文件从本地计算机发送到 hipchat?我目前正在使用Hypchat,但它没有得到很好的记录。

到目前为止,这是我的代码:

import hypchat

hc = hypchat.HypChat("myKey")

room = hc.get_room('bigRoom')

我不确定如何继续。我尝试了其他方法,例如 this 之一,但我不断收到错误:

[ERROR] HipChat file failed: '405 Client Error: Method Not Allowed for url: https://api.hipchat.com/v2/room/bigRoom/share/file'

【问题讨论】:

  • 愚蠢的问题 - 但是你能不使用 Python 来执行这个任务吗?如果不是,则可能是权限问题。您是否提供/是否有任何需要的授权令牌?
  • 嗨,是的,我可以在没有 Python 的情况下执行它。

标签: python rest hipchat


【解决方案1】:

此代码允许我将任何文件发送到 hipchat 房间:

# do this:
#     pip install requests_toolbelt

from os                import path
from sys               import exit, stderr
from requests          import post
from requests_toolbelt import MultipartEncoder


class MultipartRelatedEncoder(MultipartEncoder):
    """A multipart/related encoder"""
    @property
    def content_type(self):
        return str('multipart/related; boundary={0}'.format(self.boundary_value))

    def _iter_fields(self):
        # change content-disposition from form-data to attachment
        for field in super(MultipartRelatedEncoder, self)._iter_fields():
            content_type = field.headers['Content-Type']
            field.make_multipart(content_disposition = 'attachment',
                                 content_type        = content_type)
            yield field




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

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


    url                      = "https://{0}/v2/room/{1}/share/file".format(host, room)
    headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
    headers['Authorization'] = "Bearer " + token



    m = MultipartRelatedEncoder(fields={'metadata' : (None, '', 'application/json; charset=UTF-8'),
                                        'file'     : (path.basename(filepath), open(filepath, 'rb'), 'text/csv')})

    headers['Content-type'] = m.content_type

    r = post(url, data=m, headers=headers)

if __name__ == '__main__:

    my_token = <my token>   
    my_room  = <room name>    
    my_file  = <filepath>

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

向@Martijn Pieters 致敬

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 2021-12-27
    • 2023-03-10
    • 2017-07-04
    • 2020-06-01
    • 2021-12-30
    • 1970-01-01
    • 2019-08-13
    相关资源
    最近更新 更多