Router Discovery

RouteMQ automatically discovers and loads route definitions from your application using a convention-based approach inspired by modern web frameworks.

Discovery Process

The RouterRegistry class handles automatic route discovery through these steps:

  1. Package Scanning: Scans the app/routers directory for Python modules

  2. Module Import: Dynamically imports each router module

  3. Router Extraction: Looks for a router variable in each module

  4. Route Merging: Combines all routes into a single master router

File Structure Convention

app/
└── routers/
    ├── __init__.py
    ├── device_routes.py      # Device-related routes
    ├── sensor_routes.py      # Sensor-related routes
    ├── alerts_routes.py      # Alert handling routes
    └── api_routes.py         # API gateway routes

Router Module Format

Each router file must export a router variable:

Discovery Configuration

Default Discovery

By default, RouterRegistry scans app.routers:

Custom Directory

You can specify a different router directory:

Module Discovery Rules

Included Modules

  • All .py files in the router directory

  • Non-package modules (files, not directories)

  • Modules that don't start with underscore (_)

Excluded Modules

  • __init__.py files

  • Private modules starting with _

  • Subdirectories (packages)

  • Files without .py extension

Example Directory Structure

Route Merging Process

Sequential Loading

Routes are loaded and merged in alphabetical order:

Route Combination

All routes from discovered modules are combined into a single router:

Conflict Resolution

  • Topic Conflicts: Later-loaded routes override earlier ones with same topic

  • Middleware Isolation: Each route maintains its own middleware chain

  • No Cross-Contamination: Routes from different files don't affect each other

Worker Process Discovery

Workers need to reload routes in separate processes:

Error Handling

Import Errors

When a router module can't be imported:

Missing Router Variable

When a module doesn't export router:

Invalid Router Type

When router variable isn't a Router instance:

Development Workflow

Adding New Routes

  1. Create new file in app/routers/

  2. Define router and routes

  3. Restart application (routes loaded at startup)

Route Organization

Group related routes in the same file:

Advanced Features

Conditional Route Loading

Load routes based on environment:

Dynamic Route Generation

Generate routes programmatically:

Logging and Debugging

Discovery Logging

RouterRegistry provides detailed logging:

Route Inspection

Debug loaded routes:

Best Practices

File Naming

Use descriptive names that group related functionality:

  • device_management.py

  • sensor_telemetry.py

  • user_authentication.py

  • routes.py

  • misc.py

Route Organization

Group routes logically within files:

Error Prevention

Always include the router variable:

Next Steps

Last updated