Python flask_sqlalchemy.SQLAlchemy() Examples

The following are 30 code examples of flask_sqlalchemy.SQLAlchemy(). 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 flask_sqlalchemy , or try the search function .
Example #1
Source File: __init__.py    From hobbit-core with MIT License 7 votes vote down vote up
def init_app(self, app, db, **kwargs):
        """
        app: The Flask application instance.
        """
        if not isinstance(app, Flask):
            raise TypeError(
                'hobbit_core.HobbitManager.init_app(): '
                'Parameter "app" is an instance of class "{}" '
                'instead of a subclass of class "flask.Flask".'.format(
                    app.__class__.__name__))

        if not isinstance(db, SQLAlchemy):
            raise TypeError('hobbit-core be dependent on SQLAlchemy.')
        self.db = db

        app.config.setdefault('HOBBIT_UPPER_SEQUENCE_NAME', False)

        # Bind hobbit-core to app
        app.hobbit_manager = self 
Example #2
Source File: db_object.py    From docassemble with MIT License 6 votes vote down vote up
def init_flask():
    global db
    global UserMixin
    import docassemble.webapp.database
    if docassemble.webapp.database.pool_pre_ping:
        from flask_sqlalchemy import SQLAlchemy as _BaseSQLAlchemy
        class SQLAlchemy(_BaseSQLAlchemy):
            def apply_pool_defaults(self, app, options):
                super().apply_pool_defaults(app, options)
                options["pool_pre_ping"] = True
    else:
        from flask_sqlalchemy import SQLAlchemy
    db = SQLAlchemy()
    import flask_user
    UserMixin = flask_user.UserMixin
    return db 
Example #3
Source File: test_flask_sqlalchemy.py    From scout_apm_python with MIT License 6 votes vote down vote up
def app_with_scout():
    with flask_app_with_scout() as app:
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
        app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
        db = SQLAlchemy(app)
        # Setup according to https://docs.scoutapm.com/#flask-sqlalchemy
        instrument_sqlalchemy(db)
        conn = db.engine.connect()

        @app.route("/sqlalchemy/")
        def sqlalchemy():
            result = conn.execute("SELECT 'Hello from the DB!'")
            return list(result)[0][0]

        try:
            yield app
        finally:
            conn.close() 
Example #4
Source File: instances.py    From Flask-Celery-Helper with MIT License 6 votes vote down vote up
def generate_context(config):
    """Create the Flask app context and initializes any extensions such as Celery, Redis, SQLAlchemy, etc.

    :param dict config: Partial Flask config dict from generate_config().

    :return: The Flask app instance.
    """
    flask_app = Flask(__name__)
    flask_app.config.update(config)
    flask_app.config['TESTING'] = True
    flask_app.config['CELERY_ACCEPT_CONTENT'] = ['pickle']

    if 'SQLALCHEMY_DATABASE_URI' in flask_app.config:
        db = SQLAlchemy(flask_app)
        db.engine.execute('DROP TABLE IF EXISTS celery_tasksetmeta;')
    elif 'REDIS_URL' in flask_app.config:
        redis = Redis(flask_app)
        redis.flushdb()

    Celery(flask_app)
    return flask_app 
Example #5
Source File: db.py    From orion-server with MIT License 6 votes vote down vote up
def DbClient(app, user, password, host, port, name):
    """
    Orion does not need to provide any additional abstractions over the client object created by
    SQLAlchemy. This function directly returns the object instantiated by creating a SQLAlchemy
    object from the current Flask app.

    :param app: Flask application object.
    :param user: The username of the MySQL user.
    :param password: The password of the MySQL user.
    :param host: The host of the MySQL instance.
    :param port: The port of the MySQL instance.
    :param name: The name of the MySQL database.
    :return: A SQLAlchemy object for interacting with the database.
    """
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{user}:{password}@{host}:{port}/{name}'.format(
        user=user,
        password=password,
        host=host,
        port=port,
        name=name,
    )
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    return flask_sqlalchemy.SQLAlchemy(app, session_options=session_opts) 
Example #6
Source File: models.py    From commandment with MIT License 6 votes vote down vote up
def from_model(cls, cmd: commands.Command):
        """This method turns a subclass of commands.Command into an SQLAlchemy model.
        The parameters of the command are encoded as a JSON dictionary inside the parameters column.

        Args:
              cmd (commands.Command): The command to be turned into a database model.
        Returns:
              Command: The database model, ready to be committed.
        """
        c = cls()
        assert cmd.request_type is not None
        c.request_type = cmd.request_type
        c.uuid = cmd.uuid
        c.parameters = cmd.parameters

        return c 
