当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.ServiceUnavailable方法代码示例

本文整理汇总了Python中werkzeug.exceptions.ServiceUnavailable方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ServiceUnavailable方法的具体用法?Python exceptions.ServiceUnavailable怎么用?Python exceptions.ServiceUnavailable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在werkzeug.exceptions的用法示例。


在下文中一共展示了exceptions.ServiceUnavailable方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: submit_listens_to_listenbrainz

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def submit_listens_to_listenbrainz(listenbrainz_user, listens, listen_type=LISTEN_TYPE_IMPORT):
    """ Submit a batch of listens to ListenBrainz

    Args:
        listenbrainz_user (dict): the user whose listens are to be submitted
        listens (list): a list of listens to be submitted
        listen_type: the type of listen (single, import, playing_now)
    """
    username = listenbrainz_user['musicbrainz_id']
    retries = 10
    while retries >= 0:
        try:
            current_app.logger.debug('Submitting %d listens for user %s', len(listens), username)
            insert_payload(listens, listenbrainz_user, listen_type=listen_type)
            current_app.logger.debug('Submitted!')
            break
        except (InternalServerError, ServiceUnavailable) as e:
            retries -= 1
            current_app.logger.error('ISE while trying to import listens for %s: %s', username, str(e))
            if retries == 0:
                raise spotify.SpotifyListenBrainzError('ISE while trying to import listens: %s', str(e)) 
开发者ID:metabrainz,项目名称:listenbrainz-server,代码行数:23,代码来源:spotify_read_listens.py

示例2: _get_settings

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def _get_settings():
    from indico_ursh.plugin import UrshPlugin
    api_key = UrshPlugin.settings.get('api_key')
    api_host = UrshPlugin.settings.get('api_host')

    if not api_key or not api_host:
        raise ServiceUnavailable('Not configured')

    return api_key, api_host 
开发者ID:indico,项目名称:indico-plugins,代码行数:11,代码来源:util.py

示例3: test_bad_connection

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def test_bad_connection():
    with pytest.raises(ServiceUnavailable) as exc:
        network = _load_github_hooks(github_url='http://0.0.0.0:1234')
    assert (exc.value.description == 'Error reaching GitHub') 
开发者ID:nickfrostatx,项目名称:flask-hookserver,代码行数:6,代码来源:test_github.py

示例4: test_bad_structure

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def test_bad_structure(serving_app):
    @serving_app.route('/meta')
    def meta():
        return jsonify({})

    with pytest.raises(ServiceUnavailable) as exc:
        network = _load_github_hooks(github_url=serving_app.url)
    assert exc.value.description == 'Error reaching GitHub' 
开发者ID:nickfrostatx,项目名称:flask-hookserver,代码行数:10,代码来源:test_github.py

示例5: test_bad_status

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def test_bad_status(serving_app):
    @serving_app.route('/meta')
    def meta():
        return jsonify({'hooks': ['192.30.252.0/22']}), 403

    with pytest.raises(ServiceUnavailable) as exc:
        network = _load_github_hooks(github_url=serving_app.url)
    assert exc.value.description == 'Error reaching GitHub' 
开发者ID:nickfrostatx,项目名称:flask-hookserver,代码行数:10,代码来源:test_github.py

示例6: test_bad_headers

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def test_bad_headers(serving_app):
    @serving_app.route('/meta')
    def meta():
        headers = {
            'X-RateLimit-Remaining': 0,
        }
        return jsonify({'hooks': ['192.30.252.0/22']}), 403, headers

    with pytest.raises(ServiceUnavailable) as exc:
        network = _load_github_hooks(github_url=serving_app.url)
    assert exc.value.description == 'Error reaching GitHub' 
开发者ID:nickfrostatx,项目名称:flask-hookserver,代码行数:13,代码来源:test_github.py

示例7: _load_github_hooks

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def _load_github_hooks(github_url='https://api.github.com'):
    """Request GitHub's IP block from their API.

    Return the IP network.

    If we detect a rate-limit error, raise an error message stating when
    the rate limit will reset.

    If something else goes wrong, raise a generic 503.
    """
    try:
        resp = requests.get(github_url + '/meta')
        if resp.status_code == 200:
            return resp.json()['hooks']
        else:
            if resp.headers.get('X-RateLimit-Remaining') == '0':
                reset_ts = int(resp.headers['X-RateLimit-Reset'])
                reset_string = time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                             time.gmtime(reset_ts))
                raise ServiceUnavailable('Rate limited from GitHub until ' +
                                         reset_string)
            else:
                raise ServiceUnavailable('Error reaching GitHub')
    except (KeyError, ValueError, requests.exceptions.ConnectionError):
        raise ServiceUnavailable('Error reaching GitHub')


# So we don't get rate limited 
开发者ID:nickfrostatx,项目名称:flask-hookserver,代码行数:30,代码来源:flask_hookserver.py

