如何使用REST API从Python脚本更新Jira v5.1中的问题

时间:2012-12-07 12:00:11

标签: python rest jira

我希望能够使用REST api从Python脚本更新Jira v5.1中的问题。我有以下代码来提取现有问题的信息,这完全有效:

import urllib2
import urllib
import cookielib
import json

serverURL = 'http://jiraserver.com'

# Get the authentication cookie using the REST API
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
authURL = serverURL + '/rest/auth/latest/session'
creds = {'username' : jirauser, 'password' : passwd}
req = urllib2.Request(authURL)
req.add_data(json.dumps(creds))
req.add_header("Content-type", "application/json")
req.add_header("Accept", "application/json")
fp = opener.open(req)
fp.close()

queryURL = serverURL + '/rest/api/latest/issue/SANDBOX-150'
req = urllib2.Request(queryURL)
req.add_header("Content-type", "application/json")
req.add_header("Accept", "application/json")
fp = opener.open(req)
data = json.load(fp)
fp.close()

我想扩展这个以便能够更新同样的问题,我有以下代码:

queryURL = serverURL + '/rest/api/latest/issue/SANDBOX-150'

issueUpdate =  {
    'update': {
        'comment': [
            {
                'add': {
                    'body': 'this is a comment'
                }
            }
        ]  
    }
}
req = urllib2.Request(queryURL)
req.add_data(json.dumps(issueUpdate))
req.add_header("Content-type", "application/json")
req.add_header("Accept", "application/json")
fp = opener.open(req)
fp.close()

当我尝试执行代码时,收到以下错误消息:

File "/usr/lib64/python2.6/urllib2.py", line 397, in open
response = meth(req, response)
    File "/usr/lib64/python2.6/urllib2.py", line 510, in http_response
        'http', request, response, code, msg, hdrs)

    File "/usr/lib64/python2.6/urllib2.py", line 435, in error
        return self._call_chain(*args)

    File "/usr/lib64/python2.6/urllib2.py", line 369, in _call_chain
        result = func(*args)
    File "/usr/lib64/python2.6/urllib2.py", line 518, in http_error_default 
        raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
    urllib2.HTTPError: HTTP Error 405: Method Not Allowed

,错误指向我代码中的“fp = opener.open(req)”。

我试图搜索网络,看看我是否能找到解决方案,但没有运气。有谁知道我做错了什么?

谢谢和问候

1 个答案:

答案 0 :(得分:4)

如果您使用的是Python 2.7.x,我推荐使用jira-python。它是一个Python包,用于处理与Jira的整个REST通信:

http://jira-python.readthedocs.org/en/latest/