JIRA Python add_attachment () 405 Метод не разрешен

Я пытаюсь загрузить файл в JIRA через REST API, используя библиотеку python, найденную здесь: jira python документация

Это кажется довольно простым. Я написал метод, который позволяет мне передать проблему, а затем прикрепить имя файла. и тот, который позволяет мне получить задачу из JIRA.

from jira.client import JIRA

class JIRAReport (object):
    def attach(self,issue):
            print 'Attaching... '
            attachment = self.jira.add_attachment(issue, attachment=self.reportpath, filename='Report.xlsx')
            print 'Success!'

    def getissue(self):
            if not self.issue == None:
                return self.jira.issue(self.issue)
            return None

затем в моем основном сценарии я получаю проблему и прикрепляю файл к проблеме, которую я получил из JIRA.

report = JiraReport()
report.issue = 'ProjectKey-1'
report.reportpath = '../report_upload/tmp/' + filename
issue = report.getissue()
if not issue == None:
    report.attach(issue)
else:
    print "No Issue with Key Found"

Я могу получить проблему/создать проблему, если это необходимо, но при использовании метода self.jira.add_attachment() я получаю 405 Method Not Allowed.

Файл существует и может быть открыт.

Вот метод add_attachment() из исходный код:

def add_attachment(self, issue, attachment, filename=None):
        """
        Attach an attachment to an issue and returns a Resource for it.

        The client will *not* attempt to open or validate the attachment; it expects a file-like object to be ready
        for its use. The user is still responsible for tidying up (e.g., closing the file, killing the socket, etc.)

        :param issue: the issue to attach the attachment to
        :param attachment: file-like object to attach to the issue, also works if it is a string with the filename.
        :param filename: optional name for the attached file. If omitted, the file object's ``name`` attribute
            is used. If you aquired the file-like object by any other method than ``open()``, make sure
            that a name is specified in one way or the other.
        :rtype: an Attachment Resource
        """
        if isinstance(attachment, string_types):
            attachment = open(attachment, "rb")
        # TODO: Support attaching multiple files at once?
        url = self._get_url('issue/' + str(issue) + '/attachments')

        fname = filename
        if not fname:
            fname = os.path.basename(attachment.name)

        content_type = mimetypes.guess_type(fname)[0]
        if not content_type:
            content_type = 'application/octet-stream'

        files = {
            'file': (fname, attachment, content_type)
        }
        r = self._session.post(url, files=files, headers=self._options['headers'])
        raise_on_error(r)

        attachment = Attachment(self._options, self._session, json.loads(r.text)[0])
        return attachment

person Richard Christensen    schedule 07.05.2015    source источник


Ответы (2)


В документации упоминается, что в качестве аргумента они ожидать файлоподобный объект.

Попробуйте сделать что-то вроде:

file_obj = open('test.txt','rb')
jira.add_attachment(issue,file_obj,'test.txt')
file_obj.close()
person ThePavolC    schedule 08.05.2015
comment
он также говорит во второй половине предложения, также работает, если это строка с именем файла. Спасибо за ваш вклад. - person Richard Christensen; 08.05.2015

Убедитесь, что URL-адрес, который вы указываете для JIRA (при использовании службы по запросу), равен https://instance.atlassian.net..

Я только что нажал это, и он отправляет запрос POST на http://instance.atlassian.net и перенаправляется на https://instance.atlassian.net, но клиент отправляет запрос GET на перенаправленный адрес (см.: https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect для получения дополнительной информации)

person oldmantaiter    schedule 16.12.2015