Skip to content
Go to file

Latest commit

* Improve Tox configuration

* Remove unused mysql Travis service

* Upgrade dev requirements

* Update documentation

* Add Pyhton 3.7 support

* sudo Travis keyword has been fully deprecated.

* No need to reimplement container_factory fixture

Git stats


Failed to load latest commit information.



DependencyProviders and utilities for nameko services to interface with a relational database using SQLAlchemy.


from nameko_sqlalchemy import Database

from .models import Model, DeclarativeBase

class Service(object):
    name = "service"

    db = Database(DeclarativeBase)

    def write_to_db(self):
        model = Model(...)
        with self.db.get_session() as session:

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

The nameko_sqlalchemy.Database DependencyProvider can be used in three ways:

As a context manager that issues a commit or rollback on exit:

def method(self):
    with self.db.get_session() as session:

To explicitly retrieve sessions that can be manually manipulated:

def method(self):
    session1 = self.db.get_session()
    session2 = self.db.get_session()

To manage a session that is lazily opened on first use and closed when the Nameko entrypoint exits:

def method(self):

The nameko_sqlalchemy.DatabaseSession DependencyProvider maintains the original interface from the early versions of the library. It behaves similarly to the third example above, except that the session is opened before the entrypoint fires, rather than lazily.

class Service:
    name = "legacy"

    session = DatabaseSession()

    def method(self):

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:



This decorator automatically retries the wrapped function when a database connection error occurs. If the optional session argument is passed it will issue a rollback on it before retrying so the transaction can be processed again. The session argument can either be the sqlalchemy.orm.session.Session or an operator.attrgetter object if the session is a class attribute.


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from nameko_sqlalchemy import transaction_retry

engine = create_engine('postgresql://username:password@localhost/test')
Session = sessionmaker(bind=engine)
db_session = Session()

def get_example_data():

example_data = get_example_data()

or using with the Database dependency provider

from sqlalchemy.ext.declarative import declarative_base
from nameko_sqlalchemy import Database, transaction_retry

DeclBase = declarative_base(name='examplebase')

class ExampleService:
    name = 'exampleservice'

    db = Database(DeclBase)

    def get_examples(self):
        with self.db.get_session() as session:
            return session.query(ExampleModel).all()

    def get_examples_with_retry_inside(self):
        with self.db.get_session() as session:
            def foo():
                return session.query(ExampleModel).all()

            return foo()

    def create_example_without_using_context_manager(self):
        session = self.db.get_session()

    def create_example_with_worker_scoped_session(self):

Optionally, the transaction may be retried multiple times with an exponential backoff delay. If given, the backoff factor is applied between attempts after the second try (most errors are resolved immediately by a second try without a delay). The applied delay will then be:

{backoff_factor} * (2 ** ({number of total retries} - 1))

seconds. The delay will never be longer than backoff_max seconds. By default, backoff is disabled (backoff_factor set to 0). Finally, if the connection has still not recovered after total tries, the error is reraised. The following code will thus wait for 0.0s, 0.2s, 0.4s, 0.8s, 1.0s before raising an error:

@transaction_retry(total=5, backoff_factor=0.1, backoff_max=1.0)
def get_example_data():

example_data = get_example_data()


Using the decorator may cause unanticipated consequences when the decorated function uses more than one transaction.

It should only be used around single transactions because all transactions inside the decorator will be re-executed if there is a connection error during any of them. Take a look at the following example:

class ExampleService:

    db = Database(DeclBase)

    def method(self):
        with self.db.get_session() as session:

        do_something()  # during this a network error occurs

        with self.db.get_session() as session:
            session.add(something_else)  # throws error because the db connection is gone, method will be executed again

Since the method is retried all of the statements are executed twice, including the ones that didn't fail. As a result of that something will be added twice. In order to avoid that one may want to do something like this:

class ExampleService:

    db = Database(DeclBase)

    def method(self):
        with self.db.get_session() as session:
            def add_two_things():


In this case the failed transaction will be rolled back (because the session is passed to the decorator) and records will not be duplicated.

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.
  • db_engine_options fixture can be overriden to provide additional keyword arguments to sqlalchemy.create_engine.
  • database fixture which is similar to db_session but can be passed as Database dependency replacement when using worker_factory or replace_dependencies.
import pytest

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

class Base(object):

DeclarativeBase = declarative_base(cls=Base)

class User(DeclarativeBase):
    __tablename__ = "users"

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

def model_base():
    return DeclarativeBase

def db_engine_options():
    return dict(client_encoding='utf8')

def test_users(db_session):
    user = User(id=1, name='Joe')
    saved_user = db_session.query(User).get(
    assert > 0
    assert == '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.

pytest test --test-db-url=sqlite:///test_db.sql
pytest test --test-db-url=mysql+mysqlconnector://root:password@localhost:3306/nameko_sqlalchemy_test

Running the tests


Some of the tests use toxiproxy to simulate network errors. In order to be able to run those tests you need a toxiproxy server to be in place. You may install it manually or by running the following command (docker is required):

make test-deps

This will setup a mysql and a toxiproxy server with a proxy set up to the database.

Running tests by using docker

Once the containers have been set up the tests can be run by running the following command:

make test

Running tests by using pytest command

Three extra parameters may be passed to pytest:

  • test-db-url: The database URL
  • toxiproxy-api-url: The url of the Toxiproxy HTTP API
  • toxiproxy-db-url: The url of the database through Toxiproxy

If toxiproxy-api-url and toxiproxy-db-url parameters are provided the tests assume that the toxiproxy endpoint is already set up to a database upstream and this proxy can be disabled and enabled via the HTTP API of toxiproxy.

pytest test \
    --test-db-url="mysql+pymysql://test_user:password@database_host:3306/nameko_sqlalchemy_test" \

if no toxiproxy-api-url and toxiproxy-db-url parameter was provided the tests that require toxiproxy will be skipped.

You can’t perform that action at this time.