mirror of
https://github.com/WGDashboard/WGDashboard-PRW.git
synced 2026-12-01 08:57:40 +00:00
2.7 KiB
2.7 KiB
description, applyTo
| description | applyTo |
|---|---|
| Use when writing or editing Python in the WGDashboard rewrite: readability-first coding style, naming, typing, logging, error handling, subprocess and SQLAlchemy rules. | src/**/*.py, tests/**/*.py, tools/**/*.py |
Python style – readability first
The legacy code (reference/) is compact and dense. The rewrite deliberately is not.
Rules
- No
lambda,map()orfilter(). Useforloops, or a single-level comprehension with at most one simpleif. - No nested ternaries. A ternary must fit on one short line.
- One action per line. Store intermediate results in descriptively named variables instead of chaining calls.
- Return early instead of nesting
if/else. Max ~3 indentation levels inside a function body. - Descriptive names:
peer,interface_name,allowed_ips– neverp,x,ca,iph. - Type hints on every parameter and return value.
- Functions return
tuple[bool, value]to signal success (as insrc/modules/config/config.py). Do not mix with raising for control flow. - Utility functions ALWAYS log at DEBUG. Services log INFO on state changes and ERROR on failure. Use
import logging as log. - Functions ≲ 50 lines, files ≲ 400 lines. Split by responsibility.
- Enums or module constants instead of magic strings (
PeerStatus,Protocol,JobAction). - Subprocess: list arguments only, never
shell=True, always atimeout, only insidesrc/modules/wireguard/cli.py. - SQLAlchemy 2.0 typed models (
Mapped[...],mapped_column). No SQL string formatting. - Request bodies are validated with pydantic models; respond with
make_resp_obj(status, message, data, http_code). - Keep existing conventions:
#!/bin/env python3header, snake_case,'''one-line docstrings'''.
Example
Legacy:
"ConnectedPeers": len(list(filter(lambda x: x.status == "running", self.Peers))),
Rewrite:
connected_peer_count = 0
for peer in peers:
if peer.status == PeerStatus.RUNNING:
connected_peer_count += 1
Helper style:
def find_available_addresses(network: ipaddress.IPv4Network, used_addresses: set[str], limit: int) -> list[str]:
'''Return up to `limit` host addresses in `network` that are not used yet.'''
log.debug(f"searching available addresses in {network} (limit {limit})")
available_addresses: list[str] = []
for host in network.hosts():
address = str(host)
if address in used_addresses:
continue
available_addresses.append(address)
if len(available_addresses) >= limit:
break
log.debug(f"found {len(available_addresses)} available addresses")
return available_addresses