2011-11-12 60 views
2

我想創建一個使用REST API登錄到JIRA的python腳本。爲此,我需要向JIRA服務器發送登錄表單(使用用戶名和密碼)並存儲檢索到的cookie(最好是作爲文件中的字段)。如何在Python中發佈並接收cookie?

這裏的登錄文檔: http://confluence.atlassian.com/display/JIRA042/JIRA+REST+API+(Alpha)+Tutorial#JIRARESTAPIAlphaTutorial-LoggingIn

這是一個工作curl命令做的正是我想要的:

curl -c cookie_jar -H "Content-Type: application/json" -d '{"username" : "admin", "password" : "hunter2"}' http://localhost:8080/rest/auth/latest/session

我怎麼能複製這個在Python?最好沒有任何額外的庫。

+0

http://docs.python.org/library/urllib2.html – NullUserException

回答

2

您應該使用LWPCookieJar

import urllib, urllib2, cookielib 
url='http://localhost:8080/rest/auth/latest/session' 
post={"username" : "admin", "password" : "hunter2"} 
post_data=urllib.urlencode(post) 
cookie = cookielib.LWPCookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) 
opener.open(url,post_data) 
cookie.save('cookie_filename', True)