Example #1
0
def test_error_in_errorhandler(sentry_init, app, capture_events):
    sentry_init(integrations=[SanicIntegration()])
    events = capture_events()

    @app.route("/error")
    def myerror(request):
        raise ValueError("oh no")

    @app.exception(ValueError)
    def myhandler(request, exception):
        1 / 0

    request, response = app.test_client.get("/error")
    assert response.status == 500

    event1, event2 = events

    exception, = event1["exception"]["values"]
    assert exception["type"] == "ValueError"
    assert any(frame["filename"].endswith("test_sanic.py")
               for frame in exception["stacktrace"]["frames"])

    exception = event2["exception"]["values"][-1]
    assert exception["type"] == "ZeroDivisionError"
    assert any(frame["filename"].endswith("test_sanic.py")
               for frame in exception["stacktrace"]["frames"])
Example #2
0
async def startup(heliotrope: Heliotrope, loop: AbstractEventLoop) -> None:
    # DB and http setup
    heliotrope.ctx.odm = ODM.setup(heliotrope.config.INFO_DB_URL, )
    heliotrope.ctx.orm = await ORM.setup(heliotrope.config.GALLERYINFO_DB_URL)
    heliotrope.ctx.request = await BaseRequest.setup()
    heliotrope.ctx.hitomi_request = await HitomiRequest.setup(
        index_file=heliotrope.config.INDEX_FILE)
    heliotrope.ctx.common_js = await CommonJS.setup(
        heliotrope.ctx.hitomi_request)
    # Sentry
    if heliotrope.config.PRODUCTION:
        init(
            heliotrope.config.SENTRY_DSN,
            integrations=[SanicIntegration()],
            release=__version__,
        )

        # Task setup
        supervisor = SuperVisor(heliotrope)
        if is_the_first_process:
            supervisor.add_task(MirroringTask.setup,
                                heliotrope.config.MIRRORING_DELAY)
        supervisor.add_task(RefreshCommonJS.setup,
                            heliotrope.config.REFRESH_COMMON_JS_DELAY)
        heliotrope.add_task(
            supervisor.start(heliotrope.config.SUPERVISOR_DELAY))
Example #3
0
def test_request_data(sentry_init, app, capture_events):
    sentry_init(integrations=[SanicIntegration()])
    events = capture_events()

    request, response = app.test_client.get("/message?foo=bar")
    assert response.status == 200

    event, = events
    assert event["transaction"] == "hi"
    assert event["request"]["env"] == {"REMOTE_ADDR": ""}
    assert set(event["request"]["headers"]) == {
        "accept",
        "accept-encoding",
        "host",
        "user-agent",
    }
    assert event["request"]["query_string"] == "foo=bar"
    assert event["request"]["url"].endswith("/message")
    assert event["request"]["method"] == "GET"

    # Assert that state is not leaked
    events.clear()
    capture_message("foo")
    event, = events

    assert "request" not in event
    assert "transaction" not in event
def create_app(config: Configuration):
    app = Sanic(__name__)

    # Configure Sentry
    init_sentry(
        dsn=config.sentry.dsn,
        environment=config.environment,
        release=__version__,
        integrations=[SanicIntegration()],
    )

    @app.listener('before_server_start')
    async def init(app_, loop):
        pass

    @app.listener('after_server_stop')
    async def close(app_, loop):
        pass

    @app.route('/')
    async def index(_):
        return response.text(f'python-sanic-example ({__version__})')

    app.blueprint(view.app)

    return app
Example #5
0
def create_app(config: Configuration):
    app = Sanic(__name__)

    # Configure Sentry
    init_sentry(
        dsn=config.sentry.dsn,
        environment=config.environment,
        release=__version__,
        integrations=[SanicIntegration()],
    )

    @app.listener('before_server_start')
    async def init(app_, loop):  # pylint: disable=unused-variable
        pass

    @app.listener('before_server_stop')
    async def wait_before_stopping_server(app_, loop):  # pylint: disable=unused-variable
        await asyncio.sleep(config.before_graceful_termination)

    @app.listener('after_server_stop')
    async def close(app_, loop):  # pylint: disable=unused-variable
        pass

    @app.route('/')
    async def index(_):  # pylint: disable=unused-variable
        return response.text(
            f'{{ cookiecutter.project_name }} ({__version__})')

    app.blueprint(view.app)

    return app
