本文整理汇总了Python中sanic.exceptions.SanicException方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.SanicException方法的具体用法?Python exceptions.SanicException怎么用?Python exceptions.SanicException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sanic.exceptions
的用法示例。
在下文中一共展示了exceptions.SanicException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_task
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def add_task(self, task):
"""Schedule a task to run later, after the loop has started.
Different from asyncio.ensure_future in that it does not
also return a future, and the actual ensure_future call
is delayed until before server start.
:param task: future, couroutine or awaitable
"""
try:
loop = self.loop # Will raise SanicError if loop is not started
self._loop_add_task(task, self, loop)
except SanicException:
self.listener("before_server_start")(
partial(self._loop_add_task, task)
)
# Decorator
示例2: index
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def index(request):
token = request.headers.get("X-Token")
if token not in G.config.tokens:
C["global"].update({"401": 1})
raise SanicException("Unauthorized", status_code=401)
try:
latitude = float(request.args.get("lat", default=None))
longitude = float(request.args.get("lon", default=None))
ghash = geohash.encode(latitude, longitude, G.config.precision)
except:
C["stats"][token[:6]].update({"400": 1})
raise SanicException("Bad Request", status_code=400)
try:
data = search(ghash)
if data is None:
C["stats"][token[:6]].update({"404": 1})
return jsonify(G.config.fallback)
else:
C["stats"][token[:6]].update({"200": 1})
return jsonify(data)
except:
C["stats"][token[:6]].update({"500": 1})
return jsonify(G.config.fallback)
示例3: reaction_add
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def reaction_add(cls, activity, local, **kwargs):
search_model = cls if local else Inbox
add_to = await search_model.find_one(
{"activity.object.id": activity.render['object']}
)
if add_to:
if add_to.reactions and add_to.reactions.get(activity.render['type']):
if add_to.reactions[activity.render['type']].get(activity.user.name):
raise SanicException(f'This post is already {activity.render["type"]}d', status_code=409)
else:
await cls.update_one(
{'_id': add_to.id},
{'$set': {f"reactions.{activity.render['type']}.{activity.user.name}":
activity.render['id'],
"updated": datetime.now()}}
)
await cls.save(activity, **kwargs)
示例4: reaction_undo
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def reaction_undo(cls, activity):
reaction_type = activity.render['object']['type']
local = check_origin(activity.render["object"]["object"], activity.render["actor"])
search_model = cls if local else Inbox
undo_from = await search_model.find_one(
{"activity.object.id": activity.render['object']['object']}
)
if undo_from:
if undo_from.reactions and undo_from.reactions.get(reaction_type) \
and undo_from.reactions[reaction_type].get(activity.user.name):
await cls.update_one(
{'_id': undo_from.id},
{'$unset': {f"reactions.{reaction_type}.{activity.user.name}": 1}}
)
else:
raise SanicException(f'This post is not {reaction_type}d', status_code=409)
await cls.delete(activity.render["object"]["id"])
示例5: default
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def default(self, request, exception):
if issubclass(type(exception), SanicException):
return json(
{'error': '{}'.format(exception)},
status=getattr(exception, 'status_code', 500),
headers=getattr(exception, 'headers', dict())
)
else:
print_exc()
if self.debug:
error = {'error': '{}'.format(exception)},
else:
error = {'error': 'internal server error'},
return json(
error,
status=getattr(exception, 'status_code', 500),
headers=getattr(exception, 'headers', dict())
)
示例6: default
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def default(self, request: Request, exception: Exception) -> HTTPResponse:
"""The default error handler for exceptions.
This handles errors which have no error handler assigned. Synse Server
does not register any other custom error handlers, so all exceptions
raised by the application will be caught and handled here.
"""
logger.info('creating error response for request', error=exception)
if isinstance(exception, SanicException):
return super(SynseErrorHandler, self).default(request, exception)
if not isinstance(exception, SynseError):
# Setting __cause__ on the exception is effectively the same
# as what happens when you `raise NewException() from old_exception
new = SynseError(str(exception))
new.__cause__ = exception
exception = new
return utils.http_json_response(
body=exception.make_response(),
status=exception.http_code,
)
示例7: default
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def default(self, request, exception):
# Here, we have access to the exception object
# and can do anything with it (log, send to external service, etc)
# Some exceptions are trivial and built into Sanic (404s, etc)
if not isinstance(exception, SanicException):
print(exception)
# Then, we must finish handling the exception by returning
# our response to the client
# For this we can just call the super class' default handler
return super().default(request, exception)
示例8: test
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def test(request):
# Here, something occurs which causes an unexpected exception
# This exception will flow to our custom handler.
raise SanicException('You Broke It!')
示例9: test
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def test(request):
raise SanicException('You Broke It!')
示例10: create_error
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def create_error(request):
raise SanicException("I was here and I don't like where I am")
示例11: test_app_loop_not_running
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def test_app_loop_not_running(app):
with pytest.raises(SanicException) as excinfo:
app.loop
assert str(excinfo.value) == (
"Loop can only be retrieved after the app has started "
"running. Not supported with `create_server` function"
)
示例12: loop
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def loop(self):
"""Synonymous with asyncio.get_event_loop().
Only supported when using the `app.run` method.
"""
if not self.is_running and self.asgi is False:
raise SanicException(
"Loop can only be retrieved after the app has started "
"running. Not supported with `create_server` function"
)
return get_event_loop()
# -------------------------------------------------------------------- #
# Registration
# -------------------------------------------------------------------- #
示例13: exception_response
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def exception_response(request, exception, debug):
status = 500
text = (
"The server encountered an internal error "
"and cannot complete your request."
)
headers = {}
if isinstance(exception, SanicException):
text = f"{exception}"
status = getattr(exception, "status_code", status)
headers = getattr(exception, "headers", headers)
elif debug:
text = f"{exception}"
status_text = STATUS_CODES.get(status, b"Error Occurred").decode()
title = escape(f"{status} — {status_text}")
text = escape(text)
if debug and not getattr(exception, "quiet", False):
return html(
f"<!DOCTYPE html><meta charset=UTF-8><title>{title}</title>"
f"<style>{TRACEBACK_STYLE}</style>\n"
f"<h1>⚠️ {title}</h1><p>{text}\n"
f"{_render_traceback_html(request, exception)}",
status=status,
)
# Keeping it minimal with trailing newline for pretty curl/console output
return html(
f"<!DOCTYPE html><meta charset=UTF-8><title>{title}</title>"
"<style>html { font-family: sans-serif }</style>\n"
f"<h1>⚠️ {title}</h1><p>{text}\n",
status=status,
headers=headers,
)
示例14: _make_request_processor
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def _make_request_processor(weak_request):
# type: (Callable[[], Request]) -> EventProcessor
def sanic_processor(event, hint):
# type: (Event, Optional[Hint]) -> Optional[Event]
try:
if hint and issubclass(hint["exc_info"][0], SanicException):
return None
except KeyError:
pass
request = weak_request()
if request is None:
return event
with capture_internal_exceptions():
extractor = SanicRequestExtractor(request)
extractor.extract_into_event(event)
request_info = event["request"]
urlparts = urlparse.urlsplit(request.url)
request_info["url"] = "%s://%s%s" % (
urlparts.scheme,
urlparts.netloc,
urlparts.path,
)
request_info["query_string"] = urlparts.query
request_info["method"] = request.method
request_info["env"] = {"REMOTE_ADDR": request.remote_addr}
request_info["headers"] = _filter_headers(dict(request.headers))
return event
return sanic_processor
示例15: create_handler
# 需要导入模块: from sanic import exceptions [as 别名]
# 或者: from sanic.exceptions import SanicException [as 别名]
def create_handler(transmute_func, context):
@wraps(transmute_func.raw_func)
async def handler(request, *args, **kwargs):
exc, result = None, None
try:
args, kwargs = await extract_params(request, context,
transmute_func)
result = await transmute_func.raw_func(*args, **kwargs)
except SanicException as se:
code = se.status_code or 400
exc = APIException(message=str(se), code=code)
except Exception as e:
exc = e
content_type = request.headers.get("Content-Type", DEFAULT_HTTP_CONTENT_TYPE)
response = transmute_func.process_result(
context, result, exc, content_type
)
return HTTPResponse(
status=response["code"],
content_type=response["content-type"],
headers=response["headers"],
body_bytes=response["body"],
)
handler.transmute_func = transmute_func
return handler