def common_app_setup(app,
                     session_cookie_domain=None,
                     session_expiration_seconds=None):
    app.session_interface = RedisSessionInterface(
        session_cookie_domain=session_cookie_domain,
        session_expiration_seconds=session_expiration_seconds,
    )

    CORS(app, supports_credentials=config.CORS_SUPPORT_CREDENTIALS)

    register_global_endpoints(app)
    register_request_cleanup(app)
    register_request_handlers(app)

    initialize_sentry(flask=True)

    if config.SCOUT_KEY:
        app.config['SCOUT_MONITOR'] = True
        app.config['SCOUT_KEY'] = config.SCOUT_KEY
        app.config['SCOUT_NAME'] = config.SCOUT_NAME
        app.config[
            'SCOUT_CORE_AGENT_FULL_NAME'] = "scout_apm_core-v1.1.8-x86_64-unknown-linux-musl"

        ScoutApm(app)

    app.config['SESSION_COOKIE_NAME'] = 'session_id'
Example #2
0
def app_with_scout(config=None):
    """
    Context manager that configures and installs the Scout plugin for Bottle.

    """
    # Enable Scout by default in tests.
    if config is None:
        config = {"SCOUT_MONITOR": True}

    # Disable running the agent.
    config["SCOUT_CORE_AGENT_LAUNCH"] = False

    # Setup according to http://help.apm.scoutapp.com/#flask
    scout = ScoutApm(app)
    for key, value in config.items():
        app.config[key] = value
    try:
        yield app
    finally:
        # Restore original configuration.
        assert app.before_first_request_funcs == [scout.before_first_request]
        assert app.before_request_funcs == {None: [scout.process_request]}
        assert app.after_request_funcs == {None: [scout.process_response]}
        assert app.dispatch_request == scout.dispatch_request
        del app.before_first_request_funcs[:]
        del app.before_request_funcs[None][:]
        del app.after_request_funcs[None][:]
        del app.dispatch_request
        # Reset Scout configuration.
        Config.reset_all()
Example #3
0
def configure_scout(app):
    try:
        from scout_apm.flask import ScoutApm
        from scout_apm.flask.sqlalchemy import instrument_sqlalchemy
    except ImportError:
        return False

    app.config.setdefault("SCOUT_NAME", "Zeus")
    app.config.setdefault("SCOUT_MONITOR", True)

    ScoutApm(app)
    instrument_sqlalchemy(db)
Example #4
0
def app_with_scout(config=None):
    """
    Context manager that configures and installs the Scout plugin for Bottle.

    """
    if config is None:
        config = {}

    config["SCOUT_CORE_AGENT_LAUNCH"] = False
    config.setdefault("SCOUT_MONITOR", True)
    # Disable Flask's error page to improve debugging
    config.setdefault("PROPAGATE_EXCEPTIONS", True)

    # Basic Flask app
    app = flask.Flask("test_app")

    @app.route("/")
    def home():
        return "Welcome home."

    @app.route("/hello/",
               methods=["GET", "OPTIONS"],
               provide_automatic_options=False)
    def hello():
        if flask.request.method == "OPTIONS":
            return "Hello Options!"
        return "Hello World!"

    @app.route("/set-session/")
    def set_session():
        flask.session["session_var"] = 1
        return "Set session"

    @app.route("/crash/")
    def crash():
        raise ValueError("BØØM!")  # non-ASCII

    @app.route("/return-error/")
    def return_error():
        return "Something went wrong", 503

    # Setup according to https://docs.scoutapm.com/#flask
    ScoutApm(app)
    app.config.update(config)
    app.secret_key = "123"

    try:
        yield app
    finally:
        Config.reset_all()
Example #5
0
def create_app():
    app = Flask(__name__)
    CORS(app)
    ScoutApm(app)

    app.config["SCOUT_MONITOR"] = os.environ.get("SCOUT_MONITOR")
    app.config["SCOUT_KEY"] = os.environ.get("SCOUT_KEY")
    app.config["SCOUT_NAME"] = "trimtr"

    # 先に学習済みモデルを用意しておくことでリクエストが来てから学習しなくてよくなる
    setup_sent_tokenize = SentenceTokenizer.get_instance()
    setup_trimmer = Trimmer.get_instance()

    return app
