Repository navigation
Upgrade to Pydantic v2 and FastAPI lifespan events - #1
Conversation
- 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
There was a problem hiding this comment.
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,Configclass) to v2 decorators (@field_validator,@model_validator,ConfigDict) - Replaced deprecated FastAPI
@app.on_event("startup")with the@asynccontextmanagerlifespan pattern - Updated SQLAlchemy/SQLModel query patterns from
session.query()tosession.exec(select()) - Replaced
datetime.utcnow()withdatetime.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.
| if "password" in kwargs: | ||
| pw = kwargs["password"] | ||
| if isinstance(pw, str) and not pw.startswith("$2"): | ||
| kwargs["password"] = get_password_hash(pw) |
There was a problem hiding this comment.
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.
| kwargs["password"] = get_password_hash(pw) | |
| kwargs["password"] = pwd_context.hash(pw) |
| def __init__(self, **kwargs): | ||
| if "password" in kwargs: | ||
| pw = kwargs["password"] | ||
| if isinstance(pw, str) and not pw.startswith("$2"): |
There was a problem hiding this comment.
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.
| if isinstance(pw, str) and not pw.startswith("$2"): | |
| if isinstance(pw, str) and not pwd_context.identify(pw): |
| """Generate a slug from the title.""" | ||
| if self.title: | ||
| self.slug = self.title.lower().replace(" ", "-") |
There was a problem hiding this comment.
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.
| """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.") |
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
Pydantic v2 Migration
BaseModel.__init__()overrides with@field_validatorand@model_validatordecorators inContentResponseandContentIncomingConfigclass tomodel_config = ConfigDict()inContentIncomingExtra.allowwithextra="allow"in model configurationfrom_orm()calls tomodel_dump()in content and user routes.dict()calls to.model_dump()in update operationsHashedPasswordclass (Pydantic v1 validator pattern) and implemented password hashing inUser.__init__()FastAPI Lifespan Pattern
@app.on_event("startup")with@asynccontextmanagerlifespan patternDatabase Query Updates
session.query()to SQLModelsession.exec(select())pattern in user and content routesselectinload()for eager loading of User.contents relationship.first()calls after already calling.first())Datetime Improvements
datetime.utcnow()calls todatetime.now(timezone.utc)(recommended approach)Content.created_timeto use UTC timezoneBug Fixes
default=Noneto optional foreign key field in Content modelslugfield toContentIncomingmodelhttps://claude.ai/code/session_01C9P6FHhMPcwXyDJjZfdcbz