Example #6
0
    def _preload_server(self):
        if self.config.driver.sentry_dsn:
            sentry_sdk.init(
                dsn=self.config.driver.sentry_dsn,
                integrations=[SanicIntegration()],
                environment=self.config.driver.sentry_env
            )

        self._sanic = Sanic(name=self.name, log_config=get_logging_config(self.config.app))
        self._sanic.config = self.config.driver.get_sanic_config()
Example #7
0
def test_bad_request_not_captured(sentry_init, app, capture_events):
    sentry_init(integrations=[SanicIntegration()])
    events = capture_events()

    @app.route("/")
    def index(request):
        abort(400)

    request, response = app.test_client.get("/")
    assert response.status == 400

    assert not events
Example #8
0
def build_app():
    from config import config

    sentry_sdk.init(dsn=config.SENTRY_DSN,
                    integrations=[SanicIntegration()],
                    release=VERSION,
                    environment=os.environ.get(
                        'INFOENERGIA_MODULE_SETTINGS').split('.')[-1])

    app = Sanic('infoenergia-api')
    try:
        app.config.from_object(config)

        InitializeJWT(app,
                      authenticate=authenticate,
                      retrieve_user=retrieve_user,
                      class_views=extra_views)
        app.blueprint(bp_contracts)
        app.blueprint(bp_f1_measures)
        app.blueprint(bp_modcontracts)
        app.blueprint(bp_cch_measures)
        app.blueprint(bp_reports)
        app.blueprint(bp_tariff)

        app.add_route(InvitationUrlToken.as_view(),
                      '/auth/invitationtoken',
                      host='localhost:9000')

        app.thread_pool = futures.ThreadPoolExecutor(app.config.MAX_THREADS)
        app.erp_client = Client(transport=PoolTransport(
            secure=app.config.TRANSPORT_POOL_CONF['secure']),
                                **app.config.ERP_CONF)

        db.bind(provider='sqlite',
                filename=os.path.join(
                    app.config.DATA_DIR,
                    '{}.sqlite3'.format(app.config.DB_CONF['database'])),
                create_db=True)
        db.generate_mapping(create_tables=True)
        app.db = db

    except Exception as e:
        msg = "An error ocurred building Infoenergia API: %s"
        logger.exception(msg, str(e))
        raise e
    else:
        logger.info("Build api finished")
        return app
Example #9
0
    def _preload_server(self):
        if self.config.driver.sentry_dsn:
            sentry_kwargs = dict(
                dsn=self.config.driver.sentry_dsn,
                integrations=[SanicIntegration()],
                environment=self.config.driver.sentry_env,
                release=self.config.driver.version,
                ignore_errors=self.config.driver.sentry_ignore_errors,
                **self.config.driver.sentry_kwargs,
            )
            sentry_kwargs.update(self.config.driver.sentry_kwargs)
            sentry_sdk.init(**sentry_kwargs)

        self._sanic = Sanic(name=self.name,
                            log_config=get_logging_config(self.config.app))
        self._sanic.config = self.config.driver.get_sanic_config()
