Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# -*- coding: utf-8 -*- 

2""" 

3@file 

4@brief Wrapper around GitLab API. 

5""" 

6 

7import json 

8 

9 

10class GitLabException(Exception): 

11 

12 """ 

13 specific exception, stores the request 

14 """ 

15 

16 def __init__(self, mes, req=None): 

17 """ 

18 @param mes message 

19 @param req request which caused the failure 

20 """ 

21 Exception.__init__(self, mes) 

22 self.request = req 

23 

24 def __str__(self): 

25 """ 

26 usual 

27 """ 

28 if self.request is None: 

29 return Exception.__str__(self) 

30 else: 

31 return "{0}\nCODE: {1}\n[giterror]\n{2}".format( 

32 Exception.__str__(self), self.request.status_code, self.request.content) 

33 

34 

35class GitLabAPI: 

36 

37 """ 

38 Wrapper around GitLab Server. 

39 

40 The API is defined at `gitlabhq/doc/api <https://github.com/gitlabhq/gitlabhq/tree/master/doc/api>`_ 

41 """ 

42 

43 def __init__(self, host, verify_ssl=True): 

44 """ 

45 constructor 

46 

47 @param host git lab host 

48 @param verify_ssl use_ssl (SSL connection) 

49 """ 

50 self.host = host.rstrip("/") 

51 if not self.host.startswith( 

52 "https://") and not self.host.startswith("http://"): 

53 raise GitLabException("host should start with https:// or http://") 

54 

55 self.api_url = self.host + "/api/v3" 

56 self.verify_ssl = verify_ssl 

57 

58 def login(self, user, password): 

59 """ 

60 login 

61 

62 @param user user 

63 @param password password 

64 """ 

65 import requests 

66 data = {"login": user, "password": password} 

67 url = "{0}/Session".format(self.api_url) 

68 request = requests.post(url, data=data, verify=self.verify_ssl, 

69 headers={"connection": "close"}) 

70 if request.status_code == 201: 

71 self.token = json.loads( 

72 request.content.decode("utf-8"))['private_token'] 

73 self.headers = {"PRIVATE-TOKEN": self.token, "connection": "close"} 

74 elif request.status_code == 404: 

75 raise GitLabException("unable to login to " + url, request) 

76 else: 

77 msg = json.loads(request.content.decode("utf-8"))['message'] 

78 raise GitLabException( 

79 "unable to login to " + url + "\n" + msg, request) 

80 

81 def get_projects(self, page=1, per_page=100): 

82 """ 

83 returns a list of dictionaries 

84 

85 @return list of dictionaries 

86 """ 

87 import requests 

88 data = {'page': page, 'per_page': per_page} 

89 

90 request = requests.get( 

91 self.api_url, params=data, headers=self.headers, verify=self.verify_ssl) 

92 if request.status_code == 200: 

93 return json.loads(request.content.decode("utf-8")) 

94 else: 

95 raise GitLabException( 

96 "unable to retreive the list of projects: {0}".format(request), request)