add first commit

This commit is contained in:
2026-07-22 15:21:06 +08:00
commit 115312bd5e
4 changed files with 128 additions and 0 deletions
+72
View File
@@ -0,0 +1,72 @@
/target
# Byte-compiled / optimized / DLL files
__pycache__/
.pytest_cache/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
.venv/
env/
bin/
build/
develop-eggs/
dist/
eggs/
lib/
lib64/
parts/
sdist/
var/
include/
man/
venv/
*.egg-info/
.installed.cfg
*.egg
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
pip-selfcheck.json
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
# Mr Developer
.mr.developer.cfg
.project
.pydevproject
# Rope
.ropeproject
# Django stuff:
*.log
*.pot
.DS_Store
# Sphinx documentation
docs/_build/
# PyCharm
.idea/
# VSCode
.vscode/
# Pyenv
.python-version
View File
+17
View File
@@ -0,0 +1,17 @@
[build-system]
build-backend = "hatchling.build"
requires = ["hatchling"]
[project]
name = "database"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"aiosqlite>=0.22.1",
"sqlmodel>=0.0.39",
]
[tool.hatch.build.targets.wheel]
packages = ["src/chongming_database"]
+39
View File
@@ -0,0 +1,39 @@
from pathlib import Path
from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel
class Database:
def __init__(self, db_path: Path):
self._engine: AsyncEngine | None = None
self._session_maker: sessionmaker | None = None
self._db_path = db_path
self._db_path.parent.mkdir(parents=True, exist_ok=True)
async def initialize(self):
"""异步初始化,创建引擎并建立表"""
self._engine = create_async_engine(
f"sqlite+aiosqlite:///{self._db_path}",
echo=False,
future=True,
)
async with self._engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
self._session_maker = sessionmaker(
self._engine, # type: ignore
class_=AsyncSession,
expire_on_commit=False
) # type: ignore
def get_session(self):
"""返回一个异步上下文管理器,用于获取会话"""
if self._session_maker is None:
raise RuntimeError("Database not initialized")
return self._session_maker()
async def dispose(self):
"""关闭引擎,释放资源"""
if self._engine:
await self._engine.dispose()
self._engine = None
self._session_maker = None