Core-Lib

Swap the framework. Keep the app.

Core-Lib keeps Flask, SQLAlchemy, and external services out of your business logic, so changing them doesn't mean rewriting your app.

Read the docs
$ pip install core-lib

Python 3.7+MIT licenseWorks alongside Flask, Django, FastAPI

Click any module to swap it

Y1 PWR C1C2R1R2R3C3 J1 WEB J2 DATABASE J3 CACHE J4 PAYMENTS U1 YourCoreLibyour code lives here FastAPIswapPostgreSQLswapRedisswapStripeswap

Flask to FastAPI

web/user_routes.py +3 -3
-@app.route('/api/user/<int:user_id>')+@router.get('/api/user/{user_id}')-def get_user(user_id):+def get_user(user_id: int):- return response_json(your_core_lib.user.get(user_id))+ return your_core_lib.user.get(user_id)

0 lines changed in your services, data access and service tests

Failure mode

It didn't look tightly coupled until they tried to change it.

A team built a complete production system on Play Framework 1.2. Then Play 2.0 arrived with a completely different architecture. Migrating would have cost as much as rebuilding the product, so the project was dropped.

Most Python backends drift the same way, one small shortcut at a time:

  • from flask import requestYour services import Flask's request.
  • db.session.query(User)Your business logic depends on SQLAlchemy sessions.
  • redis.Redis(host='cache')Your tests need real external services to run.

Layer stack-up

Your code in the middle. Everything else on the outside.

Core-Lib doesn't invent a new pattern. It enforces one consistently, so the structure survives past the first few months, when shortcuts start creeping in.

  1. Web framework

    Flask, Django or FastAPI. A thin layer you can replace.

  2. CoreLib

    Your application, and the single entry point for web, jobs, scripts and tests.

  3. Service

    Business logic and orchestration. It never touches a database session.

  4. DataAccess, Client, Job

    Database queries, third-party API wrappers, and background tasks.

  5. Connection

    Sessions and connection pooling, wired in at startup from config.

  6. Infrastructure

    PostgreSQL, MongoDB, Redis, Memcached, Solr, Neo4j and any HTTP API.

Working with AI

AI writes the code. You keep control.

Write with AI and you lose control of your code fast. Every session picks its own structure, and soon nobody knows how it works. With Core-Lib, all your code is written the same way, so you always know where everything is.

Your AI follows the same rules, written down in AGENTS.md and the skills.

Written by you
invoice_core_lib/
  invoice_core_lib.py
  config/
  data_layers/
    data/db/entities/
    data_access/
    service/
tests/
Generated by AI
shipping_core_lib/
  shipping_core_lib.py
  config/
  data_layers/
    data/db/entities/
    data_access/
    service/
tests/

Typical application

A complete feature in four small files.

your_core_lib/your_core_lib.py

The whole application, in one class. Web, jobs, scripts and tests all start here.

from omegaconf import DictConfig

from core_lib.cache.cache_handler_ram import CacheHandlerRam
from core_lib.core_lib import CoreLib

from your_core_lib.constants import YOUR_CORE_LIB_CACHE
from your_core_lib.data_layers.data_access.user_data_access import UserDataAccess
from your_core_lib.data_layers.service.user_service import UserService


class YourCoreLib(CoreLib):
    def __init__(self, conf: DictConfig):
        super().__init__()
        self.config = conf

        if not CoreLib.cache_registry.get(YOUR_CORE_LIB_CACHE):
            CoreLib.cache_registry.register(YOUR_CORE_LIB_CACHE, CacheHandlerRam())

        db = CoreLib.connection_factory_registry.get_or_reg(conf.core_lib.data.sqlalchemy)

        self.user = UserService(UserDataAccess(db))

your_core_lib/data_layers/service/user_service.py

Business logic. Caching and error mapping are decorators, and nothing here knows about a request or a session.

from core_lib.cache.cache_decorator import Cache
from core_lib.data_layers.service.service import Service
from core_lib.data_transform.result_to_dict import ResultToDict
from core_lib.error_handling.duplicate_error_decorator import DuplicateErrorHandler

