Skip to content

Commit

Permalink
Merge pull request #82 from igorbenav/79-datetimeutcnow-is-deprecated…
Browse files Browse the repository at this point in the history
…-as-of-python-312

79 datetimeutcnow is deprecated as of python 312
  • Loading branch information
igorbenav authored Dec 28, 2023
2 parents a9eca16 + 11786ad commit ecf206d
Show file tree
Hide file tree
Showing 11 changed files with 33 additions and 32 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ crud_users.update(db=db, object={name="Updated Name"}, username="myusername")
To delete we have two options:
- db_delete: actually deletes the row from the database
- delete:
- adds `"is_deleted": True` and `deleted_at: datetime.utcnow()` if the model inherits from `PersistentDeletion` (performs a soft delete), but keeps the object in the database.
- adds `"is_deleted": True` and `deleted_at: datetime.now(UTC)` if the model inherits from `PersistentDeletion` (performs a soft delete), but keeps the object in the database.
- actually deletes the row from the database if the model does not inherit from `PersistentDeletion`

```python
Expand Down
6 changes: 3 additions & 3 deletions src/app/core/db/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import uuid as uuid_pkg
from datetime import datetime
from datetime import datetime, UTC
from sqlalchemy import Column, DateTime, Boolean, text
from sqlalchemy.dialects.postgresql import UUID

Expand All @@ -8,8 +8,8 @@ class UUIDMixin:


class TimestampMixin:
created_at: datetime = Column(DateTime, default=datetime.utcnow, server_default=text("current_timestamp(0)"))
updated_at: datetime = Column(DateTime, nullable=True, onupdate=datetime.utcnow, server_default=text("current_timestamp(0)"))
created_at: datetime = Column(DateTime, default=datetime.now(UTC), server_default=text("current_timestamp(0)"))
updated_at: datetime = Column(DateTime, nullable=True, onupdate=datetime.now(UTC), server_default=text("current_timestamp(0)"))


class SoftDeleteMixin:
Expand Down
4 changes: 2 additions & 2 deletions src/app/core/schemas.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Any
import uuid as uuid_pkg
from datetime import datetime
from datetime import datetime, UTC

from pydantic import BaseModel, Field, field_serializer

Expand All @@ -15,7 +15,7 @@ class UUIDSchema(BaseModel):


class TimestampSchema(BaseModel):
created_at: datetime = Field(default_factory=datetime.utcnow)
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC).replace(tzinfo=None))
updated_at: datetime = Field(default=None)

@field_serializer("created_at")
Expand Down
10 changes: 5 additions & 5 deletions src/app/core/security.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Union, Literal, Dict, Any
from datetime import datetime, timedelta
from datetime import datetime, timedelta, UTC

import bcrypt
from sqlalchemy.ext.asyncio import AsyncSession
Expand Down Expand Up @@ -43,19 +43,19 @@ async def authenticate_user(username_or_email: str, password: str, db: AsyncSess
async def create_access_token(data: dict[str, Any], expires_delta: timedelta | None = None) -> str:
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
expire = datetime.now(UTC).replace(tzinfo=None) + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
expire = datetime.now(UTC).replace(tzinfo=None) + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt: str = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt

async def create_refresh_token(data: dict[str, Any], expires_delta: timedelta | None = None) -> str:
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
expire = datetime.now(UTC).replace(tzinfo=None) + expires_delta
else:
expire = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
expire = datetime.now(UTC).replace(tzinfo=None) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
to_encode.update({"exp": expire})
encoded_jwt: str = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
Expand Down
4 changes: 2 additions & 2 deletions src/app/core/utils/rate_limit.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, UTC

from redis.asyncio import Redis, ConnectionPool
from sqlalchemy.ext.asyncio import AsyncSession
Expand All @@ -22,7 +22,7 @@ async def is_rate_limited(
logger.error("Redis client is not initialized.")
raise Exception("Redis client is not initialized.")

current_timestamp = int(datetime.utcnow().timestamp())
current_timestamp = int(datetime.now(UTC).timestamp())
window_start = current_timestamp - (current_timestamp % period)

sanitized_path = sanitize_path(path)
Expand Down
6 changes: 3 additions & 3 deletions src/app/crud/crud_base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Any, Dict, Generic, List, Type, TypeVar, Union
from datetime import datetime
from datetime import datetime, UTC

from pydantic import BaseModel
from sqlalchemy import select, update, delete, func, and_, inspect
Expand Down Expand Up @@ -444,7 +444,7 @@ async def update(
update_data = object.model_dump(exclude_unset=True)

if "updated_at" in update_data.keys():
update_data["updated_at"] = datetime.utcnow()
update_data["updated_at"] = datetime.now(UTC)

stmt = update(self._model) \
.filter_by(**kwargs) \
Expand Down Expand Up @@ -503,7 +503,7 @@ async def delete(
if "is_deleted" in self._model.__table__.columns:
object_dict = {
"is_deleted": True,
"deleted_at": datetime.utcnow()
"deleted_at": datetime.now(UTC)
}
stmt = update(self._model) \
.filter_by(**kwargs) \
Expand Down
9 changes: 5 additions & 4 deletions src/app/models/post.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Optional
import uuid as uuid_pkg
from datetime import datetime
from datetime import datetime, UTC

from sqlalchemy import String, DateTime, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column
Expand All @@ -21,8 +22,8 @@ class Post(Base):
media_url: Mapped[str | None] = mapped_column(String, default=None)

created_at: Mapped[datetime] = mapped_column(
DateTime, default_factory=datetime.utcnow
DateTime(timezone=True), default_factory=lambda: datetime.now(UTC)
)
updated_at: Mapped[datetime | None] = mapped_column(default=None)
deleted_at: Mapped[datetime | None] = mapped_column(default=None)
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), default=None)
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), default=None)
is_deleted: Mapped[bool] = mapped_column(default=False, index=True)
6 changes: 3 additions & 3 deletions src/app/models/rate_limit.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Optional
from datetime import datetime
from datetime import datetime, UTC

from sqlalchemy import String, DateTime, ForeignKey, Integer
from sqlalchemy.orm import Mapped, mapped_column
Expand All @@ -19,6 +19,6 @@ class RateLimit(Base):
period: Mapped[int] = mapped_column(Integer, nullable=False)

created_at: Mapped[datetime] = mapped_column(
DateTime, default_factory=datetime.utcnow
DateTime(timezone=True), default_factory=lambda: datetime.now(UTC)
)
updated_at: Mapped[Optional[datetime]] = mapped_column(default=None)
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), default=None)
6 changes: 3 additions & 3 deletions src/app/models/tier.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Optional
from datetime import datetime
from datetime import datetime, UTC

from sqlalchemy import String, DateTime
from sqlalchemy.orm import Mapped, mapped_column
Expand All @@ -15,6 +15,6 @@ class Tier(Base):
name: Mapped[str] = mapped_column(String, nullable=False, unique=True)

created_at: Mapped[datetime] = mapped_column(
DateTime, default_factory=datetime.utcnow
DateTime(timezone=True), default_factory=lambda: datetime.now(UTC)
)
updated_at: Mapped[Optional[datetime]] = mapped_column(default=None)
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), default=None)
8 changes: 4 additions & 4 deletions src/app/models/user.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Optional
import uuid as uuid_pkg
from datetime import datetime
from datetime import datetime, UTC

from sqlalchemy import String, DateTime, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column
Expand All @@ -24,10 +24,10 @@ class User(Base):
default_factory=uuid_pkg.uuid4, primary_key=True, unique=True
)
created_at: Mapped[datetime] = mapped_column(
DateTime, default_factory=datetime.utcnow
DateTime(timezone=True), default_factory=lambda: datetime.now(UTC)
)
updated_at: Mapped[Optional[datetime]] = mapped_column(default=None)
deleted_at: Mapped[Optional[datetime]] = mapped_column(default=None)
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), default=None)
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), default=None)
is_deleted: Mapped[bool] = mapped_column(default=False, index=True)
is_superuser: Mapped[bool] = mapped_column(default=False)

Expand Down
4 changes: 2 additions & 2 deletions src/scripts/create_first_superuser.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
)
from sqlalchemy.dialects.postgresql import UUID
import uuid
from datetime import datetime
from datetime import datetime, UTC

from ..app.core.db.database import async_engine
from ..app.core.db.database import AsyncSession, local_session
Expand Down Expand Up @@ -42,7 +42,7 @@ async def create_first_user(session: AsyncSession) -> None:
Column("hashed_password", String, nullable=False),
Column("profile_image_url", String, default="https://profileimageurl.com"),
Column("uuid", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True),
Column("created_at", DateTime, default=datetime.utcnow, nullable=False),
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False),
Column("updated_at", DateTime),
Column("deleted_at", DateTime),
Column("is_deleted", Boolean, default=False, index=True),
Expand Down

0 comments on commit ecf206d

Please sign in to comment.