Skip to content

Upgrade to Pydantic v2 and FastAPI lifespan events - #1

Merged
Skogix merged 1 commit into
mainfrom
claude/review-repo-update-zfK0j
Jan 31, 2026
Merged

Skogix merged 1 commit into
mainfrom
claude/review-repo-update-zfK0j

Conversation

@Skogix

@Skogix Skogix commented Jan 31, 2026

Copy link
Copy Markdown
Collaborator

Summary

This PR modernizes the codebase by upgrading to Pydantic v2 and FastAPI's new lifespan context manager pattern, while also adding explicit version constraints to all dependencies.

Key Changes

Dependencies

  • Added explicit version constraints to all requirements (fastapi, uvicorn, sqlmodel, typer, dynaconf, jinja2, python-jose, passlib, bcrypt, python-multipart, psycopg2-binary)
  • Added explicit bcrypt dependency (>=4.0.0,<4.1.0)

Pydantic v2 Migration

  • Replaced deprecated BaseModel.__init__() overrides with @field_validator and @model_validator decorators in ContentResponse and ContentIncoming
  • Updated Config class to model_config = ConfigDict() in ContentIncoming
  • Replaced Extra.allow with extra="allow" in model configuration
  • Changed from_orm() calls to model_dump() in content and user routes
  • Changed .dict() calls to .model_dump() in update operations
  • Removed custom HashedPassword class (Pydantic v1 validator pattern) and implemented password hashing in User.__init__()

FastAPI Lifespan Pattern

  • Replaced deprecated @app.on_event("startup") with @asynccontextmanager lifespan pattern
  • Moved database initialization to the new lifespan context manager

Database Query Updates

  • Migrated from SQLAlchemy session.query() to SQLModel session.exec(select()) pattern in user and content routes
  • Added selectinload() for eager loading of User.contents relationship
  • Fixed query chaining (removed redundant .first() calls after already calling .first())

Datetime Improvements

  • Updated all datetime.utcnow() calls to datetime.now(timezone.utc) (recommended approach)
  • Updated Content.created_time to use UTC timezone

Bug Fixes

  • Fixed error message in user deletion endpoint ("Content not found" → "User not found")
  • Added explicit default=None to optional foreign key field in Content model
  • Added explicit slug field to ContentIncoming model

https://claude.ai/code/session_01C9P6FHhMPcwXyDJjZfdcbz

- Replace deprecated datetime.utcnow() with datetime.now(timezone.utc)
- Migrate HashedPassword from Pydantic V1 __get_validators__ to User.__init__
  override (SQLModel table=True models bypass Pydantic validators)
- Replace deprecated from_orm() with model_dump()-based construction
- Replace deprecated .dict() with .model_dump()
- Replace deprecated on_event("startup") with lifespan context manager
- Replace Pydantic V1 Config class/Extra with ConfigDict
- Replace __init__ overrides with field_validator/model_validator
- Standardize all DB queries to modern .exec(select()) pattern,
  fixing double .first() call bug in query_user
- Fix Content.user_id missing default=None for Pydantic V2
- Fix DetachedInstanceError by eagerly loading User.contents
- Fix wrong error message ("Content not found") in user delete endpoint
- Pin dependency versions with compatible ranges
- Pin bcrypt<4.1.0 for passlib compatibility

All 27 tests passing.

https://claude.ai/code/session_01C9P6FHhMPcwXyDJjZfdcbz
Copilot AI review requested due to automatic review settings January 31, 2026 10:12
@Skogix
Skogix merged commit a52c704 into main Jan 31, 2026
5 of 6 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR modernizes the codebase by upgrading from Pydantic v1 to v2 and adopting FastAPI's new lifespan context manager pattern. The upgrade replaces deprecated patterns with their modern equivalents while adding explicit version constraints to dependencies.

