Example #1
0
def create_app():
    if os.environ.get('SENTRY_DSN'):
        sentry_init(dsn=os.environ['SENTRY_DSN'],
                    integrations=[FlaskIntegration()])
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
        'DATABASE_URL', 'sqlite:///yume.db')
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    try:
        with open('.secret_key', 'rb') as f:
            app.secret_key = f.read()
    except FileNotFoundError:
        app.secret_key = os.urandom(64)
        f = open('.secret_key', 'wb')
        f.write(app.secret_key)
        f.close()

    app.register_blueprint(api)
    app.register_blueprint(game)

    db.app = app
    db.init_app(app)

    babel.app = app
    babel.init_app(app)

    app.config.update(
        CELERY_BROKER_URL=os.environ.get('CELERY_BROKER_URL',
                                         'sqla+sqlite:///yume_broker.db'),
        CELERY_RESULT_BACKEND=os.environ.get('CELERY_RESULT_BACKEND',
                                             'db+sqlite:///yume_reuslt.db'))
    return app
Example #2
0
def _init_sentry(dsn, integrations):
    """Initialise Sentry error tracking.

    For details, see:
    https://docs.sentry.io/error-reporting/configuration/?platform=python

    Args:
        dsn (str): Sentry DSN (can be obtained from web console)
        integrations (List[sentry.integrations]): frameworks to hook into Sentry client

    """
    environment = os.getenv('SCRAPY_PROJECT_ID',
                            'local')  # dependant on `scrapy-jobparameters`
    server_name = 'scrapinghub' if is_shub_env() else 'local'

    sentry_init(
        dsn=dsn,
        integrations=integrations,
        before_send=_filter_exceptions,
        before_breadcrumb=_filter_breadcrumbs,
        in_app_include=[application.__package__],
        release=application.__version__,
        environment=environment,
        server_name=server_name,
        # request_bodies='always',
        # attach_stacktrace=True,  # send stacktraces together with log messages
    )
Example #3
0
    def _update_config(self, additional_config):
        version = "updatebot-"
        version += _run(["git", "rev-parse", "HEAD"],
                        shell=False,
                        clean_return=True).stdout.decode().strip()
        version += "-dirty" if _run(["[[ -z $(git status -s) ]]"],
                                    shell=True,
                                    clean_return=False).returncode else ""

        environment = ""
        if "TASK_ID" in os.environ:
            environment = "taskcluster"
        else:
            environment = _run(["hostname"], shell=False,
                               clean_return=True).stdout.decode().strip()

        sentry_init(dsn=self.config['sentry_config']['url'],
                    debug=self.config['sentry_config']['debug']
                    if 'debug' in self.config['sentry_config'] else False,
                    release=version,
                    max_breadcrumbs=5000,
                    environment=environment)

        with configure_scope() as scope:
            if "TASK_ID" in os.environ:
                scope.set_extra("TASK_ID", os.environ['TASK_ID'])
Example #4
0
    def setup(self, app: Application, **options):
        """Initialize Sentry Client."""
        super().setup(app, **options)

        if not self.cfg.dsn:
            return

        # Setup Sentry
        sentry_init(dsn=self.cfg.dsn, **self.cfg.sdk_options)
Example #5
0
    def _setup_sentry(self, logger, dsn):
        if not SENTRY_IMPORTED:
            raise Exception('If specifying SENTRY_DSN, sentry_sdk must be installed'
                            ' (pip install flask-logger[Sentry])')

        env = self.config.get('environment') or self.config.get('env')
        sentry_init(dsn=dsn, integrations=[FlaskIntegration()], environment=env)
        sentry_integration = GLOBAL_HUB.get_integration(LoggingIntegration)
        logger.addHandler(sentry_integration._handler)  # pylint: disable=protected-access
    def _initialize(self):
        try:
            from sentry_sdk import init as sentry_init
            from sentry_sdk import capture_exception as sentry_capture_exception
            self._exception_callback = sentry_capture_exception

            sentry_init(self.config['url'])

        except ImportError:
            raise Exception(
                'Cannot initialize SentryIO integration, sentry probably not installed'
            )
Example #7
0
    def init(self):
        if not self.settings.token:
            Logger.log.error('No access token!')
            exit()
        self.session = VK(self.settings.token)
        self.api = self.session.get_api()

        if not self.settings.debug and self.settings.sentry_dsn:
            sentry_init(self.settings.sentry_dsn, traces_sample_rate=1.0)
            Logger.log.info('Sentry initialized!')

        for p in self.settings.plugins:
            for init in p.init_methods:
                Logger.log.debug(f'Init: {p.__class__.__name__}')
                init.call()
            self.plugins.append(p)
Example #8
0
def register_error_handlers(app):
    from flask_json import json_response

    # - - - - - - - - - - - - - - - - - - - - - - -
    @app.errorhandler(BaseError)
    def handle_olea_exceptions(e: BaseError):
        return json_response(status_=e.http_code, data_=e)

    # - - - - - - - - - - - - - - - - - - - - - - -
    from sentry_sdk import init as sentry_init
    from sentry_sdk.integrations import flask, redis, sqlalchemy

    if not app.config.get('IGNORE_ERRORS', False):
        sentry_init(dsn=app.config['SENTRY_DSN'],
                    integrations=[
                        flask.FlaskIntegration(),
                        sqlalchemy.SqlalchemyIntegration(),
                        redis.RedisIntegration(),
                    ],
                    traces_sample_rate=0.2)
Example #9
0
def create_wsgi():
    application = FlaskApp(__name__)
    config = settings.load_config((
        settings.FlaskSettings,
        settings.SentrySetting,
    ))
    application.app.config.from_object(config)
    CORS(application.app)

    application.add_api(specification='v1/openapi.yaml',
                        resolver=VersionResolver('app.http.v1.handlers'),
                        strict_validation=True,
                        validate_responses=True)

    @application.app.teardown_appcontext
    def shutdown_session(exception):
        models.session.remove()

    sentry_init(dsn=config.SENTRY_DSN,
                integrations=[sentry_flask.FlaskIntegration()])

    return application
Example #10
0
# coding=utf-8

import os
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations import celery as sentry_celery
from celery import Celery
from . import config


manager = Celery('app')
manager.config_from_object(config)
sentry_init(
    dsn=os.getenv('SENTRY_DSN'),
    integrations=(sentry_celery.CeleryIntegration(),)
)
Example #11
0
from sentry_sdk import init as sentry_init
from app import app
from app.utils.logger import get_logger
from app.utils.config import get_config

SENTRY_DSN = get_config('SENTRY_DSN')
log = get_logger(__name__)


if __name__ == '__main__':
    log.info('Starting InventoryService')

    if SENTRY_DSN:
        sentry_init(SENTRY_DSN)

    app.run(host='0.0.0.0', port=5000, debug=get_config('DEBUG', default=False))
Example #12
0

class CustomPasswordResetTokenGenerator(PasswordResetTokenGenerator):
    """Custom Password Token Generator Class."""
    def _make_hash_value(self, user, timestamp):
        # Include user email alongside user password to the generated token
        # as the user state object that might change after a password reset
        # to produce a token that invalidated.
        login_timestamp = '' if user.last_login is None\
            else user.last_login.replace(microsecond=0, tzinfo=None)
        return str(user.pk) + user.password + user.email +\
            str(login_timestamp) + str(timestamp)


default_token_generator = CustomPasswordResetTokenGenerator()
sentry_init(settings.SENTRY_DSN, environment=settings.ENV_ROLE)

User = get_user_model()


def get_or_create_csrf_token(request):
    token = request.META.get('CSRF_COOKIE', None)
    if token is None:
        # Getting a new token
        token = csrf.get_token(request)
        request.META['CSRF_COOKIE'] = token

    request.META['CSRF_COOKIE_USED'] = True
    return token

