55:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
66:license: BSD, see LICENSE for more details.
77"""
8-
8+ import requests
99from django import forms
1010from django .utils .translation import ugettext_lazy as _
1111from sentry .plugins .bases .issue import IssuePlugin
12+ from sentry .http import safe_urlopen , safe_urlread
1213from sentry .utils import json
1314
1415import sentry_github
15- import urllib2
1616
1717
1818class GitHubOptionsForm (forms .Form ):
@@ -55,7 +55,7 @@ def create_issue(self, request, group, form_data, **kwargs):
5555
5656 url = 'https://api.github.com/repos/%s/issues' % (repo ,)
5757
58- data = json . dumps ( {
58+ json_data = {
5959 "title" : form_data ['title' ],
6060 "body" : form_data ['description' ],
6161 # "assignee": form_data['asignee'],
@@ -64,35 +64,28 @@ def create_issue(self, request, group, form_data, **kwargs):
6464 # "Label1",
6565 # "Label2"
6666 # ]
67- })
68-
69- req = urllib2 .Request (url , data )
70- req .add_header ('User-Agent' , 'sentry-github/%s' % self .version )
71- req .add_header ('Authorization' , 'token %s' % auth .tokens ['access_token' ])
72- req .add_header ('Content-Type' , 'application/json' )
67+ }
7368
69+ req_headers = {
70+ 'Authorization' : 'token %s' % auth .tokens ['access_token' ],
71+ }
7472 try :
75- resp = urllib2 .urlopen (req )
76- except Exception , e :
77- if isinstance (e , urllib2 .HTTPError ):
78- msg = e .read ()
79- if 'application/json' in e .headers .get ('Content-Type' , '' ):
80- try :
81- msg = json .loads (msg )
82- msg = msg ['message' ]
83- except Exception :
84- # We failed, but we still want to report the original error
85- pass
86- else :
87- msg = unicode (e )
73+ req = safe_urlopen (url , json = json_data , headers = req_headers )
74+ body = safe_urlread (req )
75+ except requests .RequestException as e :
76+ msg = unicode (e )
8877 raise forms .ValidationError (_ ('Error communicating with GitHub: %s' ) % (msg ,))
8978
9079 try :
91- data = json .load (resp )
92- except Exception , e :
93- raise forms .ValidationError (_ ('Error decoding response from GitHub: %s' ) % (e ,))
80+ json_resp = json .loads (body )
81+ except ValueError as e :
82+ msg = unicode (e )
83+ raise forms .ValidationError (_ ('Error communicating with GitHub: %s' ) % (msg ,))
84+
85+ if req .status_code > 399 :
86+ raise forms .ValidationError (json_resp ['message' ])
9487
95- return data ['number' ]
88+ return json_resp ['number' ]
9689
9790 def get_issue_label (self , group , issue_id , ** kwargs ):
9891 return 'GH-%s' % issue_id
0 commit comments