Example #6
0
def load_scout_apm(app, db, celery=False):
    logger = _get_logger(app, celery)
    try:
        if celery:
            import scout_apm.celery
            from scout_apm.api import Config
            Config.set(key=app.config['SCOUT_KEY'],
                       monitor=app.config['SCOUT_MONITOR'],
                       name=app.config['SCOUT_NAME'])
            scout_apm.celery.install()
        else:
            from scout_apm.flask import ScoutApm
            from scout_apm.flask.sqlalchemy import instrument_sqlalchemy
            ScoutApm(app)
            instrument_sqlalchemy(db)
    except ImportError:
        logger.warning('Scout APM modules not found')
    else:
        logger.info('Scout APM initialized')
Example #7
0
    def __init__(self, app):
        self.cors = CORS(app)
        self.talisman = Talisman(app)
        self.jwt = JWTManager(app)
        self.email_sender = EmailSender(app)
        self.email_verifier = EmailVerifier(app)
        self.json = FlaskJSON(app)
        self.img_manager = ImageManager(app)
        self.password_checker = PasswordEnforcer()
        self.scout_apm = ScoutApm(app)
        self.compressor = Compress(app)

        self.pymongo_db = pymongo.MongoClient(os.getenv('MONGO_URI'))[app.config['DATABASE_NAME']]

        self.mongo = mongo
        self.mongo.connect(host=os.getenv('MONGO_URI'))

        self.club_recommender = ClubRecommender(self.pymongo_db, f'ml-models/club-model-{CurrentConfig.MODE}.pkl')
        self.club_recommender.train_or_load_model(force_train=True)
Example #8
0
def app_with_scout(config=None):
    """
    Context manager that configures and installs the Scout plugin for Bottle.

    """
    # Enable Scout by default in tests.
    if config is None:
        config = {"SCOUT_MONITOR": True}

    # Disable running the agent.
    config["SCOUT_CORE_AGENT_LAUNCH"] = False

    # Basic Flask app
    app = flask.Flask("test_app")
    # Enable the following for debugging exceptions:
    # app.config["PROPAGATE_EXCEPTIONS"] = True

    @app.route("/")
    def home():
        return "Welcome home."

    @app.route("/hello/",
               methods=["GET", "OPTIONS"],
               provide_automatic_options=False)
    def hello():
        if flask.request.method == "OPTIONS":
            return "Hello Options!"
        return "Hello World!"

    @app.route("/crash/")
    def crash():
        raise ValueError("BØØM!")  # non-ASCII

    # Setup according to https://docs.scoutapm.com/#flask
    ScoutApm(app)
    app.config.update(config)

    try:
        yield app
    finally:
        Config.reset_all()
Example #9
0
from app.resources.iron_cache import IronCacheResource
from app.resources.strava import StravaResource

app_variables = AppVariables()
app_constants = AppConstants()
strava_resource = StravaResource()
athlete_resource = AthleteResource()
database_resource = DatabaseResource()
iron_cache_resource = IronCacheResource()
calculate_challenge_stats = CalculateChallengesStats()
challenges = Challenges()

app = Flask(__name__)
app.config.from_object(__name__)

ScoutApm(app)

app.config['SCOUT_MONITOR'] = app_variables.scout_monitor
app.config['SCOUT_KEY'] = app_variables.scout_key
app.config['SCOUT_NAME'] = app_variables.scout_name

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.os.environ.get('LOGGING_LEVEL'))
logger = logging.getLogger(__name__)


@app.route('/webhook/<category>', methods=['GET', 'POST'])
def strava_webhook(category):
    if request.method == 'POST':
        handle_webhook.delay(category, request.json)
Example #10
0
    {"name": "twitter:card", "content": "summary_large_image"},
    {"http-equiv": "X-UA-Compatible", "content": "IE=edge"},
    {"name": "viewport", "content": "width=device-width, initial-scale=1.0"},
]

app = dash.Dash(
    __name__,
    external_stylesheets=[BULMA_CSS, OPEN_SANS],
    external_scripts=[FONT_AWESOME, GOOGLE_ANALYTICS],
    meta_tags=meta_tags,
)
app.title = TEXT["title"]
server = app.server

# performance monitoring
ScoutApm(server)

if "REDIS_URL" in os.environ:
    cache = Cache(
        app.server,
        config={
            "CACHE_TYPE": "redis",
            "CACHE_REDIS_URL": os.environ.get("REDIS_URL", ""),
        },
    )
else:
    cache = Cache(
        app.server, config={"CACHE_TYPE": "filesystem", "CACHE_DIR": "cache-directory"}
    )

layout = html.Div(
Example #11
0
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from scout_apm.flask import ScoutApm

external_stylesheets = [
    dbc.themes.BOOTSTRAP,
    'https://codepen.io/almostburtmacklin/pen/QWWKEJb.css'
]

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True
flask = app.server
ScoutApm(flask)
flask.config["SCOUT_NAME"] = "Baseball App"