Skip to content

Single app structure in Django using services and repositories.

Notifications You must be signed in to change notification settings

luigi370/example-app-django

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Example App - Architecture Pattern Demonstration

This is an example Django app that demonstrates the architecture pattern used in this project. It implements a simple "Post" model with full CRUD operations.

Architecture Pattern

The application follows a layered architecture with clear separation of concerns:

1. Models Layer (models/)

  • Contains Django ORM models
  • Defines database structure and relationships
  • Example: Post model with title, content, user relationship, and timestamps

2. Repository Layer (repositories/)

  • Handles all database queries and data access
  • Provides abstraction over Django ORM
  • Methods: get_posts_for_user(), get_post_by_id(), create_post(), update_post(), delete_post()

3. Service Layer (services/)

  • Contains business logic
  • Orchestrates between repositories and views
  • Handles validation, authorization, and data transformation
  • Uses DTOs for input/output

4. API Layer (api/v1/)

  • DTOs (dtos/): Pydantic models for request/response validation
    • CreatePostDto: For creating posts
    • UpdatePostDto: For updating posts
    • PostResponseDto: For API responses
  • Views (views/): REST API endpoints using Django REST Framework
    • PostListView: List all posts for authenticated user
    • PostCreateView: Create a new post
    • PostRetrieveView: Get a specific post
    • PostUpdateView: Update a post (PUT/PATCH)
    • PostDeleteView: Delete a post
  • URLs (urls.py): URL routing configuration

5. Exceptions (exceptions/)

  • Custom exception classes
  • Provides meaningful error messages and HTTP status codes
  • Examples: PostNotFoundError, PostUnauthorizedAccessError

6. Tests (tests/)

  • Comprehensive test coverage using pytest
  • Uses model_bakery for test data generation
  • Test files:
    • test_models.py: Model validation and behavior
    • test_services.py: Business logic and authorization
    • test_v1_views.py: API endpoints and integration
  • conftest.py: Shared pytest fixtures

Key Features

Dependency Injection

  • Services are injected into views using dependency_injector
  • Configured in ApplicationContainer
  • Example:
    @inject
    def __init__(
        self,
        post_service: PostService = Provide[ApplicationContainer.services.post_service],
        **kwargs: Any,
    ) -> None:

Authorization

  • Uses UserRequirementMixin for user authentication
  • Services check ownership before allowing operations
  • Only post owners can update or delete their posts

DTO Pattern

  • Pydantic DTOs for request/response validation
  • Clear separation between API layer and domain models
  • Type-safe data transformation

Error Handling

  • Custom exception hierarchy
  • HTTP status codes automatically mapped
  • Consistent error responses

File Structure

example/
├── __init__.py
├── apps.py                      # Django app configuration
├── admin.py                     # Django admin configuration
├── pagination.py                # REST framework pagination
├── models/
│   ├── __init__.py
│   └── post.py                  # Post model
├── repositories/
│   ├── __init__.py
│   └── post_repository.py       # Data access layer
├── services/
│   ├── __init__.py
│   └── post_service.py          # Business logic layer
├── api/
│   └── v1/
│       ├── __init__.py
│       ├── urls.py              # API routes
│       ├── dtos/
│       │   ├── __init__.py
│       │   └── post_dto.py      # Request/response DTOs
│       └── views/
│           ├── __init__.py
│           └── post_views.py    # API endpoints
├── exceptions/
│   ├── __init__.py
│   └── post_exceptions.py       # Custom exceptions
├── tests/
│   ├── __init__.py
│   ├── conftest.py              # Test fixtures
│   ├── test_models.py           # Model tests
│   ├── test_services.py         # Service tests
│   └── test_v1_views.py         # API tests
└── migrations/
    └── __init__.py

API Endpoints

  • GET /api/v1/example/list - List all posts for authenticated user
  • POST /api/v1/example/create - Create a new post
  • GET /api/v1/example/list/<id> - Get a specific post
  • PUT/PATCH /api/v1/example/<id>/update - Update a post
  • DELETE /api/v1/example/<id>/delete - Delete a post

Testing

Run tests with:

make test

Run tests for this app only:

pytest app/example/tests/ -v

Usage Example

To create a similar feature in your own app:

  1. Create the model in models/your_model.py
  2. Create the repository in repositories/your_repository.py
  3. Create the service in services/your_service.py
  4. Create DTOs in api/v1/dtos/your_dto.py
  5. Create views in api/v1/views/your_views.py
  6. Configure URLs in api/v1/urls.py
  7. Create custom exceptions in exceptions/your_exceptions.py
  8. Write tests in tests/
  9. Register in dependency container (see core/dependency_injector/containers.py)

Dependencies

This pattern uses:

  • Django & Django REST Framework
  • Pydantic for DTOs
  • dependency-injector for DI
  • pytest & model_bakery for testing

About

Single app structure in Django using services and repositories.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages