5

I want to use python to post an attachment to jira via jira rest api and without any other packages which are needed to install. I noticed that "This resource expects a multipart post.", and I tried it,but maybe my method was wrong,I failed

I just want to know that how can I do the follow cmd via python urllib2: "curl -D- -u admin:admin -X POST -H "X-Atlassian-Token: nocheck" -F "file=@myfile.txt" /rest/api/2/issue/TEST-123/attachments" And I don't want use subprocess.popen

zhangjiangtao
  • 371
  • 1
  • 6
  • 23
  • 1
    Do some research, try out some things on your own, and if you get stuck or fail, we are always here to help you out. Show us what code of your is not giving you result and we'll let you know where you are going wrong :) – Codeek Dec 27 '14 at 12:35

4 Answers4

6

The key to getting this to work was in setting up the multipart-encoded files:

import requests

# Setup authentication credentials
credentials  = requests.auth.HTTPBasicAuth('USERNAME','PASSWORD')

# JIRA required header (as per documentation)
headers = { 'X-Atlassian-Token': 'no-check' }

# Setup multipart-encoded file
files = [ ('file', ('file.txt', open('/path/to/file.txt','rb'), 'text/plain')) ]

# (OPTIONAL) Multiple multipart-encoded files
files = [
    ('file', ('file.txt', open('/path/to/file.txt','rb'), 'text/plain')),
    ('file', ('picture.jpg', open('/path/to/picture.jpg', 'rb'), 'image/jpeg')),
    ('file', ('app.exe', open('/path/to/app.exe','rb'), 'application/octet-stream'))
]
# Please note that all entries are called 'file'. 
# Also, you should always open your files in binary mode when using requests.

# Run request
r = requests.post(url, auth=credentials, files=files, headers=headers)

https://2.python-requests.org/en/master/user/advanced/#post-multiple-multipart-encoded-files

sadpanduar
  • 84
  • 1
  • 6
  • Thanks, I was able to use this method to upload a temporary attachment to Jira Service Desk, when the atlassian python API package let me down.with HTTP error 415. – Kerridge0 May 26 '20 at 21:46
5

As in official documentation, we need to open the file in binary mode and then upload. I hope below small piece of code helps you :)

from jira import JIRA    

# Server Authentication
username = "XXXXXX"
password = "XXXXXX"

jira = JIRA(options, basic_auth=(str(username), str(password)))

# Get instance of the ticket
issue = jira.issue('PROJ-1')

# Upload the file
with open('/some/path/attachment.txt', 'rb') as f:
    jira.add_attachment(issue=issue, attachment=f)

https://jira.readthedocs.io/examples.html#attachments

Community
  • 1
  • 1
Karthik Sagar
  • 424
  • 4
  • 7
  • But there's a problem, it throws an error which goes like "dict keeps changing during iteration..." When you are using python3.8. You have to downgrade to 3.7 – Praveen Dass Oct 17 '20 at 09:08
4

You can use the jira-python package.

Install it like this:

pip install jira-python

To add attachments, use the add_attachment method of the jira.client.JIRA class:

add_attachment(*args, **kwargs) 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.)

Parameters:
  • issue – the issue to attach the attachment to
  • attachment – file-like object to attach to the issue, also works if it is a string with the filename.
  • 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.
  • You can find out more information and examples in the official documentation

    bosnjak
    • 8,424
    • 2
    • 21
    • 47
    • Sorry, I need to run this script in a jenkins,so cann't install any packages. But lucky, I have resolve it. Thanks anyway – zhangjiangtao Dec 29 '14 at 04:35
    2

    Sorry for my unclear question

    Thanks to How to POST attachment to JIRA using REST API?. I have already resolve it.

        boundary = '----------%s' % ''.join(random.sample('0123456789abcdef', 15))
        parts = []
    
        parts.append('--%s' % boundary)
        parts.append('Content-Disposition: form-data; name="file"; filename="%s"' % fpath)
        parts.append('Content-Type: %s' % 'text/plain')
        parts.append('')
        parts.append(open(fpath, 'r').read())
    
        parts.append('--%s--' % boundary)
        parts.append('')
    
        body = '\r\n'.join(parts)
    
        url = deepcopy(self.topurl)
        url += "/rest/api/2/issue/%s/attachments" % str(jrIssueId)
        req = urllib2.Request(url, body)
        req.add_header("Content-Type", "multipart/form-data; boundary=%s" % boundary)
        req.add_header("X-Atlassian-Token", "nocheck")
        res = urllib2.urlopen(req)
    
        print res.getcode()
        assert res.getcode() in range(200,207), "Error to attachFile " + jrIssueId
        return res.read()
    
    Community
    • 1
    • 1
    zhangjiangtao
    • 371
    • 1
    • 6
    • 23