Browse Source

Add an age property to DatabaseModel

Most tables have a created_time column, so this will be usable on most
models and is more convenient and readable than always needing to
subtract from utc_now().
merge-requests/76/merge
Deimos 5 years ago
parent
commit
73457e907b
  1. 4
      tildes/tildes/models/comment/comment.py
  2. 15
      tildes/tildes/models/database_model.py
  3. 2
      tildes/tildes/models/topic/topic.py
  4. 2
      tildes/tildes/models/user/user.py

4
tildes/tildes/models/comment/comment.py

@ -115,7 +115,7 @@ class Comment(DatabaseModel):
extracted_text, length=200, truncate_at_chars=" "
)
if self.created_time and utc_now() - self.created_time > EDIT_GRACE_PERIOD:
if self.age > EDIT_GRACE_PERIOD:
self.last_edited_time = utc_now()
def __repr__(self) -> str:
@ -197,7 +197,7 @@ class Comment(DatabaseModel):
acl.append((Allow, "admin", "reply"))
acl.append((Deny, Everyone, "reply"))
if utc_now() - self.created_time < timedelta(hours=2):
if self.age < timedelta(hours=2):
acl.append((Deny, "comment.reply_slow", "reply"))
acl.append((Allow, Authenticated, "reply"))

15
tildes/tildes/models/database_model.py

@ -3,6 +3,7 @@
"""Contains the base DatabaseModel class."""
from datetime import timedelta
from typing import Any, Optional, Type, TypeVar
from marshmallow import Schema
@ -11,6 +12,8 @@ from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import MetaData
from sqlalchemy.sql.schema import Table
from tildes.lib.datetime import utc_now
ModelType = TypeVar("ModelType") # pylint: disable=invalid-name
@ -82,6 +85,18 @@ class DatabaseModelBase:
return self._schema
@property
def age(self) -> timedelta:
"""Return the model's age - requires it to have a `created_time` column."""
if not hasattr(self, "created_time"):
raise AttributeError("'age' attribute requires 'created_time' column.")
# created_time should only be None during __init__, age of 0 is reasonable
if self.created_time is None: # type: ignore
return timedelta(0)
return utc_now() - self.created_time # type: ignore
def _validate_new_value(self, attribute: str, value: Any) -> Any:
"""Validate the new value for a column.

2
tildes/tildes/models/topic/topic.py

@ -158,7 +158,7 @@ class Topic(DatabaseModel):
self._markdown = new_markdown
self.rendered_html = convert_markdown_to_safe_html(new_markdown)
if self.created_time and utc_now() - self.created_time > EDIT_GRACE_PERIOD:
if self.age > EDIT_GRACE_PERIOD:
self.last_edited_time = utc_now()
@hybrid_property

2
tildes/tildes/models/user/user.py

@ -309,7 +309,7 @@ class User(DatabaseModel):
raise ValueError("Unknown permissions format")
# give the user the "comment.label" permission if they're over a week old
if utc_now() - self.created_time > timedelta(days=7):
if self.age > timedelta(days=7):
principals.append("comment.label")
return principals

Loading…
Cancel
Save