Changes:

  • Migrated from Pydantic v1 validation patterns (__init__ overrides, Config class) to v2 decorators (@field_validator, @model_validator, ConfigDict)
  • Replaced deprecated FastAPI @app.on_event("startup") with the @asynccontextmanager lifespan pattern
  • Updated SQLAlchemy/SQLModel query patterns from session.query() to session.exec(select())
  • Replaced datetime.utcnow() with datetime.now(timezone.utc) following modern best practices
  • Added explicit version constraints to all dependencies

Reviewed changes

Copilot reviewed 5 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
requirements.txt Added explicit version constraints for all dependencies (fastapi, uvicorn, sqlmodel, typer, etc.) and explicit bcrypt dependency
skogapi/security.py Removed HashedPassword class, implemented password hashing in User.__init__(), updated datetime calls, migrated to SQLModel select pattern with selectinload
skogapi/models/content.py Updated to Pydantic v2 validators (@field_validator, @model_validator), replaced Config class with ConfigDict, added explicit slug field, updated datetime to use UTC timezone
skogapi/routes/user.py Changed from_orm() to model_dump(), migrated queries to session.exec(select()), fixed error message in delete endpoint
skogapi/routes/content.py Changed from_orm() to model_dump(), replaced .dict() with .model_dump(), migrated queries to session.exec(select())
skogapi/app.py Replaced @app.on_event("startup") with @asynccontextmanager lifespan pattern

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread skogapi/security.py
if "password" in kwargs:
pw = kwargs["password"]
if isinstance(pw, str) and not pw.startswith("$2"):
kwargs["password"] = get_password_hash(pw)

Copilot AI Jan 31, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The User.__init__() method references get_password_hash() which is defined later in the same file (line 88). While this works at runtime since the function is defined before the class is instantiated, it makes the code fragile and harder to understand. Consider moving the get_password_hash() function definition before the User class, or using a different approach such as a Pydantic field validator (though this would require making User a Pydantic model rather than a SQLModel table model). Alternatively, you could extract password hashing logic into a separate module.

Suggested change
kwargs["password"] = get_password_hash(pw)
kwargs["password"] = pwd_context.hash(pw)

Copilot uses AI. Check for mistakes.
Comment thread skogapi/security.py
def __init__(self, **kwargs):
if "password" in kwargs:
pw = kwargs["password"]
if isinstance(pw, str) and not pw.startswith("$2"):

Copilot AI Jan 31, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The password hashing check not pw.startswith("$2") assumes that all bcrypt hashes start with "$2", but bcrypt hashes can have different prefixes depending on the version: "$2a$", "$2b$", "$2x$", "$2y$". The current check would fail to recognize valid hashes that start with "$2a", "$2b", "$2x", or "$2y$" as already-hashed passwords, causing them to be double-hashed. Consider using a more robust check like not pwd_context.identify(pw) or checking for the full bcrypt prefix pattern.

Suggested change
if isinstance(pw, str) and not pw.startswith("$2"):
if isinstance(pw, str) and not pwd_context.identify(pw):

Copilot uses AI. Check for mistakes.
Comment thread skogapi/models/content.py
Comment on lines 74 to 76
"""Generate a slug from the title."""
if self.title:
self.slug = self.title.lower().replace(" ", "-")

Copilot AI Jan 31, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The generate_slug model validator only sets self.slug if self.title is provided. For PATCH requests where title might not be included, or for POST requests where title might be None, the slug will remain None. When this data is used to create or update a Content object, it could cause issues if the Content model's slug field is not nullable. Consider either ensuring slug is always set to a valid value (possibly preserving the existing slug on updates), or handling the None case explicitly.

Suggested change
"""Generate a slug from the title."""
if self.title:
self.slug = self.title.lower().replace(" ", "-")
"""Generate a slug from the title when needed and validate input."""
# If a slug is already provided, do not override it.
if self.title and not self.slug:
self.slug = self.title.lower().replace(" ", "-")
# For create requests, require at least one of title or slug.
# This prevents persisting a None slug when the database/schema
# expects a non-null value.
if not self.slug and not self.title:
raise ValueError("Either 'title' or 'slug' must be provided.")

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants