Source

python-bitbucket / api.py

Kevin Veroneau 382c1b7 











































































import cookielib
import urllib2
import base64
import json
from urllib import urlencode

class Issue():
    title = ""
    content = ""
    component = None
    milestone = None
    version = None
    responsible = None
    priority = "major"
    status = "new"
    kind = "bug"
    def __init__(self, api, username, repository):
        self.api = api
        self.username = username
        self.repository = repository
        self.responsible = username

    def as_dict(self):
        data = {'title':self.title, 'content':self.content, 'priority':self.priority, 'status':self.status, 'kind':self.kind}
        data.update({'responsible':self.responsible})
        if self.component:
	    data.update({'component':self.component})
	if self.milestone:
	    data.update({'milestone':self.milestone})
	if self.version:
	    data.update({'version':self.version})
	return data

    def save(self):
        self.json = self.api.post(self.username, self.repository, self.as_dict())
        return self.json

class API():
    api_url = 'https://api.bitbucket.org/1.0/'

    def __init__(self, username, password, proxy=None):
        encodedstring = base64.encodestring("%s:%s" % (username, password))[:-1]
        self._auth = "Basic %s" % encodedstring
        self._opener = self._create_opener(proxy)

    def _create_opener(self, proxy=None):
        cj = cookielib.LWPCookieJar()
        cookie_handler = urllib2.HTTPCookieProcessor(cj)
        if proxy:
            proxy_handler = urllib2.ProxyHandler(proxy)
            opener = urllib2.build_opener(cookie_handler, proxy_handler)
        else:
            opener = urllib2.build_opener(cookie_handler)
        return opener

    def post(self, username, repository, data):
        query_url = self.api_url + 'repositories/%s/%s/issues/' % (username, repository)
        try:
	    req = urllib2.Request(query_url, urlencode(data), {"Authorization": self._auth })
	    handler = self._opener.open(req)
	except urllib2.HTTPError, e:
	    print e.headers
	    raise e
	return json.load(handler)

    def get_issues(self, username, repository):
        query_url = self.api_url + 'repositories/%s/%s/issues/' % (username, repository)
        try:
            req = urllib2.Request(query_url, None, {"Authorization": self._auth })
            handler = self._opener.open(req)
        except urllib2.HTTPError, e:
            print e.headers
            raise e
        return json.load(handler)
        
    def new_issue(self, username, repository):
        return Issue(self, username, repository)