Python sanic.exceptions.SanicException() Examples
The following are 19
code examples of sanic.exceptions.SanicException().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sanic.exceptions
, or try the search function
.
Example #1
Source File: sapp.py From geo-br with GNU General Public License v3.0 | 6 votes |
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)
Example #2
Source File: errors.py From synse-server with GNU General Public License v3.0 | 6 votes |
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, )
Example #3
Source File: logging.py From pubgate with BSD 3-Clause "New" or "Revised" License | 6 votes |
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()) )
Example #4
Source File: boxes.py From pubgate with BSD 3-Clause "New" or "Revised" License | 6 votes |
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"])
Example #5
Source File: boxes.py From pubgate with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #6
Source File: app.py From sanic with MIT License | 6 votes |
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
Example #7
Source File: app.py From sanic with MIT License | 5 votes |
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 # -------------------------------------------------------------------- #
Example #8
Source File: errorpages.py From sanic with MIT License | 5 votes |
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, )
Example #9
Source File: sanic.py From sentry-python with BSD 2-Clause "Simplified" License | 5 votes |
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
Example #10
Source File: exception_monitoring.py From sanic with MIT License | 5 votes |
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)
Example #11
Source File: handler.py From sanic-transmute with MIT License | 5 votes |
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
Example #12
Source File: activity.py From pubgate with BSD 3-Clause "New" or "Revised" License | 5 votes |
def save(self, **kwargs): filters = self.user.follow_filter(Inbox) filters["activity.object.object"] = self.render["object"] followed = await Inbox.find_one(filters) if followed: raise SanicException('This user is already followed', status_code=409) await Outbox.save(self, **kwargs)
Example #13
Source File: test_app.py From sanic with MIT License | 5 votes |
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" )
Example #14
Source File: rollbar_example.py From sanic with MIT License | 5 votes |
def create_error(request): raise SanicException("I was here and I don't like where I am")
Example #15
Source File: boxes.py From pubgate with BSD 3-Clause "New" or "Revised" License | 5 votes |
def save(cls, user, activity): exists = await cls.find_one( {"activity.id": activity["id"]} ) if exists: if user.name in exists['users']: raise SanicException('Object with this ID already delivered to user', status_code=409) else: users = exists['users'] users.append(user.name) await cls.update_one( {'_id': exists.id}, {'$set': {"users": users, "updated": datetime.now()}} ) await cls.cache.clear() else: # TODO validate actor and activity pg_id = random_object_id() # TODO how to get single object from inbox # activity = copy.deepcopy(activity) # activity["pg_id"] = pg_id await cls.insert_one({ "_id": pg_id, "users": [user.name], "activity": activity, "label": make_label(activity), "deleted": False, "first_user": user.name, "created": datetime.now() }) return True
Example #16
Source File: raygun_example.py From sanic with MIT License | 5 votes |
def test(request): raise SanicException('You Broke It!')
Example #17
Source File: exception_monitoring.py From annotated-py-projects with MIT License | 5 votes |
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 issubclass(type(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(self, request, exception)
Example #18
Source File: exception_monitoring.py From sanic with MIT License | 5 votes |
def test(request): # Here, something occurs which causes an unexpected exception # This exception will flow to our custom handler. raise SanicException('You Broke It!')
Example #19
Source File: extension.py From sanic-cors with MIT License | 4 votes |
def wrapper(cls, f, ctx, req, e): opts = ctx.options log = ctx.log # get response from the original handler if (req is not None and SANIC_19_12_0 <= SANIC_VERSION and isinstance(e, MethodNotSupported) and req.method == "OPTIONS" and opts.get('automatic_options', True)): # A very specific set of requirments to trigger this kind of # automatic-options resp resp = response.HTTPResponse() else: do_await = iscoroutinefunction(f) resp = f(req, e) if do_await: log(logging.DEBUG, "Found an async Exception handler response. " "Cannot apply CORS to it. Passing it on.") return resp # SanicExceptions are equiv to Flask Aborts, # always apply CORS to them. if (req is not None and resp is not None) and \ (isinstance(e, exceptions.SanicException) or opts.get('intercept_exceptions', True)): try: cls._apply_cors_to_exception(ctx, req, resp) except AttributeError: # not sure why certain exceptions doesn't have # an accompanying request pass if req is None: return resp # These exceptions have normal CORS middleware applied automatically. # So set a flag to skip our manual application of the middleware. try: request_context = ctx.request[id(req)] except (LookupError, AttributeError): # On Sanic 19.12.0, a NotFound error can be thrown _before_ # the request_context is set up. This is a fallback routine: if SANIC_19_12_0 <= SANIC_VERSION and \ isinstance(e, (NotFound, MethodNotSupported)): # On sanic 19.9.0+ request is a dict, so we can add our # flag directly to it. request_context = req.ctx else: log(logging.DEBUG, "Cannot find the request context. Is request started? " "Is request already finished?") request_context = None if request_context is not None: setattr(request_context, SANIC_CORS_SKIP_RESPONSE_MIDDLEWARE, "1") return resp