示例8: test_aborter

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def test_aborter(self):
        abort = exceptions.abort
        self.assert_raises(exceptions.BadRequest, abort, 400)
        self.assert_raises(exceptions.Unauthorized, abort, 401)
        self.assert_raises(exceptions.Forbidden, abort, 403)
        self.assert_raises(exceptions.NotFound, abort, 404)
        self.assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD'])
        self.assert_raises(exceptions.NotAcceptable, abort, 406)
        self.assert_raises(exceptions.RequestTimeout, abort, 408)
        self.assert_raises(exceptions.Gone, abort, 410)
        self.assert_raises(exceptions.LengthRequired, abort, 411)
        self.assert_raises(exceptions.PreconditionFailed, abort, 412)
        self.assert_raises(exceptions.RequestEntityTooLarge, abort, 413)
        self.assert_raises(exceptions.RequestURITooLarge, abort, 414)
        self.assert_raises(exceptions.UnsupportedMediaType, abort, 415)
        self.assert_raises(exceptions.UnprocessableEntity, abort, 422)
        self.assert_raises(exceptions.InternalServerError, abort, 500)
        self.assert_raises(exceptions.NotImplemented, abort, 501)
        self.assert_raises(exceptions.BadGateway, abort, 502)
        self.assert_raises(exceptions.ServiceUnavailable, abort, 503)

        myabort = exceptions.Aborter({1: exceptions.NotFound})
        self.assert_raises(LookupError, myabort, 404)
        self.assert_raises(exceptions.NotFound, myabort, 1)

        myabort = exceptions.Aborter(extra={1: exceptions.NotFound})
        self.assert_raises(exceptions.NotFound, myabort, 404)
        self.assert_raises(exceptions.NotFound, myabort, 1) 
开发者ID:GeekTrainer,项目名称:Flask,代码行数:30,代码来源:exceptions.py

示例9: add

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def add():
    """Endpoint for adding new mappings to Spotify.

    Only connection to albums on Spotify is supported right now.

    JSON parameters:
        user: UUID of the user who is adding new mapping.
        mbid: MusicBrainz ID of an entity that is being connected.
        spotify_uri: Spotify URI of an album that is being connected.
    """
    user = request.json["user"]
    if not validate_uuid(user):
        raise BadRequest("Incorrect user ID (UUID).")

    mbid = request.json["mbid"]
    if not validate_uuid(mbid):
        raise BadRequest("Incorrect MBID (UUID).")

    uri = request.json["spotify_uri"]
    if not uri.startswith("spotify:album:"):
        raise BadRequest("Incorrect Spotify URI. Only albums are supported right now.")

    conn = psycopg2.connect(**current_app.config["PG_INFO"])
    cur = conn.cursor()

    try:
        # Checking if mapping is already created
        cur.execute("SELECT id FROM mapping "
                    "WHERE is_deleted = FALSE "
                    "AND mbid = %s "
                    "AND spotify_uri = %s", (mbid, uri))
        if not cur.rowcount:
            # and if it's not, adding it
            cur.execute("INSERT INTO mapping (mbid, spotify_uri, cb_user, is_deleted)"
                        "VALUES (%s, %s, %s, FALSE)",
                        (mbid, uri, user))
            conn.commit()
    except psycopg2.IntegrityError as e:
        raise BadRequest(str(e))
    except psycopg2.OperationalError as e:
        raise ServiceUnavailable(str(e))

    response = Response()
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response 
开发者ID:metabrainz,项目名称:mbspotify,代码行数:47,代码来源:views.py

示例10: invoke

# 需要导入模块: from werkzeug import exceptions [as 别名]
# 或者: from werkzeug.exceptions import ServiceUnavailable [as 别名]
def invoke(self, stub, method_name, request, metadata, retry=1):
        """
        Invoke a gRPC call to the remote server and return the response.
        :param stub: Reference to the *_pb2 service stub
        :param method_name: The method name inside the service stub
        :param request: The request protobuf message
        :param metadata: [(str, str), (str, str), ...]
        :return: The response protobuf message and returned trailing metadata
        """

        if not self.connected:
            raise ServiceUnavailable()

        try:
            method = getattr(stub(self.channel), method_name)
            response, rendezvous = method.with_call(request, metadata=metadata)
            returnValue((response, rendezvous.trailing_metadata()))

        except grpc._channel._Rendezvous, e:
            code = e.code()
            if code == grpc.StatusCode.UNAVAILABLE:
                e = ServiceUnavailable()

                if self.connected:
                    self.connected = False
                    yield self.connect()
                    if retry > 0:
                        response = yield self.invoke(stub, method_name,
                                                     request, metadata,
                                                     retry=retry - 1)
                        returnValue(response)

            elif code in (
                    grpc.StatusCode.NOT_FOUND,
                    grpc.StatusCode.INVALID_ARGUMENT,
                    grpc.StatusCode.ALREADY_EXISTS):

                pass  # don't log error, these occur naturally

            else:
                log.exception(e)

            raise e

    # Below is an adaptation of Google's MessageToDict() which includes
    # protobuf options extensions 
开发者ID:opencord,项目名称:voltha,代码行数:48,代码来源:grpc_client.py


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