generated from nyeki/uv-fastapi-tortoise
Initial commit
This commit is contained in:
@@ -0,0 +1 @@
|
||||
from project.db.models.example import Book as Book
|
||||
@@ -0,0 +1,26 @@
|
||||
import nanoid
|
||||
|
||||
from tortoise import fields
|
||||
|
||||
|
||||
def NanoIDField(*args, **kwargs):
|
||||
"""A nanoid DB field.
|
||||
|
||||
This is an alias for a CharField with a max length of 21 characters, using
|
||||
`nanoid.generate` as the default value generator. The arguments and keyword
|
||||
arguments are passed directly to the CharField constructor.
|
||||
|
||||
Arguments:
|
||||
*args: Positional arguments for the CharField.
|
||||
**kwargs: Keyword arguments for the CharField.
|
||||
|
||||
Returns:
|
||||
tortoise.fields.CharField: A CharField configured as a nanoid primary key.
|
||||
"""
|
||||
|
||||
return fields.CharField(
|
||||
max_length=21,
|
||||
default=nanoid.generate,
|
||||
*args,
|
||||
**kwargs,
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
from tortoise import Tortoise
|
||||
from tortoise.migrations import api as migrations
|
||||
|
||||
from project.lib import settings
|
||||
|
||||
|
||||
async def on_startup():
|
||||
"""Connects to the database and creates the missing schemas on FastAPI startup."""
|
||||
|
||||
await migrations.migrate(config=settings.DATABASE)
|
||||
await Tortoise.init(config=settings.DATABASE, _enable_global_fallback=True)
|
||||
|
||||
|
||||
async def on_shutdown():
|
||||
"""Closes the database connections on FastAPI shutdown."""
|
||||
|
||||
await Tortoise.close_connections()
|
||||
@@ -0,0 +1,16 @@
|
||||
from tortoise import fields
|
||||
from tortoise.models import Model
|
||||
|
||||
from project.db.fields import NanoIDField
|
||||
|
||||
|
||||
class Book(Model):
|
||||
id = NanoIDField(primary_key=True)
|
||||
|
||||
title = fields.CharField(max_length=255)
|
||||
author = fields.CharField(max_length=255)
|
||||
|
||||
published_at = fields.DatetimeField(null=True)
|
||||
|
||||
created_at = fields.DatetimeField(auto_now_add=True)
|
||||
updated_at = fields.DatetimeField(auto_now=True)
|
||||
Reference in New Issue
Block a user