Improve models.py documentation, small DATABASE_URL check

This commit is contained in:
2024-11-01 18:09:50 -05:00
parent cf7536a39b
commit 01f6d348cd
2 changed files with 26 additions and 6 deletions

View File

@@ -9,10 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Improved documentation in multiple areas
- Improved documentation in multiple files
- `__main__.py`
- `logging.py`
- A `get_db` utility function to retrieve a reference to the database (with type hinting).
- `models.py`
- A `get_db` utility function to retrieve a reference to the database (with type hinting)
- Minor `DATABASE_URL` check in `models.py` to prevent cryptic connection issues
### Fixed

View File

@@ -1,14 +1,32 @@
from peewee import Model, CharField, DateTimeField, IntegerField
"""models.py
This module defines the database models for the LinkPulse backend.
It also provides a base model with database connection details.
"""
from os import getenv
import structlog
from peewee import CharField, DateTimeField, IntegerField, Model
from playhouse.db_url import connect
from os import environ
logger = structlog.get_logger()
# I can't pollute the class definition with these lines, so I'll move them to a separate function.
def __get_database_url():
url = getenv("DATABASE_URL")
if url is None or url.strip() == "":
raise ValueError("DATABASE_URL is not set")
return url
class BaseModel(Model):
class Meta:
database = connect(url=environ.get("DATABASE_URL"))
# accessed via `BaseModel._meta.database`
database = connect(url=__get_database_url())
class IPAddress(BaseModel):
ip = CharField(primary_key=True)
last_seen = DateTimeField()
last_seen = DateTimeField() # timezone naive
count = IntegerField(default=0)