且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用urllib2和python以及JIRA REST API进行基本身份验证

更新时间:2022-02-07 15:31:06

有趣的是,我昨天正在为 JIRA Python CLI .我采用了使用REST API的方法来获取身份验证cookie和自定义打开器.下面的示例显示了使用打开器将数据发布到页面上以添加组件,但是您可以替换该组件 并针对其他REST调用调用正确的URL.

Funny, I was working on this yesterday for the JIRA Python CLI. I took the approach of using the REST API to get an authentication cookie and a custom opener. The example below shows using the opener to post data to a page to add a component, but you could replace that with a call to the correct URL for a different REST call.

    """
Demonstration of using Python for a RESTful call to JIRA

Matt Doar
CustomWare
"""

import urllib
import urllib2
import cookielib

jira_serverurl = "http://jira.example.com:8080"
creds = { "username" : "admin", "password" : "admin" }
authurl = jira_serverurl + "/rest/auth/latest/session"

# Get the authentication cookie using the REST API
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
req = urllib2.Request(authurl)
req.add_data('{ "username" : "admin", "password" : "admin" }')
req.add_header("Content-type", "application/json")
req.add_header("Accept", "application/json")
fp = opener.open(req)
fp.close()

add_component_url = jira_serverurl + "/secure/project/AddComponent.jspa?pid=10020&name=ABC4"
print "Using %s" % (add_component_url)

# Have to add data to make urllib2 send a POST
values = {}
data = urllib.urlencode(values)

# Have to tell JIRA to not use a form token
headers = {'X-Atlassian-Token': 'no-check'}

request = urllib2.Request(add_component_url, data, headers=headers)
fp = opener.open(request)

print fp.read()