Example #13
0
    j_print(
        "Database backup to S3 is configured.",
        host=CONFIG.y("postgresql.s3_backup.host"),
    )

# Sentry integration
_ERROR_REPORTING = CONFIG.y_bool("error_reporting.enabled", False)
if not DEBUG and _ERROR_REPORTING:
    # pylint: disable=abstract-class-instantiated
    sentry_init(
        dsn="https://[email protected]/8",
        integrations=[
            DjangoIntegration(transaction_style="function_name"),
            CeleryIntegration(),
            RedisIntegration(),
        ],
        before_send=before_send,
        release=f"authentik@{__version__}",
        traces_sample_rate=0.6,
        environment=CONFIG.y("error_reporting.environment", "customer"),
        send_default_pii=CONFIG.y_bool("error_reporting.send_pii", False),
    )
    j_print(
        "Error reporting is enabled.",
        env=CONFIG.y("error_reporting.environment", "customer"),
    )

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = "/static/"
Example #14
0
import os

from flask import Flask, render_template
from jinja2 import StrictUndefined
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.flask import FlaskIntegration

from .extensions import db, migrate

app = Flask(__name__)
app.config.from_object("{{cookiecutter.app_name}}.config")

if app.config.get("JINJA_STRICT_UNDEFINED"):
    # Detect undefined jinja variables
    app.jinja_env.undefined = StrictUndefined

# Initialize Extensions
db.init_app(app)
migrate.init_app(app, db)

SENTRY_API_KEY = os.environ.get("SENTRY_API_KEY")
if SENTRY_API_KEY:
    sentry_init(SENTRY_API_KEY, integrations=[FlaskIntegration()])


@app.route("/")
def index() -> str:
    return render_template("index.html")
Example #15
0
from flask import Flask
from flask_cors import CORS
from sentry_sdk import init as sentry_init
import config
from database import mongo_client
from log import get_logger
from models.error_handler import error_blueprint
from models.users_handler import users_blueprint
from models.video_handler import video_blueprint

logger = get_logger(__name__)

sentry_init(config.SENTRY_DSN, traces_sample_rate=1.0)

app = Flask(__name__)

CORS(app)

app.register_blueprint(error_blueprint)
app.register_blueprint(users_blueprint)
app.register_blueprint(video_blueprint)

mongo_client.init_app(app, uri=config.MONGO_URI)


@app.route("/")
def home():
    return "the server is up & running"


if __name__ == "__main__":
Example #16
0
def configure_sentry_logging(dsn: str, environment: str) -> None:
    config = build_sentry_configuration(dsn, environment)
    sentry_init(**config)
Example #17
0
from os import getenv

from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.sanic import SanicIntegration

from sanic import Sanic
from sanic.response import json

sentry_init(
    dsn=getenv("SENTRY_DSN"),
    integrations=[SanicIntegration()],
)

app = Sanic(__name__)


# noinspection PyUnusedLocal
@app.route("/working")
async def working_path(request):
    return json({
        "response": "Working API Response"
    })


# noinspection PyUnusedLocal
@app.route("/raise-error")
async def raise_error(request):
    raise Exception("Testing Sentry Integration")


if __name__ == '__main__':
Example #18
0
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = 1

# Sentry integration

if not DEBUG:
    sentry_init(
        dsn="https://[email protected]/2",
        integrations=[
            DjangoIntegration(transaction_style="function_name"),
            CeleryIntegration(),
        ],
        before_send=before_send,
        release='p2@%s' % __version__)

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/_/static/'