Example #7
Source File: test_message.py    From Flask-Validator with Mozilla Public License 2.0 6 votes vote down vote up
def setUp(self):
        app = Flask(__name__)
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        db = SQLAlchemy(app)

        class DummyModel(db.Model):
            """ SQLAlchemy Dummy Object """

            id = db.Column(db.Integer, primary_key=True)
            integer = db.Column(db.Integer)

        db.create_all()

        self.DummyModel = DummyModel
        self.define_validators()

        self.dummy = DummyModel()

        self.app = app
        self.db = db 
Example #8
Source File: model_cloudsql.py    From getting-started-python with Apache License 2.0 5 votes vote down vote up
def from_sql(row):
    """Translates a SQLAlchemy model instance into a dictionary"""
    data = row.__dict__.copy()
    data['id'] = row.id
    data.pop('_sa_instance_state')
    return data 
Example #9
Source File: service_test.py    From flaskerize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_all(db: SQLAlchemy):  # noqa
    yin: Widget = Widget(widget_id=1, name="Yin", purpose="thing 1")
    yang: Widget = Widget(widget_id=2, name="Yang", purpose="thing 2")
    db.session.add(yin)
    db.session.add(yang)
    db.session.commit()

    results: List[Widget] = WidgetService.get_all()

    assert len(results) == 2
    assert yin in results and yang in results 
Example #10
Source File: db.py    From gitmostwanted.com with MIT License 5 votes vote down vote up
def instance(app):
    """:rtype: SQLAlchemy"""
    return SQLAlchemy(app) 
Example #11
Source File: _conftest.py    From pytest-flask-sqlalchemy with MIT License 5 votes vote down vote up
def _db(app):
    '''
    Provide the transactional fixtures with access to the database via a Flask-SQLAlchemy
    database connection.
    '''
    db = SQLAlchemy(app=app)
    return db 
Example #12
Source File: test_sqla_to_intermediary.py    From eralchemy with Apache License 2.0 5 votes vote down vote up
def test_flask_sqlalchemy():
    from flask_sqlalchemy import SQLAlchemy
    from flask import Flask
    from eralchemy.main import all_to_intermediary
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    db = SQLAlchemy(app)
    model = db.Model
    model.metadata = Base.metadata
    tables, relationships = all_to_intermediary(db.Model)
    check_intermediary_representation_simple_all_table(tables, relationships) 
Example #13
Source File: models.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def token(self) -> str:
        """

        Notes
        -----
        When called on the class, returns the SQLAlchemy QueryableAttribute

        Returns
        -------
        str
            The encrypted token as a string when called on an instance.
        """
        return self._token 
Example #14
Source File: models.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def backup_code(self) -> str:
        """

        Notes
        -----
        When called on the class, returns the SQLAlchemy QueryableAttribute

        Returns
        -------
        str
            The encrypted backup code as a string when called on an instance.
        """
        return self._backup_code 
Example #15
Source File: models.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def secret_key(self) -> str:
        """

        Notes
        -----
        When called on the class, returns the SQLAlchemy QueryableAttribute

        Returns
        -------
        str
            The encrypted secret key as a string when called on an instance.
        """
        return self._secret_key 
Example #16
Source File: models.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def password(self) -> str:
        """

        Notes
        -----
        When called on the class, returns the SQLAlchemy QueryableAttribute

        Returns
        -------
        str
            The encrypted password as a string when called on an instance.
        """
        return self._password 
Example #17
Source File: init.py    From GeoHealthCheck with MIT License 5 votes vote down vote up
def init():
        # Do init once
        app = Flask(__name__)

        # Read and override configs
        app.config.from_pyfile('config_main.py')
        app.config.from_pyfile('../instance/config_site.py')
        app.config.from_envvar('GHC_SETTINGS', silent=True)

        # Global Logging config
        logging.basicConfig(level=int(app.config['GHC_LOG_LEVEL']),
                            format=app.config['GHC_LOG_FORMAT'])

        app.config['GHC_SITE_URL'] = \
            app.config['GHC_SITE_URL'].rstrip('/')

        app.secret_key = app.config['SECRET_KEY']

        App.db_instance = SQLAlchemy(app)
        App.babel_instance = Babel(app)

        # Plugins (via Docker ENV) must be list, but may have been
        # specified as comma-separated string, or older set notation
        app.config['GHC_PLUGINS'] = to_list(app.config['GHC_PLUGINS'])
        app.config['GHC_USER_PLUGINS'] = \
            to_list(app.config['GHC_USER_PLUGINS'])

        # Concatenate core- and user-Plugins
        App.plugins_instance = \
            app.config['GHC_PLUGINS'] + app.config['GHC_USER_PLUGINS']

        # Needed to find Plugins
        home_dir = os.path.dirname(os.path.abspath(__file__))
        App.home_dir = sys.path.append('%s/..' % home_dir)

        # Finally assign app-instance
        App.app_instance = app
        App.count += 1
        LOGGER.info("created GHC App instance #%d" % App.count) 
Example #18
Source File: test_flask_integration.py    From postgresql-audit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def db():
    return SQLAlchemy() 
Example #19
Source File: ghstats.py    From github-traffic-stats with Apache License 2.0 5 votes vote down vote up
def alchemyencoder(obj):
    """JSON encoder function for SQLAlchemy special classes."""
    if isinstance(obj, datetime.date):
        return obj.isoformat()
    elif isinstance(obj, decimal.Decimal):
        return float(obj)

# Set the role for the current session user 
Example #20
Source File: model_test.py    From flaskerize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_Widget_retrieve(widget: Widget, db: SQLAlchemy):  # noqa
    db.session.add(widget)
    db.session.commit()
    s = Widget.query.first()
    assert s.__dict__ == widget.__dict__ 
Example #21
Source File: __init__.py    From betterlifepsi with MIT License 5 votes vote down vote up
def init_db(flask_app):
    from flask_sqlalchemy import SQLAlchemy
    sqlalchemy = SQLAlchemy(flask_app, session_options={'autoflush': False})
    sqlalchemy.init_app(flask_app)
    Info.set_db(sqlalchemy)
    return sqlalchemy 
Example #22
Source File: service_test.py    From flaskerize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_update(db: SQLAlchemy):  # noqa
    yin: Widget = Widget(widget_id=1, name="Yin", purpose="thing 1")

    db.session.add(yin)
    db.session.commit()
    updates: WidgetInterface = dict(name="New Widget name")

    WidgetService.update(yin, updates)

    result: Widget = Widget.query.get(yin.widget_id)
    assert result.name == "New Widget name" 
Example #23
Source File: service_test.py    From flaskerize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_delete_by_id(db: SQLAlchemy):  # noqa
    yin: Widget = Widget(widget_id=1, name="Yin", purpose="thing 1")
    yang: Widget = Widget(widget_id=2, name="Yang", purpose="thing 2")
    db.session.add(yin)
    db.session.add(yang)
    db.session.commit()

    WidgetService.delete_by_id(1)
    db.session.commit()

    results: List[Widget] = Widget.query.all()

    assert len(results) == 1
    assert yin not in results and yang in results 
Example #24
Source File: service_test.py    From flaskerize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_create(db: SQLAlchemy):  # noqa

    yin: WidgetInterface = dict(name="Fancy new widget", purpose="Fancy new purpose")
    WidgetService.create(yin)
    results: List[Widget] = Widget.query.all()

    assert len(results) == 1

    for k in yin.keys():
        assert getattr(results[0], k) == yin[k] 
Example #25
Source File: database.py    From JusticeAI with MIT License 5 votes vote down vote up
def connect(app, user, password, db, host='postgresql_db'):
    if 'CI' in os.environ:
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
        return SQLAlchemy(app)
    else:
        # We connect with the help of the PostgreSQL URL
        url = 'postgresql://{user}:{password}@{host}/{db}'.format(user=user, password=password, host=host, db=db)
        app.config['SQLALCHEMY_DATABASE_URI'] = url
        db = SQLAlchemy(app)
    return db 
Example #26
Source File: manage_users.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def start_user_management(app):
    db = SQLAlchemy(app)
    Security(app)
    store = create_user_interface(db)

    db.create_all()

    prompt_for_actions(app, store, db) 
Example #27
Source File: authentication.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def add_flask_security_to_app(app, config):
    _add_configuration_to_app(app, config)

    db = SQLAlchemy(app)

    user_interface = create_user_interface(db)
    security = Security(app, user_interface)

    _add_apikey_handler(security, user_interface)
    return db, user_interface 
Example #28
Source File: test_user_role_db_interface.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.test_app = Flask(__name__)
        self.test_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
        self.test_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        self.test_app.config['SECURITY_PASSWORD_SALT'] = 'salt123'
        db = SQLAlchemy(self.test_app)
        self.db_interface = create_user_interface(db)
        Security(self.test_app, self.db_interface)
        db.create_all() 
Example #29
Source File: conftest.py    From flask-bitmapist with MIT License 5 votes vote down vote up
def sqlalchemy_db(app):
    from flask_sqlalchemy import SQLAlchemy

    db = SQLAlchemy(app)
    return db 
Example #30
Source File: models_base.py    From cloudify-manager with Apache License 2.0 5 votes vote down vote up
def _get_extension_type(desc):
    """Return the extension_type of a SQLAlchemy descriptors.

    This also handles proxy descriptors, looking up the extension type on
    the proxied-to descriptor.
    """
    extension_type = desc.extension_type
    if extension_type is NOT_EXTENSION:
        proxied_desc = getattr(desc, 'descriptor', None)
        if proxied_desc is not None:
            extension_type = proxied_desc.extension_type
    return extension_type