Layered architecture

RoadmapsPython

Overview

Layered architecture is a way to organize your code into separate levels, like a multi-story building. Each layer has a specific job and only talks to the layer directly below it. ```python # Layer 1: Presentation (handles user requests) def handle_user_request(user_id): return get_user_logic(user_id) # Layer 2: Business Logic (makes decisions) def get_user_logic(user_id): if user_id < 0: return 'Invalid' return fetch_from_db(user_id) # Layer 3: Data (talks to database) def fetch_from_db(user_id): return f'User {user_id} data' ``` The rule: **A layer can only call functions in the layer below it.** The presentation layer cannot talk directly to the database. Think of it like a restaurant: the waiter (presentation) takes your order to the chef (logic), and the chef gets ingredients from the pantry (data). The waiter never goes to the pantry.

It keeps code from becoming a tangled mess. If you change your database, you only rewrite the data layer, not the whole app.

Where used: Backend web applications, Enterprise software

Why learn this

Code walkthrough

def api(req):
    return logic(req)

def logic(req):
    return data(req) + ' updated'

def data(req):
    return 'record'

print(api('get'))

Focus: return logic(req)

Common mistakes

Recall questions

Understanding checks

What does this print?

processed data

The request goes from the UI, to the logic, to the DB, and then the DB returns 'data' which the logic layer modifies before giving it to the UI.

What architectural rule does this code break?

The presentation layer (`web_route`) calls the data layer (`db_query`) directly.

In a layered architecture, the top layer must go through the middle business logic layer, not skip it to talk to the DB directly.

Practice tasks

Fix the skipped layer

Modify this code so that the `handle_click` function calls `process_click` instead of talking to the database directly.

Continue learning

Previous: Package structure and __init__.py

Next: Service-repository pattern

Return to Python Roadmap