Example #10
0
def test_concurrency(sentry_init, app):
    sentry_init(integrations=[SanicIntegration()])

    @app.route("/context-check/<i>")
    async def context_check(request, i):
        with configure_scope() as scope:
            scope.set_tag("i", i)

        await asyncio.sleep(random.random())

        with configure_scope() as scope:
            assert scope._tags["i"] == i

        return response.text("ok")

    async def task(i):
        responses = []

        await app.handle_request(
            request.Request(
                url_bytes="http://localhost/context-check/{i}".format(
                    i=i).encode("ascii"),
                headers={},
                version="1.1",
                method="GET",
                transport=None,
            ),
            write_callback=responses.append,
            stream_callback=responses.append,
        )

        r, = responses
        assert r.status == 200

    async def runner():
        await asyncio.gather(*(task(i) for i in range(1000)))

    if sys.version_info < (3, 7):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(runner())
    else:
        asyncio.run(runner())

    with configure_scope() as scope:
        assert not scope._tags
Example #11
0
def create_app():
    app = Sanic(__name__)

    # ------------------------------------------------------------------------
    # CONFIGURATION
    # ------------------------------------------------------------------------

    init(dsn=config('SENTRY_DSN'), integrations=[SanicIntegration()])

    app.blueprint(initdb_blueprint)
    app.blueprint(oauth_blueprint)
    app.blueprint(auth_blueprint)
    app.blueprint(form_blueprint)
    app.blueprint(api_retrieve_blueprint)
    app.blueprint(api_create_blueprint)
    app.blueprint(api_update_blueprint)
    app.blueprint(api_delete_blueprint)
    app.blueprint(api_switch_blueprint)
    app.blueprint(api_redirect_blueprint)
    app.blueprint(view_blueprint)
    app.blueprint(extra_blueprint)

    app.static('/links/', './static/')
    app.config.WTF_CSRF_SECRET_KEY = config('WTF_CSRF_SECRET_KEY')

    # ------------------------------------------------------------------------
    # AUTHENTICATION
    # ------------------------------------------------------------------------

    app.session_interface = InMemorySessionInterface()

    app.config.OAUTH_PROVIDER = config('OAUTH_PROVIDER')
    app.config.OAUTH_SCOPE = config('OAUTH_SCOPE')
    app.config.OAUTH_CLIENT_ID = config('OAUTH_CLIENT_ID')
    app.config.OAUTH_CLIENT_SECRET = config('OAUTH_CLIENT_SECRET')
    if config('PRODUCTION', default=False, cast=bool):
        domain = config('DOMAIN_NAME')
    else:
        domain = config('LOCAL_HOST')
    app.config.OAUTH_REDIRECT_URI = domain + config('OAUTH_REDIRECT_ENDPOINT')

    app.register_middleware(add_session_to_request, 'request')
    app.register_middleware(save_session, 'response')

    return app
Example #12
0
def test_errors(sentry_init, app, capture_events):
    sentry_init(integrations=[SanicIntegration()])
    events = capture_events()

    @app.route("/error")
    def myerror(request):
        raise ValueError("oh no")

    request, response = app.test_client.get("/error")
    assert response.status == 500

    event, = events
    assert event["transaction"] == "myerror"
    exception, = event["exception"]["values"]

    assert exception["type"] == "ValueError"
    assert exception["value"] == "oh no"
    assert any(frame["filename"].endswith("test_sanic.py")
               for frame in exception["stacktrace"]["frames"])
Example #13
0
async def before_server_start(app: Sanic):
    """
    Before server start
    @param app:
    @return:
    """
    DatabaseEngineManager.create_engines(
        primary_db_urls=[app.config["PRIMARY_DB_URL"]],
        replica_db_urls=[app.config["REPLICA_DB_URL"]],
    )
    app.db_client = DatabaseClient()
    app.redis_client = await aioredis.create_redis_pool(app.config["REDIS_URL"]
                                                        )
    sentry_sdk.init(
        dsn=app.config["SENTRY_DSN"],
        environment=app.config["ENV"],
        integrations=[
            SanicIntegration(),
            AioHttpIntegration(),
            SqlalchemyIntegration(),
        ],
    )
