appkit-commons
Skill5 starsChanged 16 days agoMITView on GitHub
appkit-commons usage patterns: configuration (YAML profiles, env overrides, secrets), service registry, repository pattern, database entities, custom column types (EncryptedString, ArrayType), scheduler (APScheduler, PGQueuer), ASGI middleware (ForceHTTPSMiddleware, SecurityHeadersMiddleware), and serving apps below a shared-origin path prefix (frontend_path, public_path, cookie and storage key prefixes, OAuth redirect URLs). Apply automatically when adding new features, services, repositories, scheduled tasks, links, browser storage, or configuring the application stack.
- Reads credentials
In this repository27 other files it gives its agents.
- AGENTS.mdAGENTS.md
- llms.txtllms.txt
- appkit-commonsSkill
- boostSkill
- code-cleanupSkill
- commit-msgSkill
- create-readmeSkill
- docker-multi-stageSkill
- frontend-designSkill
- github-actions-cicdSkill
- python-clean-codeSkill
- python-codingSkill
- reflex-docsSkill
- reflex-state-and-architectureSkill
- reflex-testing-stateSkill
- releaseSkill
- runic-migrateSkill
- runic-ogmSkill
- terraform-azure-verified-modulesSkill
- terraform-refactor-moduleSkill
- terraform-run-acceptance-testsSkill
- terraform-search-importSkill
- terraform-stacksSkill
- terraform-style-guideSkill
- terraform-testSkill
- appkit-mantine-referenceSkill
- appkit-userSkill
The file
We split this skill into the rules it gives an agent
9 rules. About 0 are common, 2 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 20
Read before writing any new feature.
- Very specific: line 77
Use service_registry().get() with the exact config class.
- Very specific: line 216
Every rx.LocalStorage / rx.SessionStorage name, every key written from rx.call_script JS and every persist_key uses app_storage_key().
- Very specific: line 219
Do not set OAuth redirect_url in YAML unless you must.
- Very specific: line 227
Not prefixable (owned by Reflex / React Router): sessionStorage token, localStorage theme, last_compiled_theme, …
- Very specific: line 259
Call service_registry() inside functions/methods — never at module level.
- Very specific: line 331
Never use rx.asession() — it breaks in background tasks and callbacks outside the Reflex request lifecycle.
- Distinctive: line 381
Never store SQLAlchemy entities in Reflex state — lazy-loaded relationships fail outside the session.
- Very specific: line 401
Never use --autogenerate. Write migrations manually.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
appkit-commons Best Practices
Read before writing any new feature. Covers configuration, DI, persistence, and scheduling.
1. Configuration
App initialization pattern
Define a cached configure() function in config.py. Call it from __init__.py before anything else.
# config.py
from functools import lru_cache
from appkit_commons.configuration import BaseConfig
from appkit_commons.configuration.configuration import Configuration, Environment
from appkit_commons.registry import service_registry
class MyFeatureConfig(BaseConfig):
api_url: str | None = None
api_key: str = ""
class ApplicationConfig(BaseConfig):
version: str
name: str
logging: str
environment: Environment | None = Environment.local
my_feature: MyFeatureConfig = MyFeatureConfig()
@lru_cache(maxsize=1)
def configure() -> Configuration[ApplicationConfig]:
return service_registry().configure(ApplicationConfig, env_file=".env")# __init__.py
import logging
from dotenv import load_dotenv
from myapp.config import configure
from appkit_commons.configuration.logging import init_logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
load_dotenv(override=True)
configuration = configure()
init_logging(configuration)service_registry().configure() auto-registers every nested config object by its own type —
ApplicationConfig, MyFeatureConfig, DatabaseConfig, ServerConfig, etc. are all retrievable after this call.
Accessing config anywhere
Use service_registry().get() with the exact config class. Always call inside functions/methods, never at module level.
from appkit_commons.registry import service_registry
from myapp.config import ApplicationConfig, LlmConfig, MyFeatureConfig
# top-level app config
cfg = service_registry().get(ApplicationConfig)
log.info("Starting %s v%s", cfg.name, cfg.version)
# nested sub-config — registered automatically by configure()
llm_cfg = service_registry().get(LlmConfig)
feature_cfg = service_registry().get(MyFeatureConfig)YAML + profiles
BaseConfig loads from config.yaml first, then merges config.<profile>.yaml.
# config.yaml
app:
name: my-app
version: "1.0"
logging: configuration/logging.yaml
database:
host: localhost
name: mydb# config.development.yaml
app:
database:
echo: trueSet active profile via PROFILE=development env var. Multiple profiles merge in order.
Environment overrides
__ as nested delimiter maps to config hierarchy:
APP__DATABASE__HOST=prod-db.internal
APP__MY_FEATURE__API_KEY=secret123Secret values
Prefix with secret: to resolve at runtime through SECRET_PROVIDER:
app:
my_feature:
api_key: "secret:my-feature-api-key"SECRET_PROVIDER | Store | Name with SECRET_NAMESPACE=myapp | Extra |
local (default) | env / .env (name, NAME, NA_ME) | — | — |
macos | Keychain, account = namespace (appkit if unset) | service name | — |
windows | Credential Manager | target myapp:name | windows |
azure | Key Vault (az login + AZURE_KEY_VAULT_URL) | myapp-name | azure |
aws_ssm | SSM Parameter Store (aws login, AWS_PROFILE/AWS_REGION) | /myapp/name | aws |
Without SECRET_NAMESPACE, Azure and SSM use the bare name. Unknown providers raise ValueError. .env is loaded with override=True.
Local stores are managed with the appkit-secrets CLI (cli extra): add, update, delete, list (names only), env (shell exports), check (every secret: of configuration/ for PROFILES present; --all-profiles), completion [zsh|bash|fish|powershell] (init with eval "$(appkit-secrets completion zsh)"; completes stored names, missing config names for add, profiles).
DatabaseConfig fields
# Key fields with defaults
host: str = "localhost"
port: int = 5432
name: str = "postgres"
username: str = "postgres"
password: SecretStr = SecretStr("postgres")
encryption_key: SecretStr = SecretStr("") # required for EncryptedString columns
pool_size: int = 10
max_overflow: int = 30
echo: bool = False
ssl_mode: str = "disable"
url_override: str | None = None # override full URLServing below a path prefix (shared origin)
Several apps can share one origin (e.g. https://x/knai, https://x/alloq).
One setting drives it: reflex.frontend_path. rxconfig.py passes it to
rx.Config(frontend_path=...). Export and backend must use the same value.
# config.local.yaml
reflex:
frontend_path: /knai # leave out for the site rootDerived from it automatically:
| What | Site root | Below /knai | Override |
| Session cookie | reflex_session | knai_session | authentication.session_cookie_name |
| Local storage prefix | "" | knai_ | authentication.storage_key_prefix |
AuthenticationConfiguration.public_base_url | https://x | https://x/knai | server_url already ending in /knai |
OAuth redirect_url | <public_base_url>/oauth/<provider>/callback | same, carries /knai | oauth_providers[].redirect_url |
Helpers in appkit_commons.public_path (no Reflex import needed by callers):
from appkit_commons.public_path import (
public_path, # "/img/logo.svg" -> "/knai/img/logo.svg"; URLs unchanged
public_url, # public_url(base, "/api/x") -> "<base>/knai/api/x"
strip_public_prefix, # "/knai/login" -> "/login" (router.url.path carries it)
public_prefix, # "/knai" or ""
app_slug, # "knai" or ""
)
from appkit_user.authentication.states import app_storage_key # "knai_<name>"
rx.image(src=public_path("/img/logo.svg"))
download_url = public_path(f"/api/bpmn/diagrams/{diagram_id}/xml")
if strip_public_prefix(self.router.url.path) == "/login":
...
token: str = rx.LocalStorage(name=app_storage_key("my-key"), sync=True)
rx.link("Login", href="/login") # app relative: React Router adds the basename
return rx.redirect("/login") # sameRules:
- Page routes in
rx.link(href=...),rx.redirect(...)and@rx.page(route=...)stay app relative. React Router adds the prefix;public_path()there doubles it. - Everything the browser or server resolves without React Router gets the prefix:
asset
src, raw HTMLhref, HTTP redirects in ASGI middleware, REST/API URLs, URLs handed to JS or external services. Usepublic_path()(path) orpublic_url()(absolute URL). - Route checks on
router.url.pathgo throughstrip_public_prefix(). - Every
rx.LocalStorage/rx.SessionStoragename, every key written fromrx.call_scriptJS and everypersist_keyusesapp_storage_key(). Writer and reader must share one constant. - Do not set OAuth
redirect_urlin YAML unless you must; an explicit value is used verbatim and skips the prefix. The provider's registered callback URL must include the prefix (GitHub accepts a subpath of the registered URL, so registering the origin root covers every prefix). - Cookie and storage names are fixed at import time and baked into the export.
Re-export after changing
frontend_path. Test them in a fresh interpreter (subprocess), not in-process. - In-process tests:
appkit_commons.testing.set_public_path_prefix(monkeypatch, "/knai"). - Not prefixable (owned by Reflex / React Router): sessionStorage
token, localStoragetheme,last_compiled_theme,react-router-scroll-positions. Apps sharing one Redis also need distinctapp_names or Redis DBs.
2. Service Registry
Single IoC container. All services registered as singletons by type.
from appkit_commons.registry import service_registry
# Register (in app startup / _initialize_services, in dependency order)
registry = service_registry()
registry.register(MyService())
registry.register_as(MyProtocol, my_impl) # register under a different type
# Retrieve (anywhere)
svc = service_registry().get(MyService)
config = service_registry().get(MyFeatureConfig)
# Introspect
registry.has(MyService) # bool
registry.list_registered() # list[type]
registry.unregister(MyService)
# Tests: save and restore the registry around a test
saved = registry.snapshot()
registry.restore(saved)Call service_registry() inside functions/methods — never at module level.
Service pattern
class MyService:
def __init__(self) -> None:
self._config = service_registry().get(MyFeatureConfig)
async def do_work(self) -> str: ...3. Repository Pattern
BaseRepository[T] provides full async CRUD. Add custom methods only for queries not in the base.
Define
from appkit_commons.database.base_repository import BaseRepository
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
class MyEntityRepository(BaseRepository[MyEntity]):
@property
def model_class(self) -> type[MyEntity]:
return MyEntity
async def find_by_name(self, session: AsyncSession, name: str) -> MyEntity | None:
result = await session.execute(select(MyEntity).where(MyEntity.name == name))
return result.scalar_one_or_none()
my_entity_repo = MyEntityRepository()Full CRUD reference
from appkit_commons.database.session import get_asyncdb_session
async with get_asyncdb_session() as session:
# Create
entity = await my_entity_repo.create(session, MyEntity(name="foo"))
# Read
item = await my_entity_repo.find_by_id(session, item_id)
items = await my_entity_repo.find_all(session)
batch = await my_entity_repo.find_all_by_ids(session, [1, 2, 3])
exists = await my_entity_repo.exists_by_id(session, item_id)
total = await my_entity_repo.count(session)
# Update
entity.name = "bar"
await my_entity_repo.update(session, entity)
# Save (create or update based on id)
entity = await my_entity_repo.save(session, entity)
saved = await my_entity_repo.save_all(session, [e1, e2])
# Delete
await my_entity_repo.delete_by_id(session, item_id)
await my_entity_repo.delete(session, entity)
count = await my_entity_repo.delete_all_by_ids(session, [1, 2])
count = await my_entity_repo.delete_all(session)The session auto-commits on exit and rolls back on exception — do not call session.commit() manually.
Never use rx.asession() — it breaks in background tasks and callbacks outside the Reflex request lifecycle.
4. Database Entities
Entity + Base
from appkit_commons.database.entities import Base, Entity
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
class MyEntity(Entity, Base):
__tablename__ = "my_items"
name: Mapped[str] = mapped_column(String(200))
is_active: Mapped[bool] = mapped_column(default=True)
def to_dict(self) -> dict:
return {"id": self.id, "name": self.name, "is_active": self.is_active}Entity mixin auto-provides:
id: int— PK, auto-increment, indexedcreated: datetime— UTC, set on insert viaserver_defaultupdated: datetime— UTC, auto-updated on each change
Custom column types
from appkit_commons.database.entities import EncryptedString, ArrayType
class MyEntity(Entity, Base):
__tablename__ = "my_items"
secret_field: Mapped[str] = mapped_column(
EncryptedString
) # Fernet-encrypted at rest
tags: Mapped[list] = mapped_column(ArrayType) # native ARRAY (PG) / JSON (SQLite)EncryptedString reads cipher key from DatabaseConfig.encryption_key at runtime via service registry.
ArrayType is dialect-agnostic — no migration changes needed between PG and SQLite.
Pydantic display model (state-safe DTO)
Never store SQLAlchemy entities in Reflex state — lazy-loaded relationships fail outside the session.
from pydantic import BaseModel
class MyModel(BaseModel):
id: int
name: str
is_active: bool = True
# In event handler:
self.items = [MyModel(**e.to_dict()) for e in entities]5. Alembic Migrations
Never use --autogenerate. Write migrations manually.
down_revision must be the revision string from the previous migration file, not the filename:
# ✅ CORRECT — open the previous migration file and copy its `revision` value
revision = "3f7a2d019e5b"
down_revision = "8a6c1e2b9f04"
# ❌ WRONG — filename is not the revision ID
down_revision = "2026_05_05_add_items_table"The # Revises: comment in the module docstring must match down_revision.
6. Scheduler
Two backends: APScheduler (distributed-safe, default) and PGQueuerScheduler.
Define a scheduled service
from appkit_commons.scheduler import ScheduledService, CronTrigger, IntervalTrigger
from appkit_commons.database.session import get_asyncdb_session
class NightlyCleanupService(ScheduledService):
job_id = "nightly_cleanup"
name = "Nightly Cleanup"
@property
def trigger(self) -> CronTrigger:
return CronTrigger(hour=2, minute=0)
async def execute(self, *args, **kwargs) -> None:
async with get_asyncdb_session() as session:
await my_entity_repo.delete_old_items(session)Trigger types
# Cron — standard cron fields, all optional (default *)
CronTrigger(hour=2, minute=30) # daily at 02:30
CronTrigger(day_of_week="mon", hour=9) # every Monday 09:00
CronTrigger(minute="*/15") # every 15 minutes
# Fixed interval
IntervalTrigger(minutes=5) # every 5 minutes
IntervalTrigger(hours=1, minutes=30) # every 90 minutes
# Calendar interval (month/year-aware)
from appkit_commons.scheduler import CalendarIntervalTrigger
CalendarIntervalTrigger(months=1, day=1) # 1st of each monthRegister and start
from appkit_commons.scheduler import APScheduler
scheduler = APScheduler()
scheduler.add_service(NightlyCleanupService())
service_registry().register(scheduler)
# In app lifespan:
await scheduler.start()
# On shutdown:
await scheduler.shutdown()APScheduler auto-configures from DatabaseConfig. In multi-node deployments it coordinates via the SQL datastore so each job runs on only one node. Uses PsycopgEventBroker for real-time scheduling when PostgreSQL is available.
7. ASGI Middleware
appkit_commons.middleware holds two pure ASGI middlewares for Reflex's
api_transformer. Do not copy them into an app.
from appkit_commons.middleware import ForceHTTPSMiddleware, SecurityHeadersMiddleware
def add_security_headers(asgi_app: ASGIApp) -> ASGIApp:
return SecurityHeadersMiddleware(asgi_app)
def add_https_middleware(asgi_app: ASGIApp) -> ASGIApp:
return ForceHTTPSMiddleware(asgi_app, trusted_hosts=config.app.trusted_proxies)
rx.App(api_transformer=[create_rest_api(), add_security_headers, add_https_middleware])ForceHTTPSMiddlewaresetsscope["scheme"]fromX-Forwarded-Proto; it never redirects. Passtrusted_hosts(the proxy addresses) wherever the backend port can be reached without the proxy.SecurityHeadersMiddlewareaddsX-Content-Type-Options,Referrer-Policy,Content-Security-Policy: frame-ancestors 'self'and, on https, HSTS. Headers a route sets itself are kept. A full CSP stays with the proxy (Reflex needs inline scripts).- Reflex applies transformers in list order, each wrapping the previous. Put
SecurityHeadersMiddlewarebeforeForceHTTPSMiddleware, so it sits inside it and sees the corrected scheme when it decides on HSTS. - Tests:
BASE_SECURITY_HEADERSandHSTSare module constants; assert on them.
8. Anti-Patterns
| Anti-pattern | Correct approach |
rx.asession() in background tasks / callbacks | get_asyncdb_session() |
service_registry() at module level | Call inside functions/methods |
| SQLAlchemy entities in Reflex state | Convert to Pydantic BaseModel via to_dict() |
| Duplicating CRUD in repos | Use BaseRepository built-ins; add only custom query methods |
--autogenerate for Alembic | Write migrations manually |
| Hardcoded credentials in YAML | Use secret: prefix, resolve via get_secret() |
Bare /img/... asset src, API URLs, ASGI redirects | public_path() / public_url() |
rx.redirect(public_path("/x")) / rx.link(href=public_path("/x")) | App relative "/x"; React Router adds the prefix |
Literal rx.LocalStorage(name="...") or localStorage.setItem("...") | app_storage_key("..."), one shared constant |
Hardcoded OAuth redirect_url in config.yaml | Leave unset; derived from public_base_url |
router.url.path == "/login" | strip_public_prefix(router.url.path) == "/login" |
session.commit() inside get_asyncdb_session() block | Session auto-commits on context exit |
State._backend_var passed as prop/child, State.var = x (Reflex 0.10 descriptors) | .default_value() / State.__fields__["x"].set_default(...) |
Inherited vars written in a background task outside async with self | Wrap writes in async with self |
| Several backend versions behind a load balancer without sticky sessions | Sticky sessions; Reflex 0.10.1 reloads a stale frontend on state-tree hash mismatch |
| Non fork-safe app in production on Linux (workers fork from the imported app) | REFLEX_BACKEND_START_METHOD=spawn |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

