FogBugz » FogBugzPy A Python wrapper for the FogBugz API Read More
Clone URL:  
Pushed to one repository · View In Graph Contained in master

Fixed encoding issues. Login now works on Python 3

--HG--
extra : rebase_source : 0fd7d74990412f40e224111d62c8eaebc7c2231e

Changeset 14aa9294a3a2

Parent 133415d1edf2

by Jason R. Coombs

Changes to one file · Browse files at 14aa9294a3a2 Showing diff from parent 133415d1edf2 Diff from another changeset...

Change 1 of 3 Show Changes Only fogbugz.py Stacked
1
2
3
4
5
6
7
8
9
10
11
 
12
13
 
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
 
97
98
99
100
101
 
102
103
104
105
106
107
108
109
 
 
 
 
110
111
 
112
113
114
115
116
117
118
119
120
 
121
122
123
124
125
 
 
126
127
128
129
130
 
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
1
2
3
4
5
6
7
8
9
10
 
11
12
 
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
 
96
97
98
99
100
 
101
102
103
104
105
 
 
 
 
106
107
108
109
110
 
111
112
113
114
115
116
117
118
119
 
120
121
122
123
124
125
126
127
128
129
130
131
 
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
 import sys  try:   from email.generator import _make_boundary  except ImportError:   from mimetools import choose_boundary as _make_boundary  try:   import urllib.request as urllib_request  except ImportError:   import urllib2 as urllib_request  try: - from io import StringIO + from io import BytesIO  except ImportError: - from StringIO import StringIO + from StringIO import StringIO as BytesIO    try:   basestring  except NameError:   basestring = str    from bs4 import BeautifulSoup, CData    DEBUG = False # Set to True for debugging output.    class FogBugzAPIError(Exception):   pass    class FogBugzLogonError(FogBugzAPIError):   pass    class FogBugzConnectionError(FogBugzAPIError):   pass    class FogBugz:   def __init__(self, url, token=None):   self.__handlerCache = {}   if not url.endswith('/'):   url += '/'     if token:   self._token = token.encode('utf-8')   else:   self._token = None     self._opener = urllib_request.build_opener()   try:   soup = BeautifulSoup(self._opener.open(url + 'api.xml'))   except (urllib_request.URLError, urllib_request.HTTPError):   e = sys.exc_info()[1]   raise FogBugzConnectionError("Library could not connect to the FogBugz API. Either this installation of FogBugz does not support the API, or the url, %s, is incorrect.\n\nError: %s" % (self._url, e))   self._url = url + soup.response.url.string   self.currentFilter = None     def logon(self, username, password):   """   Logs the user on to FogBugz.     Returns None for a successful login.   """   if self._token:   self.logoff()   try:   response = self.__makerequest('logon', email=username, password=password)   except FogBugzAPIError:   e = sys.exc_info()[1]   raise FogBugzLogonError(e)     self._token = response.token.string   if type(self._token) == CData:   self._token = self._token.encode('utf-8')     def logoff(self):   """   Logs off the current user.   """   self.__makerequest('logoff')   self._token = None     def token(self,token):   """   Set the token without actually logging on. More secure.   """   self._token = token.encode('utf-8')     def __encode_multipart_formdata(self, fields, files):   """   fields is a sequence of (key, value) elements for regular form fields.   files is a sequence of (filename, filehandle) files to be uploaded   returns (content_type, body)   """   BOUNDARY = _make_boundary()     if len(files) > 0:   fields['nFileCount'] = str(len(files))     crlf = '\r\n' - buf = StringIO() + buf = BytesIO()     for k, v in fields.items():   if DEBUG:   print("field: %s: %s"% (repr(k), repr(v))) - buf.write(crlf.join([ '--' + BOUNDARY, 'Content-disposition: form-data; name="%s"' % k, '', str(v), '' ])) + buf.write(crlf.join([ '--' + BOUNDARY, 'Content-disposition: form-data; name="%s"' % k, '', v, '' ]).encode('utf-8'))     n = 0   for f, h in files.items():   n += 1 - buf.write(crlf.join([ '--' + BOUNDARY, 'Content-disposition: form-data; name="File%d"; filename="%s"' % ( n, f), '' ])) - buf.write(crlf.join([ 'Content-type: application/octet-stream', '', '' ])) - buf.write(h.read()) - buf.write(crlf) + buf.write(crlf.join([ '--' + BOUNDARY, 'Content-disposition: form-data; name="File%d"; filename="%s"' % ( n, f), '' ]).encode('utf-8')) + buf.write(crlf.join([ 'Content-type: application/octet-stream', '', '' ]).encode('utf-8')) + buf.write(h.read().encode('utf-8')) + buf.write(crlf.encode('utf-8'))   - buf.write('--' + BOUNDARY + '--' + crlf) + buf.write(('--' + BOUNDARY + '--' + crlf).encode('utf-8'))   content_type = "multipart/form-data; boundary=%s" % BOUNDARY   return content_type, buf.getvalue()     def __makerequest(self, cmd, **kwargs):   kwargs["cmd"] = cmd   if self._token:   kwargs["token"] = self._token   - fields = dict([k, v.encode('utf-8') if isinstance(v,basestring) else v] for k, v in kwargs.items()) + fields = kwargs   files = fields.get('Files', {})   if 'Files' in fields:   del fields['Files']     content_type, body = self.__encode_multipart_formdata(fields, files) + if DEBUG: + print(body)   headers = { 'Content-Type': content_type,   'Content-Length': str(len(body))}     try: - request = urllib_request.Request(self._url.encode('utf-8'), body, headers) + request = urllib_request.Request(self._url, body, headers)   response = BeautifulSoup(self._opener.open(request)).response   except urllib_request.URLError:   e = sys.exc_info()[1]   raise FogBugzConnectionError(e)   except UnicodeDecodeError:   e = sys.exc_info()[1]   print(kwargs)   raise     if response.error:   raise FogBugzAPIError('Error Code %s: %s' % (response.error['code'], response.error.string,))   return response     def __getattr__(self, name):   """   Handle all FogBugz API calls.     >>> fb.logon(email@example.com, password)   >>> response = fb.search(q="assignedto:email")   """     # Let's leave the private stuff to Python   if name.startswith("__"):   raise AttributeError("No such attribute '%s'" % name)     if not self.__handlerCache.has_key(name):   def handler(**kwargs):   return self.__makerequest(name, **kwargs)   self.__handlerCache[name] = handler   return self.__handlerCache[name]