Example #14
0
 def start(self, deamon=True, port=None, debug=False):
     user = getpass.getuser()
     if user != self.__shell_user:
         raise ValueError(
             f"{user} not autorized, use {self.__shell_user} instead")
     if port:
         self.__port = port
     print("Start Runner", __version__)
     try:
         if os.environ.get("NAAS_SENTRY_DSN"):
             sentry_sdk.init(
                 dsn=os.environ.get("NAAS_SENTRY_DSN"),
                 traces_sample_rate=1.0,
                 environment=escape_kubernet(self.__user),
                 integrations=[SanicIntegration()],
             )
             sentry_sdk.set_user({"email": self.__user})
             with sentry_sdk.configure_scope() as scope:
                 scope.set_context("Naas", {"version": __version__})
         self.__main(debug)
     except KeyboardInterrupt:
         print("Shutdown server")
         sys.exit()
Example #15
0
def test_concurrency(sentry_init, app):
    """
    Make sure we instrument Sanic in a way where request data does not leak
    between request handlers. This test also implicitly tests our concept of
    how async code should be instrumented, so if it breaks it likely has
    ramifications for other async integrations and async usercode.

    We directly call the request handler instead of using Sanic's test client
    because that's the only way we could reproduce leakage with such a low
    amount of concurrent tasks.
    """

    sentry_init(integrations=[SanicIntegration()])

    @app.route("/context-check/<i>")
    async def context_check(request, i):
        with configure_scope() as scope:
            scope.set_tag("i", i)

        await asyncio.sleep(random.random())

        with configure_scope() as scope:
            assert scope._tags["i"] == i

        return response.text("ok")

    async def task(i):
        responses = []

        kwargs = {
            "url_bytes": "http://localhost/context-check/{i}".format(i=i).encode(
                "ascii"
            ),
            "headers": {},
            "version": "1.1",
            "method": "GET",
            "transport": None,
        }

        if SANIC_VERSION >= (19,):
            kwargs["app"] = app

        await app.handle_request(
            request.Request(**kwargs),
            write_callback=responses.append,
            stream_callback=responses.append,
        )

        r, = responses
        assert r.status == 200

    async def runner():
        await asyncio.gather(*(task(i) for i in range(1000)))

    if sys.version_info < (3, 7):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(runner())
    else:
        asyncio.run(runner())

    with configure_scope() as scope:
        assert not scope._tags
Example #16
0
import sentry_sdk
from sentry_sdk.integrations.sanic import SanicIntegration
from tortoise import Tortoise

import config


# 初始化数据库
async def init_db(create_db=False):
    await Tortoise.init(db_url=config.DB_URL,
                        modules={'models': ['app.models']},
                        _create_db=create_db)


sentry_sdk.init(dsn=config.SENTRY_DSN, integrations=[SanicIntegration()])
from django.conf import settings
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.redis import RedisIntegration
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.aiohttp import AioHttpIntegration
from sentry_sdk.integrations.sanic import SanicIntegration

if not settings.DEBUG:
    sentry_sdk.init(
        "https://[email protected]/1471674",
        environment=settings.SENTRY_ENVIRONMENT,
        integrations=[
            CeleryIntegration(),
            DjangoIntegration(),
            RedisIntegration(),
            FlaskIntegration(),
            AioHttpIntegration(),
            SanicIntegration(),
        ],
        release=os.getenv("RELEASE", None),
        traces_sample_rate=1.0,
    )

try:
    application = get_wsgi_application()
except Exception as e:
    print(e)
    traceback.print_exc()
Example #18
0
        app.conn.use("magiccap")

        await app.create_table_if_not_exists("uploads")
        await app.create_table_if_not_exists("installs")

        await app.create_s3_client()


app = RethinkSanic(__name__)
# Defines the app.

CORS(app)
# Allows CORS.

sentry_sdk.init(dsn=os.environ['SENTRY_DSN'],
                integrations=[SanicIntegration()])
# Loads in Sentry.


@app.route("/")
async def root_redirect(_):
    """Redirects to magiccap.me."""
    return response.redirect("https://magiccap.me")


@app.route("/healthcheck")
async def healthcheck(_):
    """A simple healthcheck."""
    return response.json(200)

