本文整理汇总了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))
示例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
示例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')
示例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'
示例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'
示例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'
示例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
示例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)
示例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
示例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