本文整理汇总了Python中sentry.http.safe_urlopen函数的典型用法代码示例。如果您正苦于以下问题:Python safe_urlopen函数的具体用法?Python safe_urlopen怎么用?Python safe_urlopen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了safe_urlopen函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_service_hook
def process_service_hook(servicehook_id, event, **kwargs):
from sentry import tsdb
from sentry.models import ServiceHook
try:
servicehook = ServiceHook.objects.get(id=servicehook_id)
except ServiceHook.DoesNotExist:
return
tsdb.incr(tsdb.models.servicehook_fired, servicehook.id)
if servicehook.version == 0:
payload = get_payload_v0(event)
else:
raise NotImplementedError
body = json.dumps(payload)
headers = {
'Content-Type': 'application/json',
'X-ServiceHook-Timestamp': six.text_type(int(time())),
'X-ServiceHook-GUID': servicehook.guid,
'X-ServiceHook-Signature': servicehook.build_signature(body),
}
safe_urlopen(
url=servicehook.url,
data=body,
headers=headers,
timeout=5,
verify_ssl=False,
)
示例2: process_resource_change
def process_resource_change(action, sender, instance_id, *args, **kwargs):
model = None
name = None
# Previous method signature.
if inspect.isclass(sender):
model = sender
else:
model = TYPES[sender]
name = RESOURCE_RENAMES.get(model.__name__, model.__name__.lower())
# We may run into a race condition where this task executes before the
# transaction that creates the Group has committed.
try:
instance = model.objects.get(id=instance_id)
except model.DoesNotExist as e:
# Explicitly requeue the task, so we don't report this to Sentry until
# we hit the max number of retries.
return current.retry(exc=e)
event = '{}.{}'.format(name, action)
if event not in ALLOWED_EVENTS:
return
project = None
if isinstance(instance, Group):
project = instance.project
if not project:
return
servicehooks = ServiceHook.objects.filter(
project_id=project.id,
)
for servicehook in filter(lambda s: event in s.events, servicehooks):
# For now, these ``post_save`` callbacks are only valid for service
# hooks created by a Sentry App.
if not servicehook.created_by_sentry_app:
continue
request_data = AppPlatformEvent(
resource=name,
action=action,
install=SentryAppInstallation.objects.get(id=servicehook.actor_id),
data=serialize(instance),
)
safe_urlopen(
url=servicehook.url,
data=request_data.body,
headers=request_data.headers,
timeout=5,
)
示例3: notify_users
def notify_users(self, group, event, **kwargs):
project = group.project
body = 'Sentry [{0}] {1}: {2}'.format(
project.name.encode('utf-8'),
event.get_level_display().upper().encode('utf-8'),
event.error().encode('utf-8').splitlines()[0]
)
body = body[:MAX_SMS_LENGTH]
account_sid = self.get_option('account_sid', project)
auth_token = self.get_option('auth_token', project)
sms_from = clean_phone(self.get_option('sms_from', project))
endpoint = twilio_sms_endpoint.format(account_sid)
sms_to = self.get_option('sms_to', project)
if not sms_to:
return
sms_to = split_sms_to(sms_to)
headers = {
'Authorization': basic_auth(account_sid, auth_token),
}
errors = []
for phone in sms_to:
if not phone:
continue
try:
phone = clean_phone(phone)
http.safe_urlopen(
endpoint,
method='POST',
headers=headers,
data={
'From': sms_from,
'To': phone,
'Body': body,
},
).raise_for_status()
except Exception as e:
errors.append(e)
if errors:
if len(errors) == 1:
raise errors[0]
# TODO: multi-exception
raise Exception(errors)
示例4: _make_request
def _make_request(self):
req = safe_urlopen(
url=self._build_url(),
headers=self._build_headers(),
method='POST',
data=self.body,
)
try:
body = safe_urlread(req)
response = json.loads(body)
except Exception:
logger.info(
'issue-link-requester.error',
extra={
'sentry_app': self.sentry_app.slug,
'install': self.install.uuid,
'project': self.group.project.slug,
'group': self.group.id,
'uri': self.uri,
}
)
response = {}
if not self._validate_response(response):
raise APIError()
return response
示例5: send_webhook
def send_webhook(self, url, data):
return safe_urlopen(
url=url,
data=data,
timeout=self.timeout,
user_agent=self.user_agent,
)
示例6: send_webhook
def send_webhook(self, url, payload):
return safe_urlopen(
url=url,
json=payload,
timeout=self.timeout,
verify_ssl=False,
)
示例7: github_request
def github_request(self, request, url, **kwargs):
"""
Make a GitHub request on behalf of the logged in user. Return JSON
response on success or raise forms.ValidationError on any exception
"""
auth = self.get_auth_for_user(user=request.user)
if auth is None:
raise forms.ValidationError(_("You have not yet associated GitHub with your account."))
headers = kwargs.pop("headers", None) or {}
headers["Authorization"] = "token %s" % auth.tokens["access_token"]
try:
req = safe_urlopen(url, headers=headers, **kwargs)
body = safe_urlread(req)
except requests.RequestException as e:
msg = unicode(e)
raise forms.ValidationError(_("Error communicating with GitHub: %s") % (msg,))
try:
json_resp = json.loads(body)
except ValueError as e:
msg = unicode(e)
raise forms.ValidationError(_("Error communicating with GitHub: %s") % (msg,))
if req.status_code > 399:
raise forms.ValidationError(json_resp["message"])
return json_resp
示例8: _make_request
def _make_request(self):
try:
body = safe_urlread(
safe_urlopen(
url=self._build_url(),
headers=self._build_headers(),
)
)
response = json.loads(body)
except Exception as e:
logger.info(
'select-requester.error',
extra={
'sentry_app': self.sentry_app.slug,
'install': self.install.uuid,
'project': self.project and self.project.slug,
'uri': self.uri,
'error_message': e.message,
}
)
response = {}
if not self._validate_response(response):
raise APIError()
return self._format_response(response)
示例9: notify_users
def notify_users(self, group, event, fail_silently=False):
if not self.is_configured(group.project):
return
api_key = self.get_option('api_key', group.project)
recipients = self.get_option('recipients', group.project)
alert_url = self.get_option('alert_url', group.project)
message = getattr(group, 'message_short', group.message).encode('utf-8')
payload = {
'apiKey': api_key,
'message': message,
'source': 'Sentry',
'details': self.get_group_data(group, event)
}
if recipients:
payload['recipients'] = recipients
req = http.safe_urlopen(alert_url, json=payload)
resp = req.json()
if resp.get('status') != 'successful':
raise Exception('Unsuccessful response from OpsGenie: %s' % resp)
示例10: dispatch
def dispatch(self, request, helper):
access_token = helper.fetch_state('data')['access_token']
req = safe_urlopen('{0}?{1}&alt=json'.format(
USER_DETAILS_ENDPOINT,
urlencode({
'access_token': access_token,
})
))
body = safe_urlread(req)
data = json.loads(body)
if not data.get('data'):
logger.error('Invalid response: %s' % body)
return helper.error(ERR_INVALID_RESPONSE)
if not data.get('data').get('email'):
logger.error('Invalid response: %s' % body)
return helper.error(ERR_INVALID_RESPONSE)
domain = extract_domain(data.get('data').get('email'))
if domain in DOMAIN_BLOCKLIST:
return helper.error(ERR_INVALID_DOMAIN % (domain,))
if self.domain and self.domain != domain:
return helper.error(ERR_INVALID_DOMAIN % (domain,))
helper.bind_state('domain', domain)
helper.bind_state('user', data.get('data'))
return helper.next_step()
示例11: refresh_identity
def refresh_identity(self, auth_identity):
refresh_token = auth_identity.data.get("refresh_token")
if not refresh_token:
raise IdentityNotValid("Missing refresh token")
data = self.get_refresh_token_params(refresh_token=refresh_token)
req = safe_urlopen(self.get_refresh_token_url(), data=data)
try:
body = safe_urlread(req)
payload = json.loads(body)
except Exception:
payload = {}
error = payload.get("error", "unknown_error")
error_description = payload.get("error_description", "no description available")
formatted_error = "HTTP {} ({}): {}".format(req.status_code, error, error_description)
if req.status_code == 401:
raise IdentityNotValid(formatted_error)
if req.status_code == 400:
# this may not be common, but at the very least Google will return
# an invalid grant when a user is suspended
if error == "invalid_grant":
raise IdentityNotValid(formatted_error)
if req.status_code != 200:
raise Exception(formatted_error)
auth_identity.data.update(self.get_oauth_data(payload))
auth_identity.update(data=auth_identity.data)
示例12: exchange_token
def exchange_token(self, request, pipeline, code):
# TODO: this needs the auth yet
data = self.get_token_params(
code=code,
redirect_uri=absolute_uri(pipeline.redirect_url()),
)
verify_ssl = pipeline.config.get('verify_ssl', True)
try:
req = safe_urlopen(self.access_token_url, data=data, verify_ssl=verify_ssl)
body = safe_urlread(req)
if req.headers.get('Content-Type', '').startswith('application/x-www-form-urlencoded'):
return dict(parse_qsl(body))
return json.loads(body)
except SSLError:
logger.info('identity.oauth2.ssl-error', extra={
'url': self.access_token_url,
'verify_ssl': verify_ssl,
})
url = self.access_token_url
return {
'error': 'Could not verify SSL certificate',
'error_description': u'Ensure that {} has a valid SSL certificate'.format(url)
}
except JSONDecodeError:
logger.info('identity.oauth2.json-error', extra={
'url': self.access_token_url,
})
return {
'error': 'Could not decode a JSON Response',
'error_description': u'We were not able to parse a JSON response, please try again.'
}
示例13: exchange_token
def exchange_token(self, request, helper, code):
# TODO: this needs the auth yet
data = self.get_token_params(code=code, redirect_uri=absolute_uri(helper.get_redirect_url()))
req = safe_urlopen(self.access_token_url, data=data)
body = safe_urlread(req)
return json.loads(body)
示例14: send_webhook
def send_webhook(self, url, data):
return safe_urlopen(
url=url,
data=data,
timeout=self.timeout,
user_agent=self.user_agent,
headers=(('Accept-Encoding', 'gzip'), ('Content-type', 'application/json')),
)
示例15: exchange_token
def exchange_token(self, request, helper, code):
# TODO: this needs the auth yet
data = self.get_token_params(code=code, redirect_uri=absolute_uri(helper.get_redirect_url()))
req = safe_urlopen(self.access_token_url, data=data)
body = safe_urlread(req)
if req.headers["Content-Type"].startswith("application/x-www-form-urlencoded"):
return dict(parse_qsl(body))
return json.loads(body)