from your_core_lib.constants import YOUR_CORE_LIB_CACHE
from your_core_lib.data_layers.data.db.entities.user import User
from your_core_lib.data_layers.data_access.user_data_access import UserDataAccess

CACHE_KEY_USER = 'your_user_{user_id}'


class UserService(Service):

    def __init__(self, user_da: UserDataAccess):
        self._user_da = user_da

    @ResultToDict()
    @DuplicateErrorHandler()
    def create(self, email: str, name: str):
        return self._user_da.create({User.email.key: email, User.name.key: name})

    @Cache(CACHE_KEY_USER, handler_name=YOUR_CORE_LIB_CACHE)
    @ResultToDict()
    def get(self, user_id: int):
        return self._user_da.get(user_id)

    @Cache(CACHE_KEY_USER, handler_name=YOUR_CORE_LIB_CACHE, invalidate=True)
    def update(self, user_id: int, data: dict):
        return self._user_da.update(user_id, data)

your_core_lib/data_layers/data_access/user_data_access.py

Create, read, update and delete come from the base class. The validator is an allow-list for every write.

from core_lib.connection.sql_alchemy_connection_factory import SqlAlchemyConnectionFactory
from core_lib.data_layers.data_access.db.crud.crud import CRUD
from core_lib.data_layers.data_access.db.crud.crud_soft_data_access import CRUDSoftDeleteDataAccess
from core_lib.rule_validator.rule_validator import RuleValidator, ValueRuleValidator

from your_core_lib.data_layers.data.db.entities.user import User

rule_validator = RuleValidator([
    ValueRuleValidator(User.email.key, str),
    ValueRuleValidator(User.name.key, str),
])


class UserDataAccess(CRUDSoftDeleteDataAccess):

    def __init__(self, db: SqlAlchemyConnectionFactory):
        CRUD.__init__(self, User, db, rule_validator)

your_core_lib/data_layers/data/db/entities/user.py

Plain SQLAlchemy. You keep writing models the way you already do.

from sqlalchemy import Column, INTEGER, VARCHAR

from core_lib.data_layers.data.db.sqlalchemy.base import Base
from core_lib.data_layers.data.db.sqlalchemy.mixins.soft_delete_mixin import SoftDeleteMixin


class User(Base, SoftDeleteMixin):

    __tablename__ = 'user'

    id = Column(INTEGER, primary_key=True, autoincrement=True)
    email = Column(VARCHAR(length=255), nullable=False)
    name = Column(VARCHAR(length=255), nullable=False)

tests/test_user_service.py

The full application on in-memory SQLite. No Docker and no services to start.

import unittest

from tests.helpers.utils import sync_create_start_core_lib
from your_core_lib.data_layers.data.db.entities.user import User


