Skip to content

Commit

Permalink
Update to declarative model creation, fix new db creation script
Browse files Browse the repository at this point in the history
  • Loading branch information
le717 committed Jun 8, 2024
1 parent 6f5161f commit 175c54c
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 23 deletions.
13 changes: 12 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,16 @@
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
"python.testing.pytestEnabled": true,
"ruff.enable": true,
"ruff.fixAll": true,
"ruff.codeAction.fixViolation": {
"enable": true
},
"[python]": {
"diffEditor.ignoreTrimWhitespace": false,
"editor.formatOnType": true,
"editor.wordBasedSuggestions": "off",
"editor.defaultFormatter": "charliermarsh.ruff"
}}
}
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
- Create, update, and delete entries
- Linkrot checking, with Web Archive fallback url for dead links (when possible)
- Optional linkrot event logging to [Discord](https://discord.com/) channel
- Text error log fallback if disabled

### Rotting links checking

Expand Down Expand Up @@ -80,6 +79,8 @@ is kept as simple as possible.
1. Get the Discord webhook URL from the configuration and set it as the value for
the `DISCORD_WEBHOOK_URL` secret key

A text file logger for events is always configured.

## Required Secrets

- Flask secret key (`SECRET_KEY`)
Expand Down
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ indent-width = 4
[tool.ruff.lint]
preview = true

ignore = [
"RET501", # unnecessary-return-none
]

select = [
"A", # flake8-builtins
"ARG", # flake8-unused-arguments
Expand All @@ -64,6 +68,8 @@ select = [
"T20", # flake8-print
"TD", # flake8-todos
"UP", # pyupgrade

"F401",
]

[tool.ruff.format]
Expand Down
5 changes: 5 additions & 0 deletions run-app.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
#!/usr/bin/env bash
# Run database migrations
python ./scripts/make_database.py
flask db migrate
flask db seed
rm .env

# Start the application
gunicorn --bind 0.0.0.0:80 --workers 2 --log-level error --access-logfile /app/log/access.log --error-logfile /app/log/error.log wsgi:app
7 changes: 3 additions & 4 deletions scripts/make_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


from db.dummy_db import create_app
from src.core.database.schema import db
from src.core.database.schema import Base, db


def create_database() -> None:
Expand All @@ -20,12 +20,11 @@ def create_database() -> None:
# Create the database tables if needed
if not bool(inspect(db.engine).get_table_names()):
print("Creating new database...") # noqa: T201
db.create_all()
Base.metadata.create_all(db.engine)

# Tell Alembic this is a new database and
# we don't need to update it to a newer schema
alembic_cfg = Config("alembic.ini")
command.stamp(alembic_cfg, "head")
command.stamp(Config("alembic.ini"), "head")


if __name__ == "__main__":
Expand Down
58 changes: 41 additions & 17 deletions src/core/database/schema.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,56 @@
from datetime import datetime
from typing import Any

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, DateTime, Integer, String, inspect
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy.types import DateTime, String

__all__ = ["Base", "RottedLinks", "WebLink"]

db = SQLAlchemy()

# Set up the flask-sqlalchemy extension for "new-style" models
class Base(DeclarativeBase): ...

__all__ = ["WebLink"]

db = SQLAlchemy(model_class=Base)


class HelperMethods:
def as_dict(self) -> dict:
def as_dict(self) -> dict[str, Any]:
"""Return a model as a dictionary."""
return {c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs}

def update_with(self, data: dict[str, Any]) -> None:
"""Update a record with the given data."""
for k, v in data.items():
setattr(self, k, v)
return None

class WebLink(HelperMethods, db.Model):
__tablename__ = "weblinks"

id = Column(String, primary_key=True)
title = Column(String, nullable=False)
description = Column(String, nullable=False)
url = Column(String, nullable=False)
date_added = Column(DateTime, nullable=False)
is_dead = Column(Integer, nullable=False, server_default="0")
is_web_archive = Column(Integer, nullable=False, server_default="0")


class RottedLinks(HelperMethods, db.Model):
class WebLink(HelperMethods, Base):
__tablename__ = "weblinks"
__table_args__ = {"comment": "Store the webring entries."}

id: Mapped[str] = mapped_column(String, primary_key=True)
title: Mapped[str] = mapped_column(String)
description: Mapped[str] = mapped_column(String)
url: Mapped[str] = mapped_column(
String,
)
date_added: Mapped[datetime] = Column(
DateTime,
nullable=False,
default=datetime.now,
onupdate=datetime.now,
)
is_dead: Mapped[bool] = mapped_column(default=False, server_default="0")
is_web_archive: Mapped[bool] = mapped_column(default=False, server_default="0")


class RottedLinks(HelperMethods, Base):
__tablename__ = "rotted_links"
__table_args__ = {"comment": "Log rotting webring entries."}

id = Column(String, primary_key=True)
times_failed = Column(Integer, nullable=False)
id: Mapped[str] = mapped_column(String, primary_key=True)
times_failed: Mapped[int] = mapped_column(Integer)

0 comments on commit 175c54c

Please sign in to comment.