Skip to content

Feature: issue #385 - Resctructured to follow bigger apps layout #388

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

DimitriZC
Copy link

@DimitriZC DimitriZC commented Jun 2, 2025

This PR changes the project structure following the FastAPI layout documentation for Bigger Applications (the optional change was not implemented). Black and flake8 verifications were executed, all test passed after the structural changes.


This change is Reviewable

Summary by CodeRabbit

  • Refactor
    • Updated import paths and module references throughout the application for improved consistency and clarity.
    • Renamed router instances and variables to avoid naming conflicts and enhance readability.
    • Adjusted Docker configuration to reflect new source code structure.
  • Chores
    • Updated test configuration to match revised import paths.

Copy link

coderabbitai bot commented Jun 2, 2025

Walkthrough

The changes reorganize source code imports and references to consistently use the src/ directory as the code root. Router instances are renamed for clarity, and variable naming is improved to avoid shadowing. The Dockerfile and test configuration are updated to reflect the new structure. No functional logic is altered.

Changes

File(s) Change Summary
Dockerfile Updated COPY paths and CMD to use src/ directory for application source code.
tests/conftest.py Changed app import from main to src.main.
src/main.py Updated router imports and usage to use src.routes and renamed router variables.
src/routes/health.py, src/routes/player.py Renamed router instance from api_router to router; updated route decorators and import paths for consistency.
src/routes/player.py Renamed service module alias, introduced PLAYER_TITLE constant, renamed result variables to avoid shadowing.
src/schemas/player.py Changed Base import to use src.databases.player instead of databases.player_database.
src/services/player.py Updated model and schema imports to use absolute src. paths.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FastAPI App (src.main)
    participant Player Router (src.routes.player)
    participant Player Service (src.services.player)
    participant Player Model (src.models.player)
    participant Database

    Client->>FastAPI App (src.main): HTTP request (e.g., GET /players/{player_id})
    FastAPI App (src.main)->>Player Router: Route dispatch
    Player Router->>Player Service: Call service function (e.g., get_player)
    Player Service->>Player Model: ORM/database interaction
    Player Model->>Database: Query/Update
    Database-->>Player Model: Result
    Player Model-->>Player Service: Model instance/data
    Player Service-->>Player Router: Data/response
    Player Router-->>FastAPI App (src.main): Response
    FastAPI App (src.main)-->>Client: HTTP response
Loading

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef83ac0 and fad6cc7.

📒 Files selected for processing (7)
  • Dockerfile (2 hunks)
  • src/main.py (2 hunks)
  • src/routes/health.py (1 hunks)
  • src/routes/player.py (7 hunks)
  • src/schemas/player.py (1 hunks)
  • src/services/player.py (1 hunks)
  • tests/conftest.py (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • src/services/player.py
  • src/routes/health.py
  • src/main.py
  • src/schemas/player.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/conftest.py
  • Dockerfile
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/routes/player.py (3)
src/databases/player.py (1)
  • generate_async_session (35-43)
src/models/player.py (1)
  • PlayerModel (33-63)
src/services/player.py (6)
  • retrieve_by_id_async (68-80)
  • create_async (24-45)
  • retrieve_all_async (51-65)
  • retrieve_by_squad_number_async (83-99)
  • update_async (105-135)
  • delete_async (141-160)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (6)
src/routes/player.py (6)

25-27: LGTM! Import paths correctly updated for new structure.

The absolute import paths with src. prefix align perfectly with the restructuring to follow FastAPI's bigger applications layout. The service import alias change from player_service to player improves readability.


29-29: LGTM! Router instance renamed for consistency.

The router instance name change from api_router to router follows a cleaner naming convention and is consistent with the broader project restructuring.


35-35: Excellent addition of constant for consistency.

The PLAYER_TITLE constant eliminates string duplication across multiple route parameter definitions, improving maintainability and consistency.


40-40: Router decorators consistently updated.

All route decorators have been properly updated from @api_router to @router, maintaining consistency throughout the file.

Also applies to: 71-71, 99-99, 130-130, 166-166, 200-200


61-62: Smart variable renaming avoids shadowing.

Renaming service call result variables from player to player_res prevents shadowing of the imported player module, improving code clarity and avoiding potential confusion.

Also applies to: 124-127, 155-160, 190-193, 221-224


107-107: Good use of constant for path parameter titles.

Using the PLAYER_TITLE constant for player ID path parameters ensures consistency and makes future changes easier to maintain.

Also applies to: 173-173, 207-207

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (5)
app/services/player.py (1)

18-19: Update to absolute imports for service dependencies
Switching imports to app.models.player.PlayerModel and app.schemas.player.Player aligns with the new package layout. Consider aliasing the schema import (e.g., PlayerSchema) to avoid confusion with the ORM class.

app/routes/player.py (4)

35-35: Extracted PLAYER_TITLE constant

Nice DRY improvement. For consistency, consider extracting the squad-number title into its own constant as well.


61-66: Enhance POST /players/ to return created resource

Currently the endpoint returns a 201 with no body. For better REST semantics, you could add a response_model=PlayerModel and return the newly created object (or include a Location header). For example:

 @router.post(
-   "/players/",
-   status_code=status.HTTP_201_CREATED,
+   "/players/",
+   status_code=status.HTTP_201_CREATED,
+   response_model=PlayerModel,
 )
 ...
     await player.create_async(async_session, player_model)
     await simple_memory_cache.clear(CACHE_KEY)
+    return player_model

107-127: Add descriptive detail on 404 in GET by ID

Raising a bare 404 is fine, but including a detail message improves client feedback:

     if not player_res:
-        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
+        raise HTTPException(
+            status_code=status.HTTP_404_NOT_FOUND,
+            detail=f"Player with id={player_id} not found"
+        )
🧰 Tools
🪛 Ruff (0.11.9)

108-108: Do not perform function call Depends in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)


