复制 from sqlalchemy import Column, Integer, String, select, func
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqladmin import Admin, BaseView, expose
from starlette.applications import Starlette
Base = declarative_base()
engine = create_async_engine("sqlite+aiosqlite:///test.db")
Session = sessionmaker(bind=engine, class_=AsyncSession)
app = Starlette()
admin = Admin(app=app, engine=engine)
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String(length=16))
class ReportView(BaseView):
name = "报告页面"
icon = "fa-solid fa-chart-line"
@expose("/report", methods=["GET"])
async def report_page(self, request):
# async with engine.begin() as conn:
# await conn.run_sync(Base.metadata.create_all)
async with Session(expire_on_commit=False) as session:
stmt = select(func.count(User.id))
result = await session.execute(stmt)
users_count = result.scalar_one()
return await self.templates.TemplateResponse(
request,
"report.html",
context={"users_count": users_count},
)
admin.add_view(ReportView)