import typing from flask import g from .. import CortexSearchConfig, init_cortex_search if typing.TYPE_CHECKING: from flask import Flask class FlaskCortexSearch: """Flask extension for integrating CortexSearchClient. This extension initializes and manages the Cortex Search client within a Flask application context. It reads Snowflake connection settings from the Flask application configuration and sets up the search service if valid credentials are provided. Connects owslogger to include correlation_id in a right way. Expected Flask config keys: - ``SNOWFLAKE_ACCOUNT``: Snowflake account identifier. - ``SNOWFLAKE_USER``: Snowflake username. - ``SNOWFLAKE_DATABASE``: Target Snowflake database. - ``SNOWFLAKE_SCHEMA``: Target Snowflake schema. - ``SNOWFLAKE_CORTEX_SEARCH_SERVICE_NAME``: Name of the Cortex Search service. - ``SNOWFLAKE_PRIVATE_KEY_PATH``: Path to the private key file (PEM/P8). - ``SNOWFLAKE_PRIVATE_KEY``: Private key content as a string (alternative to path if already parsed). - ``SNOWFLAKE_KEY_PASSPHRASE``: Passphrase for the private key, if encrypted. - ``SNOWFLAKE_CORTEX_SEARCH_SCORING_CONFIG``: Optional scoring configuration. - ``SNOWFLAKE_LOGIN_TIMEOUT``: Optional login timeout in seconds. - ``SNOWFLAKE_NETWORK_TIMEOUT``: Optional network timeout in seconds. """ def __init__(self, app: 'Flask | None' = None) -> None: if app is not None: self.init_app(app) def init_app(self, app: 'Flask') -> None: """Bind the extension to a Flask application and initialize Cortex Search. Initialization is skipped when neither ``SNOWFLAKE_PRIVATE_KEY_PATH`` nor ``SNOWFLAKE_PRIVATE_KEY`` is set in the app config, allowing the application to start without Snowflake credentials in environments where the search feature is not required. Args: app: The Flask application instance to bind this extension to. """ if 'cortex_search' in app.extensions: raise RuntimeError('FlaskCortexSearch is already initialised on this app.') app.extensions['cortex_search'] = self config = app.config if config.get('SNOWFLAKE_PRIVATE_KEY_PATH') or config.get( 'SNOWFLAKE_PRIVATE_KEY' ): init_cortex_search( CortexSearchConfig( SNOWFLAKE_ACCOUNT=config.get('SNOWFLAKE_ACCOUNT'), SNOWFLAKE_USER=config.get('SNOWFLAKE_USER'), SNOWFLAKE_DATABASE=config.get('SNOWFLAKE_DATABASE'), SNOWFLAKE_SCHEMA=config.get('SNOWFLAKE_SCHEMA'), SNOWFLAKE_CORTEX_SEARCH_SERVICE_NAME=config.get( 'SNOWFLAKE_CORTEX_SEARCH_SERVICE_NAME' ), SNOWFLAKE_PRIVATE_KEY_PATH=config.get('SNOWFLAKE_PRIVATE_KEY_PATH'), SNOWFLAKE_KEY_PASSPHRASE=config.get('SNOWFLAKE_KEY_PASSPHRASE'), SNOWFLAKE_PRIVATE_KEY=config.get('SNOWFLAKE_PRIVATE_KEY'), SNOWFLAKE_CORTEX_SEARCH_SCORING_CONFIG=config.get( 'SNOWFLAKE_CORTEX_SEARCH_SCORING_CONFIG' ), SNOWFLAKE_LOGIN_TIMEOUT=config.get('SNOWFLAKE_LOGIN_TIMEOUT'), SNOWFLAKE_NETWORK_TIMEOUT=config.get('SNOWFLAKE_NETWORK_TIMEOUT'), ), lambda: getattr(g, 'log', None), )