• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python http.build_session函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sentry.http.build_session函数的典型用法代码示例。如果您正苦于以下问题:Python build_session函数的具体用法?Python build_session怎么用?Python build_session使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了build_session函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:binlee1990,项目名称:sentry,代码行数:30,代码来源:provider.py


示例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))
开发者ID:richardmurri,项目名称:sentry-zulip,代码行数:34,代码来源:plugin.py


示例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})
开发者ID:Kayle009,项目名称:sentry,代码行数:30,代码来源:action_endpoint.py


示例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
开发者ID:mjumbewu,项目名称:sentry,代码行数:25,代码来源:integration.py


示例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
开发者ID:yogeshmangaj,项目名称:sentry,代码行数:26,代码来源:integration.py


示例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, ''))
开发者ID:getsentry,项目名称:sentry-plugins,代码行数:26,代码来源:plugin.py


示例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
开发者ID:NuttasitBoonwat,项目名称:sentry,代码行数:25,代码来源:errormapping.py


示例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)
开发者ID:getsentry,项目名称:sentry,代码行数:60,代码来源:client.py


示例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
开发者ID:alexandrul,项目名称:sentry,代码行数:29,代码来源:integration.py


示例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'])
开发者ID:justintung,项目名称:sentry,代码行数:33,代码来源:sync_docs.py


示例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"],
            }
        )
开发者ID:carriercomm,项目名称:sentry-1,代码行数:27,代码来源:project_platform_docs.py


示例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)
开发者ID:PXke,项目名称:sentry-jira,代码行数:33,代码来源:jira.py


示例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
开发者ID:Kayle009,项目名称:sentry,代码行数:58,代码来源:notify_action.py


示例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)
开发者ID:rev112,项目名称:sentry-redmine,代码行数:9,代码来源:client.py


示例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']
开发者ID:binlee1990,项目名称:sentry,代码行数:11,代码来源:integration.py


示例16: get_user_info

def get_user_info(access_token):
    session = http.build_session()
    resp = session.get(
        'https://api.github.com/user',
        params={'access_token': access_token},
        headers={'Accept': 'application/vnd.github.machine-man-preview+json'}
    )
    resp.raise_for_status()
    resp = resp.json()

    return resp
开发者ID:Kayle009,项目名称:sentry,代码行数:11,代码来源:provider.py


示例17: get_accounts

 def get_accounts(self, access_token, user_id):
     session = http.build_session()
     url = 'https://app.vssps.visualstudio.com/_apis/accounts?ownerId=%s&api-version=4.1' % user_id
     response = session.get(
         url,
         headers={
             'Content-Type': 'application/json',
             'Authorization': 'Bearer %s' % access_token,
         },
     )
     if response.status_code == 200:
         return response.json()
     return None
开发者ID:mjumbewu,项目名称:sentry,代码行数:13,代码来源:integration.py


示例18: get_user_info

def get_user_info(access_token, installation_data):
    session = http.build_session()
    resp = session.get(
        u'{}/api/v4/user'.format(installation_data['url']),
        headers={
            'Accept': 'application/json',
            'Authorization': 'Bearer %s' % access_token,
        },
        verify=installation_data['verify_ssl']
    )

    resp.raise_for_status()
    return resp.json()
开发者ID:alexandrul,项目名称:sentry,代码行数:13,代码来源:provider.py


示例19: get_base_url

 def get_base_url(cls, access_token, account_id):
     session = http.build_session()
     url = VstsIntegrationProvider.VSTS_ACCOUNT_LOOKUP_URL % account_id
     response = session.get(
         url,
         headers={
             'Content-Type': 'application/json',
             'Authorization': 'Bearer %s' % access_token,
         },
     )
     if response.status_code == 200:
         return response.json()['locationUrl']
     return None
开发者ID:mjumbewu,项目名称:sentry,代码行数:13,代码来源:integration.py


示例20: 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)
         return JIRAResponse(r.text, r.status_code)
     except Exception, e:
         logging.error("Error in request to %s: %s", url, e.message)
         return JIRAResponse("There was a problem reaching %s: %s" % (url, e.message), 500)
开发者ID:dannygeek,项目名称:sentry-jira,代码行数:14,代码来源:jira.py



注:本文中的sentry.http.build_session函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python http.safe_urlopen函数代码示例发布时间:2022-05-27
下一篇:
Python helpers.transform函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap