Skip to main content

SQLAlchemy dependency for nameko services

Project description

A SQLAlchemy dependency for nameko, enabling services to interface with a relational database.

Usage

from nameko_sqlalchemy import Session

from .models import Model, DeclarativeBase

class Service(object):

    session = Session(DeclarativeBase)

    @entrypoint
    def write_to_db(self):
        model = Model(...)
        self.session.add(model)
        self.session.commit()

    @entrypoint
    def query_db(self):
        queryset = self.session.query(Model).filter(...)
        ...

Database drivers

You may use any database driver compatible with SQLAlchemy provided it is safe to use with eventlet. This will include all pure-python drivers. Known safe drivers are:

Pytest fixtures

Pytest fixtures to allow for easy testing are available.

  • db_session fixture (which depends on db_connection fixture) will instantiate test database and tear it down at the end of each test.

  • model_base fixture can be overridden to provide custom declarative_base

import pytest

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base


class Base(object):
    pass


DeclarativeBase = declarative_base(cls=Base)


class User(DeclarativeBase):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String)


@pytest.fixture(scope='session')
def model_base():
    return DeclarativeBase


def test_users(db_session):
    user = User(id=1, name='Joe')
    db_session.add(user)
    db_session.commit()
    saved_user = db_session.query(User).get(user.id)
    assert saved_user.id > 0
    assert saved_user.name == 'Joe'

When running tests you can pass database test url with --test-db-url parameter or override db_url fixture. By default SQLite memory database will be used.

py.test test --test-db-url=sqlite:///test_db.sql

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nameko-sqlalchemy-0.0.3.tar.gz (3.8 kB view details)

Uploaded Source

File details

Details for the file nameko-sqlalchemy-0.0.3.tar.gz.

File metadata

File hashes

Hashes for nameko-sqlalchemy-0.0.3.tar.gz
Algorithm Hash digest
SHA256 dfca85ab5d7989baee68210f51c1698b6784cae1d752d93646e82c6cea835017
MD5 b4a097426123031935712852950b32c5
BLAKE2b-256 3037f9a7af2e10f94f965a58d09e329b63e3c899ead1cc419381ebf8448c9e79

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page