zhangjiangtao
zhangjiangtao

Reputation: 371

How can I post an attachment to jira via python

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 "[email protected]" /rest/api/2/issue/TEST-123/attachments" And I don't want use subprocess.popen

Upvotes: 5

Views: 20283

Answers (4)

Karthik Sagar
Karthik Sagar

Reputation: 444

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

Upvotes: 6

sadpanduar
sadpanduar

Reputation: 84

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

Upvotes: 6

zhangjiangtao
zhangjiangtao

Reputation: 371

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()

Upvotes: 2

bosnjak
bosnjak

Reputation: 8614

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

    Upvotes: 4

    Related Questions