structlog.configure_once(
    processors=[
        structlog.stdlib.add_log_level,
        structlog.stdlib.PositionalArgumentsFormatter(),
        structlog.processors.TimeStamper(),
        structlog.processors.StackInfoRenderer(),
Example #19
0
def disable_sentry_logging() -> None:
    sentry_init(dsn=None)
Example #20
0
import os
import psycopg2
from psycopg2 import pool
from psycopg2.extras import Json
import requests
import secrets
from sentry_sdk import init as sentry_init
import sys
import time
from traceback import format_exc

import matrix_manager
from pdf_maker import get_pdf_name
from grid import parse_batch, batch_size_from_batch_name
sentry_init('https://[email protected]/8',
            environment=os.getenv('SENTRY_ENV', 'dev'),
            release=os.getenv('SENTRY_RELEASE', 'unknown'))

from compute_wrapper import get_test_results
"""
    App setup, teardown and constants
"""

app = Flask(__name__)
app.secret_key = 'byom-testing-backend'

# Response headers
CONTENT_TYPE = "Content-Type"
CONTENT_JSON = "application/json"

# Using lmdb as a simple K/V store for storing auth tokens and OTP for mobile numbers. Can be replaced by redis once requirements get more complex
Example #21
0
SITE_ID = 1

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = "/static/"

# Sentry integration
_ERROR_REPORTING = CONFIG.y_bool("error_reporting", False)
if not DEBUG and _ERROR_REPORTING:
    sentry_init(
        dsn="https://[email protected]/5",
        integrations=[
            DjangoIntegration(transaction_style="function_name"),
            CeleryIntegration(),
            RedisIntegration(),
        ],
        before_send=before_send,
        release="pyazo@%s" % __version__,
        traces_sample_rate=1.0,
        send_default_pii=False,
    )
    print(
        dumps({
            "event": "Error reporting is enabled.",
            "level": "info",
            "logger": __name__,
        }))

structlog.configure_once(
    processors=[
        structlog.stdlib.add_log_level,
Example #22
0
from envparse import env
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.redis import RedisIntegration
from sentry_sdk.integrations.rq import RqIntegration

from .base import *  # noqa


sentry_init(
    dsn=env.str("SENTRY_DSN", default=""),
    integrations=[DjangoIntegration(), RedisIntegration(), RqIntegration()],
)

POCKET_CONSUMER_KEY = env.str("POCKET_CONSUMER_KEY")

STATICFILES_DIRS = [os.path.join(FRONTEND_DIR, "theme", "dist", "assets")]
Example #23
0
from os import getenv

from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.sanic import SanicIntegration

from sanic import Sanic
from sanic.response import json

sentry_init(
    dsn=getenv("SENTRY_DSN"),
    integrations=[SanicIntegration()],
)

app = Sanic("Example")


# noinspection PyUnusedLocal
@app.route("/working")
async def working_path(request):
    return json({"response": "Working API Response"})


# noinspection PyUnusedLocal
@app.route("/raise-error")
async def raise_error(request):
    raise Exception("Testing Sentry Integration")


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=getenv("PORT", 8080))
Example #24
0
from aiohttp import ClientSession
from aiohttp.web import Application, Request, Response, run_app
from cachetools import LRUCache
from gidgethub.sansio import Event
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations.aiohttp import AioHttpIntegration

from algorithms_keeper.api import GitHubAPI
from algorithms_keeper.event import main_router

cache: MutableMapping[Any, Any] = LRUCache(maxsize=500)

sentry_init(
    dsn=os.environ.get("SENTRY_DSN"),
    integrations=[
        AioHttpIntegration(transaction_style="method_and_path_pattern")
    ],
)

logging.basicConfig(
    format="[%(levelname)s] %(message)s",
    level=os.environ.get("LOG_LEVEL", "INFO"),
    handlers=[logging.StreamHandler()],
)

logger = logging.getLogger(__package__)


async def main(request: Request) -> Response:
    try:
        body = await request.read()
Example #25
0
# Sentry integration
SENTRY_DSN = "https://[email protected]/8"

env = get_env()
_ERROR_REPORTING = CONFIG.y_bool("error_reporting.enabled", False)
if _ERROR_REPORTING:
    # pylint: disable=abstract-class-instantiated
    sentry_init(
        dsn=SENTRY_DSN,
        integrations=[
            DjangoIntegration(transaction_style="function_name"),
            CeleryIntegration(),
            RedisIntegration(),
            Boto3Integration(),
            ThreadingIntegration(propagate_hub=True),
        ],
        before_send=before_send,
        release=f"authentik@{__version__}",
        traces_sample_rate=float(CONFIG.y("error_reporting.sample_rate", 0.5)),
        environment=CONFIG.y("error_reporting.environment", "customer"),
        send_default_pii=CONFIG.y_bool("error_reporting.send_pii", False),
    )
    set_tag("authentik.build_hash", get_build_hash("tagged"))
    set_tag("authentik.env", env)
    set_tag("authentik.component", "backend")
    set_tag("authentik.uuid",
            sha512(str(SECRET_KEY).encode("ascii")).hexdigest()[:16])
    j_print(
        "Error reporting is enabled",
        env=CONFIG.y("error_reporting.environment", "customer"),
Example #26
0
    SANIC_CONFIG,
    CORS_ORIGINS,
    SENTRY_DSN,
    MODE,
    CELERY_BROKER_PASSWORD,
)
from ora_backend.constants import UNCLAIMED_CHATS_PREFIX

# Init Sentry before app creation
if SENTRY_DSN:
    sentry_init(
        dsn=SENTRY_DSN,
        integrations=[
            CeleryIntegration(),
            RedisIntegration(),
            SanicIntegration(),
            SqlalchemyIntegration(),
        ],
        request_bodies="always",
        send_default_pii=True,
    )

# Note: Gino doesn't auto-generate any new changes in the schema
# Use alembic to apply new changes to the db
# (Refer to scripts/migration.sh)
db = Gino()

app = Sanic(__name__)

app.config.update(SANIC_CONFIG)
app.config["JWT_SECRET_KEY"] = JWT_SECRET_KEY
Example #27
0
from sentry_sdk import init as sentry_init
from sentry_sdk.integrations import sqlalchemy as sentry_sqlalchemy
from sqlalchemy.engine import create_engine
from app import settings
from ._base import (
    Base,
    session,
    enable_time_logging,
)
from .task import Task
from .user import User


config = settings.load_config(
    (settings.SQLAlchemySettings, settings.SentrySetting,)
)
if config.QUERY_TIME_LOGGING:
    enable_time_logging(config.QUERY_TIME_THRESHOLD)

engine = create_engine(         # pylint: disable=C0103
    config.SQLALCHEMY_DATABASE_URI,
    convert_unicode=True,
    echo=bool(config.SQLALCHEMY_ENGINE_LOG)
)
session.configure(bind=engine)

sentry_init(
    dsn=config.SENTRY_DSN,
    integrations=(sentry_sqlalchemy.SqlalchemyIntegration(),)
)
Example #28
0
#
# if development server enable debugging and load local keys.
if not os.environ.get('SECRET_KEY'):
    from flask_debugtoolbar import DebugToolbarExtension
    from development_local.local_settings import SECRET_KEY
    app.config["SECRET_KEY"] = SECRET_KEY
    app.config['SQLALCHEMY_ECHO'] = True
    app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False
    DEBUG = DebugToolbarExtension(app)
    logging.basicConfig(filename='gastronaut.log', level=logging.WARNING,
                        format='%(levelname)s:%(asctime)s:%(message)s')

# if production server enable sentry and load environ variables.
else:
    sentry_init(
        dsn="https://[email protected]/5319947",  # NOQA E 501
        integrations=[FlaskIntegration(), SqlalchemyIntegration()]
    )
    app.config["SECRET_KEY"] = os.environ.get('SECRET_KEY')
    DEBUG = False


connect_db(app)


#
# 404, 401
#


@app.errorhandler(404)
def page_not_found(e):