Example #19
0
def test_concurrency(sentry_init, app):
    """
    Make sure we instrument Sanic in a way where request data does not leak
    between request handlers. This test also implicitly tests our concept of
    how async code should be instrumented, so if it breaks it likely has
    ramifications for other async integrations and async usercode.

    We directly call the request handler instead of using Sanic's test client
    because that's the only way we could reproduce leakage with such a low
    amount of concurrent tasks.
    """

    sentry_init(integrations=[SanicIntegration()])

    @app.route("/context-check/<i>")
    async def context_check(request, i):
        with configure_scope() as scope:
            scope.set_tag("i", i)

        await asyncio.sleep(random.random())

        with configure_scope() as scope:
            assert scope._tags["i"] == i

        return response.text("ok")

    async def task(i):
        responses = []

        kwargs = {
            "url_bytes": "http://localhost/context-check/{i}".format(i=i).encode(
                "ascii"
            ),
            "headers": {},
            "version": "1.1",
            "method": "GET",
            "transport": None,
        }

        if SANIC_VERSION >= (19,):
            kwargs["app"] = app

        if SANIC_VERSION >= (21, 3):
            try:
                app.router.reset()
                app.router.finalize()
            except AttributeError:
                ...

            class MockAsyncStreamer:
                def __init__(self, request_body):
                    self.request_body = request_body
                    self.iter = iter(self.request_body)
                    self.response = b"success"

                def respond(self, response):
                    responses.append(response)
                    patched_response = HTTPResponse()
                    patched_response.send = lambda end_stream: asyncio.sleep(0.001)
                    return patched_response

                def __aiter__(self):
                    return self

                async def __anext__(self):
                    try:
                        return next(self.iter)
                    except StopIteration:
                        raise StopAsyncIteration

            patched_request = request.Request(**kwargs)
            patched_request.stream = MockAsyncStreamer([b"hello", b"foo"])

            await app.handle_request(
                patched_request,
            )
        else:
            await app.handle_request(
                request.Request(**kwargs),
                write_callback=responses.append,
                stream_callback=responses.append,
            )

        (r,) = responses
        assert r.status == 200

    async def runner():
        await asyncio.gather(*(task(i) for i in range(1000)))

    if sys.version_info < (3, 7):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(runner())
    else:
        asyncio.run(runner())

    with configure_scope() as scope:
        assert not scope._tags
Example #20
0
File: app.py Project: acquity3/api
    UserService,
)
from src.utils import AcquityJson

if APP_CONFIG["SENTRY_ENABLE"]:

    def sentry_before_send(event, hint):
        if "exc_info" in hint:
            _exc_type, exc_value, _tb = hint["exc_info"]
            if isinstance(exc_value, AcquityException):
                return None
        return event

    sentry_sdk.init(
        dsn="https://[email protected]/1800796",
        integrations=[SanicIntegration(), SqlalchemyIntegration()],
        before_send=sentry_before_send,
    )

app = Sanic(load_env=False)
app.config.update(APP_CONFIG)

sio = socketio.AsyncServer(
    async_mode="sanic", cors_allowed_origins=[], json=AcquityJson
)
sio.attach(app)
sio.register_namespace(ChatSocketService("/v1/chat", app.config))

app.user_service = UserService(app.config)
app.sell_order_service = SellOrderService(app.config)
app.buy_order_service = BuyOrderService(app.config)
Example #21
0
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import asyncio

import sentry_sdk
import uvloop
from sentry_sdk.integrations.sanic import SanicIntegration
from sentry_sdk.integrations.aiohttp import AioHttpIntegration

from . import Server
from .logging import fix_access_log, setup_logging

sentry_sdk.init(
    dsn=
    "https://[email protected]/5921973",
    integrations=[SanicIntegration(), AioHttpIntegration()],
    request_bodies="always",
    traces_sample_rate=1.0)

asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())

with setup_logging():
    fix_access_log()

    Server.with_config().run()