class TestUserService(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.your_core_lib = sync_create_start_core_lib()

    def test_update_is_visible_on_the_next_read(self):
        user = self.your_core_lib.user.create('reviewer@acme.example', 'Reviewer')
        user_id = user[User.id.key]

        self.assertEqual('Reviewer', self.your_core_lib.user.get(user_id)[User.name.key])

        self.your_core_lib.user.update(user_id, {User.name.key: 'Lead reviewer'})

        self.assertEqual('Lead reviewer', self.your_core_lib.user.get(user_id)[User.name.key])

These files are tested as shown. The YAML config, a one-line constants file and the test bootstrap are left out for space. Continue with the getting started guide.

Data map

Get a clear picture of where your data goes.

Every service has its job and every data access has its job. Your app makes one call, always to a wrapper service, and the wrapper calls the services it needs. Pick a table to see who writes it, who reads it, and where it leaves your app.

View the map as

Pick your data

ShopCoreLibsingle entry pointTableyour dataDataAccessits job: the queriesServiceits job: the logicWrapper serviceits job: what your app callsUserServiceregistergetcachedrenameclears cacheUserDataAccesscreategetupdateuseridemailnameProductServiceaddgetcachedrepriceclears cache · eventProductDataAccesscreategetupdateproductidnamepriceOrderServicecreategetcachedmark_shippedclears cacheOrderDataAccesscreategetupdateorderiduser_idproduct_idtotalstatusBillingServicechargeexternal APIinvoicesInvoiceDataAccesscreatefor_orderinvoiceidorder_idamountShipmentServicedispatchexternal APItrackShipmentDataAccesscreatefor_ordershipmentidorder_idtrackingReviewServicecreatefor_productReviewDataAccesscreatefor_productreviewidorder_idproduct_idratingAccountServiceregisterprofilerenameCatalogServiceaddproductrepriceCheckoutServiceplaceeventorderinvoicesFeedbackServiceposteventreviewsFulfilmentServiceshipeventtrackingyour appone callUserDataAccessUserServiceProductDataAccessProductServiceOrderDataAccessOrderServiceInvoiceDataAccessBillingServiceShipmentDataAccessShipmentServiceReviewDataAccessReviewServiceCatalogServiceCheckoutServiceFulfilmentServiceAccountServiceFeedbackServiceShopCoreLibsingle entry pointuserproductorderinvoiceshipmentreviewyour datayour appone callTableDataAccessServiceWrapper serviceFacadecreategetupdateregistergetrenameUserDataAccessUserServiceusercreategetupdateaddgetrepriceProductDataAccessProductServiceproductcreategetupdatecreategetmark_shippedOrderDataAccessOrderServiceordercreatefor_orderchargeinvoicesInvoiceDataAccessBillingServiceinvoicecreatefor_orderdispatchtrackShipmentDataAccessShipmentServiceshipmentcreatefor_productcreatefor_productReviewDataAccessReviewServicereviewregisterprofilerenameAccountServiceaddproductrepriceCatalogServiceplaceorderinvoicesCheckoutServicepostreviewsFeedbackServiceshiptrackingFulfilmentServiceShopCoreLibsingle entry pointyour appone call

order

id, user_id, product_id, total, status

Written by
through
through
Read by
through
through
Cached as
shop_order_{order_id} cleared by
Fires
order_placed
order_shipped
Used with
in
in ,
in
in
in

Each line is one call from your app. Its answer comes back along the same line.Call changes the tableCall only reads itCachedClears cacheEventLeaves the appGenerated from the code of a small sample shop library, run through three example apps: Flask, Django and FastAPI.

The code behind the map

Click any part of the map, or a name in the panel, to open its code.

Bill of materials

What's on the board.

RefPartWhat it does
U1CoreLibThe base class your application extends. One entry point for web, jobs, scripts and tests.
U2AlembicVersioned schema migrations, run with core_lib migrate or install().
J1SQLAlchemySessions and connection pooling, configured from YAML.
J2MongoDB, Neo4j, Solr, ElasticsearchConnection factories that follow the same lifecycle.
J3ClientBaseA base for HTTP API clients, with headers, auth and timeouts.
C1@CacheCache and invalidate by key template on RAM, Memcached or Redis.
Q1CRUD data accessCreate, read, update and delete, with soft-delete variants.
R1RuleValidatorAn allow-list of fields and types for every write.
T1@ResultToDictTurns entities into plain dicts your web layer can return.
F1Error handlersMap missing rows and duplicates to HTTP status codes.
Y1JobScheduled and one-shot background work, declared in config.
D1@ObserveFire events that the rest of your system can listen to.
TP1Test supportStart the full application against SQLite with a config override.
P1core_lib CLIScaffold a new library and run its migrations.

The references follow PCB convention: U for chips, J for connectors, C for storage, R for what resists bad input, F for fuses, Y for the clock.

Recommended operating conditions

Built for backends that last.

Use it when

  • Your backend will live for years, not weeks
  • Multiple engineers will touch the same codebase
  • You want to run the same logic from web, jobs, scripts, and tests
  • You need to swap infrastructure without touching business logic

Skip it when

  • Your app is a prototype, script, or simple CRUD app
  • There's no long-term maintenance expectation
  • Your app is small and unlikely to change much

It has no router

Core-Lib has no request lifecycle of its own. It works alongside Flask, Django and FastAPI, and you bring the web layer.

You keep your tools

You still write SQLAlchemy models and Redis commands. Core-Lib handles the connection lifecycle and stops those dependencies from spreading.

Put your application at the center.

Install it, answer a few questions, and start from a complete library with config, tests and a place for every layer.

$ pip install core-lib
$ core_lib generate
Read the docs