本文整理汇总了Python中sentry.http.build_session函数的典型用法代码示例。如果您正苦于以下问题:Python build_session函数的具体用法?Python build_session怎么用?Python build_session使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了build_session函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_user_info
def get_user_info(access_token):
session = http.build_session()
resp = session.get(
'https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=1.0',
headers={
'Accept': 'application/json',
'Authorization': 'bearer %s' % access_token,
},
)
resp.raise_for_status()
user = resp.json()
resp = session.get(
'https://app.vssps.visualstudio.com/_apis/connectionData/',
headers={
'Accept': 'application/json',
'Authorization': 'bearer %s' % access_token,
},
)
resp.raise_for_status()
# NOTE (from Microsoft PM):
# The "descriptor" is the universal identifier for a given user and is consistent across
# all VSTS accounts (organizations). The "id" field for the same user can be different for
# the same user in different places, so the "descriptor" is the best identifier for a user.
# This is returned in most/all of the VSTS REST APIs at this point (except for the
# profiles/me API above). To get the current user's descriptor, we call the "connection data"
# REST API (this assumes we are authenticating with an access token issued to the user).
# We will also see descriptors returned for every user in the "Get users" (Graph) REST API.
user['id'] = resp.json()['authenticatedUser']['subjectDescriptor']
return user
示例2: notify
def notify(self, notification):
event = notification.event
group = event.group
project = group.project
if not self.is_configured(project):
return
apiurl = self.get_option('apiurl', project)
username = self.get_option('username', project).strip().encode('utf-8')
apikey = self.get_option('apikey', project).encode('utf-8')
stream = self.get_option('stream', project).strip().encode('utf-8')
level = group.get_level_display()
title = event.message_short.encode('utf-8')
project_name = get_project_full_name(project).encode('utf-8')
values = {
'type': 'stream',
'to': stream,
'subject': title,
'content': "[%s] **%s** %s [view](%s)" % (
level.upper(), project_name, title, group.get_absolute_url()
)
}
# Apparently we've stored some bad data from before we used `URLField`.
apiurl = apiurl.strip(' ')
session = build_session()
return session.request(method='POST',
url=apiurl,
data=values,
auth=(username, apikey))
示例3: open_resolve_dialog
def open_resolve_dialog(self, data, group, integration):
# XXX(epurkhiser): In order to update the original message we have to
# keep track of the response_url in the callback_id. Definitely hacky,
# but seems like there's no other solutions [1]:
#
# [1]: https://stackoverflow.com/questions/46629852/update-a-bot-message-after-responding-to-a-slack-dialog#comment80795670_46629852
callback_id = json.dumps({
'issue': group.id,
'orig_response_url': data['response_url'],
'is_message': self.is_message(data),
})
dialog = {
'callback_id': callback_id,
'title': u'Resolve Issue',
'submit_label': 'Resolve',
'elements': [RESOLVE_SELECTOR],
}
payload = {
'dialog': json.dumps(dialog),
'trigger_id': data['trigger_id'],
'token': integration.metadata['access_token'],
}
session = http.build_session()
req = session.post('https://slack.com/api/dialog.open', data=payload)
resp = req.json()
if not resp.get('ok'):
logger.error('slack.action.response-error', extra={'response': resp})
示例4: create_webhook
def create_webhook(self, base_url, access_token, verify_ssl):
webhook_secret = generate_token()
session = http.build_session()
uri = GitLabApiClientPath.build_api_url(
base_url=base_url,
path=GitLabApiClientPath.hooks
)
resp = session.post(
uri,
headers={
'Accept': 'application/json',
'Authorization': 'Bearer %s' % access_token,
},
verify=verify_ssl,
data={
'url': absolute_uri('/extensions/gitlab/webhooks/'),
'token': webhook_secret,
'merge_requests_events': True,
'push_events': True,
},
)
resp.raise_for_status()
return resp.json()['id'], webhook_secret
示例5: get_installation_info
def get_installation_info(self, access_token, installation_id):
session = http.build_session()
resp = session.get(
'https://api.github.com/app/installations/%s' % installation_id,
headers={
'Authorization': 'Bearer %s' % get_jwt(),
'Accept': 'application/vnd.github.machine-man-preview+json',
}
)
resp.raise_for_status()
installation_resp = resp.json()
resp = session.get(
'https://api.github.com/user/installations',
params={'access_token': access_token},
headers={'Accept': 'application/vnd.github.machine-man-preview+json'}
)
resp.raise_for_status()
user_installations_resp = resp.json()
# verify that user actually has access to the installation
for installation in user_installations_resp['installations']:
if installation['id'] == installation_resp['id']:
return installation_resp
return None
示例6: forward_event
def forward_event(self, event, payload, **kwargs):
# TODO(dcramer): we currently only support authenticated events, as the
# value of anonymous errors/crashes/etc is much less meaningful in the
# context of Segment
# we currently only support errors
if event.get_event_type() != 'error':
return
# we avoid instantiating interfaces here as they're only going to be
# used if there's a User present
user_interface = event.data.get('sentry.interfaces.User')
if not user_interface:
return
user_id = user_interface.get('id')
if not user_id:
return
write_key = self.get_option('write_key', event.project)
if not write_key:
return
session = http.build_session()
session.post(self.endpoint, json=payload, auth=(write_key, ''))
示例7: load_mapping
def load_mapping(self):
key = 'javascript.errormapping:%s' % self.vendor
mapping = cache.get(key)
cached_rv = None
if mapping is not None:
ts, cached_rv = json.loads(mapping)
if not is_expired(ts):
return cached_rv
try:
http_session = http.build_session()
response = http_session.get(
self.mapping_url,
allow_redirects=True,
timeout=settings.SENTRY_SOURCE_FETCH_TIMEOUT,
)
# Make sure we only get a 2xx to prevent caching bad data
response.raise_for_status()
data = response.json()
cache.set(key, json.dumps([time.time(), data]), HARD_TIMEOUT)
except Exception:
if cached_rv is None:
raise
return cached_rv
return data
示例8: _request
def _request(self, method, path, headers=None, data=None, params=None,
auth=None, json=True, allow_text=None, allow_redirects=None,
timeout=None):
if allow_text is None:
allow_text = self.allow_text
if allow_redirects is None:
allow_redirects = self.allow_redirects
if allow_redirects is None: # is still None
allow_redirects = method.upper() == 'GET'
if timeout is None:
timeout = 30
full_url = self.build_url(path)
host = urlparse(full_url).netloc
session = build_session()
try:
resp = getattr(session, method.lower())(
url=full_url,
headers=headers,
json=data if json else None,
data=data if not json else None,
params=params,
auth=auth,
verify=self.verify_ssl,
allow_redirects=allow_redirects,
timeout=timeout,
)
resp.raise_for_status()
except ConnectionError as e:
metrics.incr('integrations.http_response', tags={
'host': host,
'status': 'connection_error'
})
raise ApiHostError.from_exception(e)
except Timeout as e:
metrics.incr('integrations.http_response', tags={
'host': host,
'status': 'timeout'
})
raise ApiTimeoutError.from_exception(e)
except HTTPError as e:
resp = e.response
if resp is None:
track_response_code(host, 'unknown')
self.logger.exception('request.error', extra={
'url': full_url,
})
raise ApiError('Internal Error')
track_response_code(host, resp.status_code)
raise ApiError.from_response(resp)
track_response_code(host, resp.status_code)
if resp.status_code == 204:
return {}
return BaseApiResponse.from_response(resp, allow_text=allow_text)
示例9: get_installation_info
def get_installation_info(self, installation_data, access_token, installation_id):
session = http.build_session()
resp = session.get(
u'https://{}/api/v3/app/installations/{}'.format(
installation_data['url'], installation_id),
headers={
'Authorization': 'Bearer %s' % get_jwt(github_id=installation_data['id'], github_private_key=installation_data['private_key']),
'Accept': 'application/vnd.github.machine-man-preview+json',
},
verify=installation_data['verify_ssl']
)
resp.raise_for_status()
installation_resp = resp.json()
resp = session.get(
u'https://{}/api/v3/user/installations'.format(installation_data['url']),
params={'access_token': access_token},
headers={'Accept': 'application/vnd.github.machine-man-preview+json'},
verify=installation_data['verify_ssl']
)
resp.raise_for_status()
user_installations_resp = resp.json()
# verify that user actually has access to the installation
for installation in user_installations_resp['installations']:
if installation['id'] == installation_resp['id']:
return installation_resp
return None
示例10: sync_docs
def sync_docs():
from sentry import http, options
session = http.build_session()
logger.info('Syncing documentation (platform index)')
data = session.get(BASE_URL.format('_index.json')).json()
platform_list = []
for platform_id, integrations in data['platforms'].iteritems():
platform_list.append({
'id': platform_id,
'name': integrations['_self']['name'],
'integrations': [
{
'id': get_integration_id(platform_id, i_id),
'name': i_data['name'],
'type': i_data['type'],
'link': i_data['doc_link'],
} for i_id, i_data in sorted(
integrations.iteritems(),
key=lambda x: x[1]['name']
)
],
})
platform_list.sort(key=lambda x: x['name'])
options.set('sentry:docs', {'platforms': platform_list})
for platform_id, platform_data in data['platforms'].iteritems():
for integration_id, integration in platform_data.iteritems():
logger.info('Syncing documentation for %s integration', integration_id)
sync_integration(platform_id, integration_id, integration['details'])
示例11: get
def get(self, request, project, platform):
if platform not in PLATFORMS:
raise ResourceDoesNotExist
cache_key = "docs:{}".format(platform)
result = cache.get(cache_key)
if result is None:
session = http.build_session()
result = session.get(DOC_URL.format(platform=platform)).json()
cache.set(cache_key, result, 3600)
try:
project_key = ProjectKey.objects.filter(
project=project, roles=ProjectKey.roles.store, status=ProjectKeyStatus.ACTIVE
)[0]
except IndexError:
project_key = None
return Response(
{
"name": result["name"],
"html": replace_keys(result["body"], project_key),
"sdk": result["client_lib"],
"isFramework": result["is_framework"],
"link": result["doc_link"],
}
)
示例12: make_request
def make_request(self, method, url, payload=None):
if url[:4] != "http":
url = self.instance_url + url
auth = self.username, self.password
session = build_session()
try:
if method == 'get':
r = session.get(
url, params=payload, auth=auth,
verify=False, timeout=self.HTTP_TIMEOUT)
else:
r = session.post(
url, json=payload, auth=auth,
verify=False, timeout=self.HTTP_TIMEOUT)
except ConnectionError as e:
raise JIRAError(unicode(e))
except RequestException as e:
resp = e.response
if not resp:
raise JIRAError('Internal Error')
if resp.status_code == 401:
raise JIRAUnauthorized.from_response(resp)
raise JIRAError.from_response(resp)
except Exception as e:
logging.error('Error in request to %s: %s', url, e.message[:128],
exc_info=True)
raise JIRAError('Internal error', 500)
if r.status_code == 401:
raise JIRAUnauthorized.from_response(r)
elif r.status_code < 200 or r.status_code >= 300:
raise JIRAError.from_response(r)
return JIRAResponse.from_response(r)
示例13: get_channel_id
def get_channel_id(self, integration_id, name):
try:
integration = Integration.objects.get(
provider='slack',
organizations=self.project.organization,
id=integration_id,
)
except Integration.DoesNotExist:
return None
session = http.build_session()
token_payload = {
'token': integration.metadata['access_token'],
}
# Look for channel ID
channels_payload = dict(token_payload, **{
'exclude_archived': False,
'exclude_members': True,
})
resp = session.get('https://slack.com/api/channels.list', params=channels_payload)
resp = resp.json()
if not resp.get('ok'):
self.logger.info('rule.slack.channel_list_failed', extra={'error': resp.get('error')})
return None
channel_id = {c['name']: c['id'] for c in resp['channels']}.get(name)
if channel_id:
return (CHANNEL_PREFIX, channel_id)
# Channel may be private
resp = session.get('https://slack.com/api/groups.list', params=channels_payload)
resp = resp.json()
if not resp.get('ok'):
self.logger.info('rule.slack.group_list_failed', extra={'error': resp.get('error')})
return None
group_id = {c['name']: c['id'] for c in resp['groups']}.get(name)
if group_id:
return (CHANNEL_PREFIX, group_id)
# Channel may actually be a user
resp = session.get('https://slack.com/api/users.list', params=token_payload)
resp = resp.json()
if not resp.get('ok'):
self.logger.info('rule.slack.user_list_failed', extra={'error': resp.get('error')})
return None
member_id = {c['name']: c['id'] for c in resp['members']}.get(name)
if member_id:
return (MEMBER_PREFIX, member_id)
return None
示例14: request
def request(self, method, path, data=None):
headers = {
'X-Redmine-API-Key': self.key,
'Content-Type': "application/json",
}
url = '{}{}'.format(self.host, path)
session = http.build_session()
req = getattr(session, method.lower())(url, json=data, headers=headers)
return json.loads(req.text)
示例15: get_team_info
def get_team_info(self, access_token):
payload = {
'token': access_token,
}
session = http.build_session()
resp = session.get('https://slack.com/api/team.info', params=payload)
resp.raise_for_status()
resp = resp.json()
return resp['team']