Launch an interactive shell with Tortoise ORM context. Prefers IPython if available, falls back to ptpython. Requires at least one shell provider to be installed. Raises: CLIError: If neither IPython nor ptpython is installed
(ctx: CLIContext)
| 375 | |
| 376 | |
| 377 | async def shell(ctx: CLIContext) -> None: |
| 378 | """Launch an interactive shell with Tortoise ORM context. |
| 379 | |
| 380 | Prefers IPython if available, falls back to ptpython. |
| 381 | Requires at least one shell provider to be installed. |
| 382 | |
| 383 | Raises: |
| 384 | CLIError: If neither IPython nor ptpython is installed |
| 385 | """ |
| 386 | # Detect which shell provider is available |
| 387 | provider = _get_available_shell_provider() |
| 388 | |
| 389 | if provider is None: |
| 390 | raise utils.CLIError( |
| 391 | "No interactive shell available. Please install one of the following:\n" |
| 392 | " - IPython (recommended): pip install tortoise-orm[ipython]\n" |
| 393 | " - ptpython: pip install tortoise-orm[ptpython]\n" |
| 394 | " - Or install directly: pip install ipython (or ptpython)" |
| 395 | ) |
| 396 | |
| 397 | config = _load_config(ctx) |
| 398 | |
| 399 | # For IPython: Initialize context, prepare namespace, then launch synchronously |
| 400 | # IPython manages its own event loop for autoawait |
| 401 | if provider == ShellProvider.IPYTHON: |
| 402 | async with tortoise_cli_context(config) as tortoise_ctx: |
| 403 | # Prepare namespace with Tortoise context and useful imports |
| 404 | namespace = { |
| 405 | "Tortoise": Tortoise, |
| 406 | "tortoise": tortoise_ctx, |
| 407 | "apps": tortoise_ctx.apps, |
| 408 | } |
| 409 | # Add all models to namespace for easy access |
| 410 | if tortoise_ctx.apps: |
| 411 | for app_name, models_dict in tortoise_ctx.apps.items(): |
| 412 | for model_name, model_class in models_dict.items(): |
| 413 | namespace[model_name] = model_class |
| 414 | |
| 415 | # Launch IPython synchronously - it will manage its own event loop |
| 416 | _launch_ipython_shell(namespace) |
| 417 | else: |
| 418 | # ptpython works fine in async context |
| 419 | async with tortoise_cli_context(config) as tortoise_ctx: |
| 420 | # Prepare namespace with Tortoise context and useful imports |
| 421 | namespace = { |
| 422 | "Tortoise": Tortoise, |
| 423 | "tortoise": tortoise_ctx, |
| 424 | "apps": tortoise_ctx.apps, |
| 425 | } |
| 426 | # Add all models to namespace for easy access |
| 427 | if tortoise_ctx.apps: |
| 428 | for app_name, models_dict in tortoise_ctx.apps.items(): |
| 429 | for model_name, model_class in models_dict.items(): |
| 430 | namespace[model_name] = model_class |
| 431 | |
| 432 | await _launch_ptpython_shell(namespace) |
| 433 | |
| 434 |
no test coverage detected
searching dependent graphs…