155-160: Factor out squad-number title into constant

For consistency with PLAYER_TITLE, consider defining PLAYER_SQUAD_TITLE = "The Squad Number of the Player" at the top and using it here:

-    squad_number: int = Path(..., title="The Squad Number of the Player"),
+    squad_number: int = Path(..., title=PLAYER_SQUAD_TITLE),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d0e44c and 52b47c7.

⛔ Files ignored due to path filters (1)
  • storage/players-sqlite3.db is excluded by !**/*.db
📒 Files selected for processing (7)
  • Dockerfile (2 hunks)
  • app/main.py (2 hunks)
  • app/routes/health.py (1 hunks)
  • app/routes/player.py (7 hunks)
  • app/schemas/player.py (1 hunks)
  • app/services/player.py (1 hunks)
  • tests/conftest.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
app/services/player.py (2)
app/models/player.py (1)
  • PlayerModel (33-63)
app/schemas/player.py (1)
  • Player (13-43)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (10)
tests/conftest.py (1)

4-4: Update import to reflect new project layout
Import path updated to use the app package. This aligns with the restructured codebase.

app/schemas/player.py (1)

10-10: Use absolute import for Base
Switch to absolute import from app.databases.player. Ensure Base is exported from that module.

app/routes/health.py (1)

10-13: Rename router instance and update decorator
Renamed api_router to router and updated the route decorator to use @router.get. This improves naming consistency across all route modules.

app/main.py (2)

15-15: Use absolute imports for route modules
Importing from app.routes aligns with the restructured package layout.


38-39: Include routers from refactored modules
Updated include_router calls to player.router and health.router. Verify that each router defines its own prefix and tags as expected.

Dockerfile (1)

81-81: Verify that app package is present for the CMD path

You updated the CMD to uvicorn app.main:app. After adjusting the COPY step, ensure that /app/app/main.py (and the rest of the app/ directory) exists in the image so this command resolves correctly.

app/routes/player.py (4)

25-27: Imports updated to absolute app. namespace

Good alignment with the new project layout—app.databases.player, app.models.player, and app.services.player now reflect the package structure. Just confirm that each module and its __init__.py (or namespace package) are in place.


29-29: Router renamed from api_router to router

This naming follows FastAPI conventions and matches the changes in app/main.py. No further action needed.


173-195: PUT /players/{player_id} behavior is correct

The handler checks existence, updates the record, clears the cache, and implicitly returns 204 No Content. This aligns with the API contract.

🧰 Tools
🪛 Ruff (0.11.9)

174-174: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)


175-175: Do not perform function call Depends in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)


207-226: DELETE /players/{player_id} behavior is correct

The handler verifies the entity exists, performs deletion, clears the cache, and returns 204 No Content. Well-implemented.

🧰 Tools
🪛 Ruff (0.11.9)

208-208: Do not perform function call Depends in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

Dockerfile Outdated
Comment on lines 48 to 55
# Copy application source code
COPY app/main.py ./
COPY app/databases/ ./databases/
COPY app/models/ ./models/
COPY app/routes/ ./routes/
COPY app/schemas/ ./schemas/
COPY app/services/ ./services/

Copy link

@coderabbitai coderabbitai bot Jun 2, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Dockerfile flattens app package, breaking imports

The current COPY commands break the app package hierarchy by installing subdirectories directly under /app. Since the code uses imports like app.main and app.models, there must be a top-level app directory in the image. Without it, uvicorn app.main:app will fail at runtime.

Please replace the individual COPY instructions with one that preserves the package:

- # Copy application source code 
- COPY app/main.py            ./
- COPY app/databases/         ./databases/
- COPY app/models/            ./models/
- COPY app/routes/            ./routes/
- COPY app/schemas/           ./schemas/
- COPY app/services/          ./services/
+ # Copy entire app package with correct ownership
+ COPY --chown=fastapi:fastapi app/ ./app/
🤖 Prompt for AI Agents
In Dockerfile lines 48 to 55, the current COPY commands flatten the app package
by copying subdirectories directly into the image root, breaking imports like
app.main. To fix this, replace all individual COPY commands with a single COPY
that copies the entire app directory into the image, preserving the app package
hierarchy so that imports remain valid at runtime.

✅ Addressed in commit 589e8e6

Comment on lines 90 to 96
players = await simple_memory_cache.get(CACHE_KEY)
response.headers["X-Cache"] = "HIT"
if not players:
players = await player_service.retrieve_all_async(async_session)
players = await player.retrieve_all_async(async_session)
await simple_memory_cache.set(CACHE_KEY, players, ttl=CACHE_TTL)
response.headers["X-Cache"] = "MISS"
return players
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix cache-miss logic to distinguish empty lists

Using if not players: treats an empty list as a miss. Switch to a None check so that an empty result still counts as a valid cache hit:

-    players = await simple_memory_cache.get(CACHE_KEY)
-    response.headers["X-Cache"] = "HIT"
-    if not players:
+    players = await simple_memory_cache.get(CACHE_KEY)
+    response.headers["X-Cache"] = "HIT"
+    if players is None:
         players = await player.retrieve_all_async(async_session)
         await simple_memory_cache.set(CACHE_KEY, players, ttl=CACHE_TTL)
         response.headers["X-Cache"] = "MISS"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
players = await simple_memory_cache.get(CACHE_KEY)
response.headers["X-Cache"] = "HIT"
if not players:
players = await player_service.retrieve_all_async(async_session)
players = await player.retrieve_all_async(async_session)
await simple_memory_cache.set(CACHE_KEY, players, ttl=CACHE_TTL)
response.headers["X-Cache"] = "MISS"
return players
players = await simple_memory_cache.get(CACHE_KEY)
response.headers["X-Cache"] = "HIT"
if players is None:
players = await player.retrieve_all_async(async_session)
await simple_memory_cache.set(CACHE_KEY, players, ttl=CACHE_TTL)
response.headers["X-Cache"] = "MISS"
return players
🤖 Prompt for AI Agents
In app/routes/player.py around lines 90 to 96, the cache-miss logic incorrectly
treats an empty list as a cache miss by using 'if not players:'. Change this
condition to explicitly check for None instead, so that an empty list is
considered a valid cache hit and does not trigger a cache refresh.

@DimitriZC DimitriZC force-pushed the feature/issue-385-Restructure-to-bigger-apps-layout branch from ef83ac0 to 52b47c7 Compare June 2, 2025 22:37
Copy link

codecov bot commented Jun 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.90%. Comparing base (8d0e44c) to head (fad6cc7).

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #388      +/-   ##
==========================================
+ Coverage   89.65%   90.90%   +1.25%     
==========================================
  Files           3        4       +1     
  Lines         116      132      +16     
==========================================
+ Hits          104      120      +16     
  Misses         12       12              
Components Coverage Δ
Services ∅ <ø> (∅)
Routes ∅ <ø> (∅)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

sonarqubecloud bot commented Jun 5, 2025

@DimitriZC DimitriZC changed the title Fix: issue #385 - Resctructured to follow bigger apps layout Feature: issue #385 - Resctructured to follow bigger apps layout Jun 6, 2025
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.

1 participant