Chore: Upgraded from psycopg2 to psycopg3

This will also change the connection strings.
Chore: Removed usage of deprecated datetime.datetime.utcnow()
This commit is contained in:
Amritanshu Agrawal 2024-04-30 11:27:01 +05:30
parent 4d9996353c
commit 43cb697737
18 changed files with 40 additions and 45 deletions

View File

@ -27,7 +27,7 @@ class Settings(BaseSettings):
if isinstance(self.SQLALCHEMY_DATABASE_URI, str): if isinstance(self.SQLALCHEMY_DATABASE_URI, str):
return self return self
self.SQLALCHEMY_DATABASE_URI = PostgresDsn.build( self.SQLALCHEMY_DATABASE_URI = PostgresDsn.build(
scheme="postgresql", scheme="postgresql+psycopg",
username=self.POSTGRES_USER, username=self.POSTGRES_USER,
password=self.POSTGRES_PASSWORD, password=self.POSTGRES_PASSWORD,
host=self.POSTGRES_SERVER, host=self.POSTGRES_SERVER,

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import datetime, timedelta from datetime import UTC, datetime, timedelta
from typing import Any from typing import Any
from fastapi import Depends, HTTPException, Security, status from fastapi import Depends, HTTPException, Security, status
@ -35,7 +35,7 @@ class TokenData(BaseModel):
def create_access_token(*, data: dict[str, Any], expires_delta: timedelta | None = None) -> str: def create_access_token(*, data: dict[str, Any], expires_delta: timedelta | None = None) -> str:
to_encode = data.copy() to_encode = data.copy()
expire = datetime.utcnow() + expires_delta if expires_delta else datetime.utcnow() + timedelta(minutes=15) expire = datetime.now(UTC) + expires_delta if expires_delta else datetime.now(UTC) + timedelta(minutes=15)
to_encode.update({"exp": expire}) to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
return encoded_jwt return encoded_jwt

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import date, datetime from datetime import UTC, date, datetime
from decimal import Decimal from decimal import Decimal
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
@ -67,7 +67,7 @@ class Attendance:
self.attendance_type = attendance_type self.attendance_type = attendance_type
self.user_id = user_id self.user_id = user_id
self.amount = amount self.amount = amount
self.creation_date = creation_date or datetime.utcnow() self.creation_date = creation_date or datetime.now(UTC)
self.is_valid = is_valid self.is_valid = is_valid
if id_ is not None: if id_ is not None:
self.id = id_ self.id = id_

View File

@ -4,7 +4,7 @@ import random
import string import string
import uuid import uuid
from datetime import datetime from datetime import UTC, datetime
from sqlalchemy import Boolean, DateTime, Integer, Unicode, Uuid, desc from sqlalchemy import Boolean, DateTime, Integer, Unicode, Uuid, desc
from sqlalchemy.orm import Mapped, Session, mapped_column, relationship from sqlalchemy.orm import Mapped, Session, mapped_column, relationship
@ -41,7 +41,7 @@ class Client:
self.name = name self.name = name
self.enabled = enabled self.enabled = enabled
self.otp = otp self.otp = otp
self.creation_date = datetime.utcnow() if creation_date is None else creation_date self.creation_date = datetime.now(UTC) if creation_date is None else creation_date
if id_ is not None: if id_ is not None:
self.id = id_ self.id = id_

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import datetime from datetime import UTC, datetime
from sqlalchemy import DateTime, LargeBinary, Unicode, Uuid from sqlalchemy import DateTime, LargeBinary, Unicode, Uuid
from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.orm import Mapped, mapped_column
@ -32,6 +32,6 @@ class DbImage:
self.resource_type = resource_type self.resource_type = resource_type
self.image = image self.image = image
self.thumbnail = thumbnail self.thumbnail = thumbnail
self.creation_date = creation_date or datetime.utcnow() self.creation_date = creation_date or datetime.now(UTC)
if id_ is not None: if id_ is not None:
self.id = id_ self.id = id_

View File

@ -1,6 +1,6 @@
import datetime
import uuid import uuid
from datetime import UTC, datetime
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from sqlalchemy import DateTime, UniqueConstraint, Uuid from sqlalchemy import DateTime, UniqueConstraint, Uuid
@ -26,7 +26,7 @@ class LoginHistory:
ForeignKey("clients.id"), ForeignKey("clients.id"),
nullable=False, nullable=False,
) )
date: Mapped[datetime.datetime] = mapped_column(DateTime(), nullable=False) date: Mapped[datetime] = mapped_column(DateTime(), nullable=False)
user: Mapped["User"] = relationship("User", back_populates="login_history") user: Mapped["User"] = relationship("User", back_populates="login_history")
client: Mapped["Client"] = relationship("Client", back_populates="login_history") client: Mapped["Client"] = relationship("Client", back_populates="login_history")
@ -35,11 +35,11 @@ class LoginHistory:
self, self,
user_id: uuid.UUID, user_id: uuid.UUID,
client_id: uuid.UUID, client_id: uuid.UUID,
date: datetime.datetime | None = None, date: datetime | None = None,
id_: uuid.UUID | None = None, id_: uuid.UUID | None = None,
) -> None: ) -> None:
self.user_id = user_id self.user_id = user_id
self.client_id = client_id self.client_id = client_id
self.date = datetime.datetime.utcnow() if date is None else date self.date = datetime.now(UTC) if date is None else date
if id_ is not None: if id_ is not None:
self.id = id_ self.id = id_

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import date, datetime from datetime import UTC, date, datetime
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from sqlalchemy import Date, DateTime, ForeignKey, Unicode, Uuid from sqlalchemy import Date, DateTime, ForeignKey, Unicode, Uuid
@ -52,7 +52,7 @@ class RateContract:
self.valid_till = valid_till self.valid_till = valid_till
self.narration = narration self.narration = narration
self.user_id = user_id self.user_id = user_id
self.creation_date = creation_date or datetime.utcnow() self.creation_date = creation_date or datetime.now(UTC)
self.last_edit_date = last_edit_date or datetime.utcnow() self.last_edit_date = last_edit_date or datetime.now(UTC)
if id_ is not None: if id_ is not None:
self.id = id_ self.id = id_

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import date, datetime from datetime import UTC, date, datetime
from typing import TYPE_CHECKING, Optional from typing import TYPE_CHECKING, Optional
from sqlalchemy import Boolean, Date, DateTime, Enum, ForeignKey, Unicode, Uuid from sqlalchemy import Boolean, Date, DateTime, Enum, ForeignKey, Unicode, Uuid
@ -72,8 +72,8 @@ class Voucher:
self.is_starred = is_starred if is_starred is not None else False self.is_starred = is_starred if is_starred is not None else False
self.narration = narration self.narration = narration
self.posted = posted self.posted = posted
self.creation_date = creation_date or datetime.utcnow() self.creation_date = creation_date or datetime.now(UTC)
self.last_edit_date = last_edit_date or datetime.utcnow() self.last_edit_date = last_edit_date or datetime.now(UTC)
self.voucher_type = voucher_type self.voucher_type = voucher_type
self.user_id = user_id self.user_id = user_id
if poster_id is not None: if poster_id is not None:

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import date, datetime from datetime import UTC, date, datetime
from decimal import Decimal from decimal import Decimal
from math import ceil from math import ceil
@ -203,7 +203,7 @@ def update_voucher(id_: uuid.UUID, data: schema_in.EmployeeBenefitIn, user: User
voucher.narration = data.narration voucher.narration = data.narration
voucher.user_id = user.id_ voucher.user_id = user.id_
voucher.posted = False voucher.posted = False
voucher.last_edit_date = datetime.utcnow() voucher.last_edit_date = datetime.now(UTC)
return voucher return voucher

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import date, datetime from datetime import UTC, date, datetime
from decimal import Decimal from decimal import Decimal
from fastapi import APIRouter, Depends, HTTPException, Request, Security, status from fastapi import APIRouter, Depends, HTTPException, Request, Security, status
@ -163,7 +163,7 @@ def update_voucher(id_: uuid.UUID, data: schema_in.IncentiveIn, user: UserToken,
voucher.narration = data.narration voucher.narration = data.narration
voucher.user_id = user.id_ voucher.user_id = user.id_
voucher.posted = False voucher.posted = False
voucher.last_edit_date = datetime.utcnow() voucher.last_edit_date = datetime.now(UTC)
return voucher return voucher

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import datetime from datetime import UTC, datetime
from decimal import Decimal from decimal import Decimal
from fastapi import APIRouter, Depends, File, HTTPException, Request, Security, status from fastapi import APIRouter, Depends, File, HTTPException, Request, Security, status
@ -234,7 +234,7 @@ def update_voucher(
voucher.narration = data.narration voucher.narration = data.narration
voucher.user_id = user.id_ voucher.user_id = user.id_
voucher.posted = False voucher.posted = False
voucher.last_edit_date = datetime.utcnow() voucher.last_edit_date = datetime.now(UTC)
for item in voucher.journals: for item in voucher.journals:
if item.debit == 1: if item.debit == 1:
@ -343,7 +343,7 @@ def update_journals(
def refresh_voucher(id_: uuid.UUID, batch_id: uuid.UUID, db: Session) -> None: def refresh_voucher(id_: uuid.UUID, batch_id: uuid.UUID, db: Session) -> None:
try: try:
db.execute(update(Voucher).where(Voucher.id == id_).values(last_edit_date=datetime.utcnow())) db.execute(update(Voucher).where(Voucher.id == id_).values(last_edit_date=datetime.now(UTC)))
batch = db.execute(select(Batch).where(Batch.id == batch_id)).scalar_one() batch = db.execute(select(Batch).where(Batch.id == batch_id)).scalar_one()
db.execute( db.execute(
update(Inventory) update(Inventory)

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import datetime from datetime import UTC, datetime
from fastapi import APIRouter, Depends, File, HTTPException, Request, Security, status from fastapi import APIRouter, Depends, File, HTTPException, Request, Security, status
from sqlalchemy import distinct, select from sqlalchemy import distinct, select
@ -143,7 +143,7 @@ def update_voucher(id_: uuid.UUID, data: schema_in.JournalIn, user: UserToken, d
voucher.narration = data.narration voucher.narration = data.narration
voucher.user_id = user.id_ voucher.user_id = user.id_
voucher.posted = False voucher.posted = False
voucher.last_edit_date = datetime.utcnow() voucher.last_edit_date = datetime.now(UTC)
for i in range(len(voucher.journals), 0, -1): for i in range(len(voucher.journals), 0, -1):
item = voucher.journals[i - 1] item = voucher.journals[i - 1]

View File

@ -1,4 +1,4 @@
from datetime import datetime, timedelta from datetime import UTC, datetime, timedelta
from fastapi import ( from fastapi import (
APIRouter, APIRouter,
@ -57,14 +57,12 @@ async def login_for_access_token(
delete(LoginHistory) delete(LoginHistory)
.where( .where(
or_( or_(
LoginHistory.date < datetime.utcnow() - timedelta(days=30), LoginHistory.date < datetime.now(UTC) - timedelta(days=30),
LoginHistory.client_id.in_( LoginHistory.client_id.in_(
select(Client.id) select(Client.id).where(
.where( Client.creation_date < datetime.now(UTC) - timedelta(days=3),
Client.creation_date < datetime.utcnow() - timedelta(days=3),
Client.enabled == False, # noqa: E712 Client.enabled == False, # noqa: E712
) )
.subquery()
), ),
) )
) )
@ -72,7 +70,7 @@ async def login_for_access_token(
) )
db.execute( db.execute(
delete(Client).where( delete(Client).where(
Client.creation_date < datetime.utcnow() - timedelta(days=3), Client.creation_date < datetime.now(UTC) - timedelta(days=3),
Client.enabled == False, # noqa: E712 Client.enabled == False, # noqa: E712
) )
) )

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import date, datetime from datetime import UTC, date, datetime
from decimal import Decimal from decimal import Decimal
from fastapi import APIRouter, Depends, File, HTTPException, Request, Security, status from fastapi import APIRouter, Depends, File, HTTPException, Request, Security, status
@ -231,7 +231,7 @@ def update_voucher(id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken,
voucher.narration = data.narration voucher.narration = data.narration
voucher.user_id = user.id_ voucher.user_id = user.id_
voucher.posted = False voucher.posted = False
voucher.last_edit_date = datetime.utcnow() voucher.last_edit_date = datetime.now(UTC)
return voucher return voucher

View File

@ -1,6 +1,6 @@
import uuid import uuid
from datetime import datetime from datetime import UTC, datetime
from decimal import Decimal from decimal import Decimal
from fastapi import APIRouter, Depends, File, HTTPException, Request, Security, status from fastapi import APIRouter, Depends, File, HTTPException, Request, Security, status
@ -224,7 +224,7 @@ def update_voucher(id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken,
voucher.narration = data.narration voucher.narration = data.narration
voucher.user_id = user.id_ voucher.user_id = user.id_
voucher.posted = False voucher.posted = False
voucher.last_edit_date = datetime.utcnow() voucher.last_edit_date = datetime.now(UTC)
return voucher return voucher

View File

@ -14,10 +14,7 @@ host = os.getenv("HOST", "0.0.0.0")
port = os.getenv("PORT", "9994") port = os.getenv("PORT", "9994")
bind_env = os.getenv("BIND", None) bind_env = os.getenv("BIND", None)
use_loglevel = os.getenv("LOG_LEVEL", "info") use_loglevel = os.getenv("LOG_LEVEL", "info")
if bind_env: use_bind = bind_env if bind_env else f"{host}:{port}"
use_bind = bind_env
else:
use_bind = f"{host}:{port}"
cores = multiprocessing.cpu_count() cores = multiprocessing.cpu_count()
workers_per_core = float(workers_per_core_str) workers_per_core = float(workers_per_core_str)

View File

@ -10,7 +10,7 @@ uvicorn = {extras = ["standard"], version = "^0.23.2"}
fastapi = {extras = ["all"], version = "^0.110.1"} fastapi = {extras = ["all"], version = "^0.110.1"}
python-jose = {extras = ["cryptography"], version = "^3.3.0"} python-jose = {extras = ["cryptography"], version = "^3.3.0"}
passlib = {extras = ["bcrypt"], version = "^1.7.4"} passlib = {extras = ["bcrypt"], version = "^1.7.4"}
psycopg2-binary = "^2.9.9" psycopg = {extras = ["binary", "pool"], version = "^3.1.18"}
SQLAlchemy = "^2.0.29" SQLAlchemy = "^2.0.29"
python-multipart = "^0.0.9" python-multipart = "^0.0.9"
PyJWT = "^2.8.0" PyJWT = "^2.8.0"

View File

@ -3,7 +3,7 @@ HOST=0.0.0.0
PORT=80 PORT=80
LOG_LEVEL=WARN LOG_LEVEL=WARN
DEBUG=false DEBUG=false
SQLALCHEMY_DATABASE_URI=postgresql://postgres:123456@db:5432/brewman_{{ name }} SQLALCHEMY_DATABASE_URI=postgresql+psycopg://postgres:123456@db:5432/brewman_{{ name }}
MODULE_NAME=brewman.main MODULE_NAME=brewman.main
PROJECT_NAME=brewman PROJECT_NAME=brewman
SECRET_KEY={{ secret_key }} SECRET_KEY={{ secret_key }}