Skip to content

Commit 8ba8490

Browse files
authored
refactor: use asyncclick to replace click (#6)
* refactor: use asyncclick to replace click * refactor: move logic of get tortoise orm config to utils * Remove unused pass
1 parent e8b26df commit 8ba8490

File tree

5 files changed

+109
-54
lines changed

5 files changed

+109
-54
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44

55
### 0.2.0
66

7+
- Use `asyncclick` instead of `click` ([#6])
78
- Only install tomlkit for Python version less than 3.11 ([#5])
89
- Migrate lint tool from isort+black to ruff ([#5])
910
- Drop support for Python3.8 ([#4])
1011

12+
[#6]: https://github.com/tortoise/tortoise-cli/pull/6
1113
[#5]: https://github.com/tortoise/tortoise-cli/pull/5
1214
[#4]: https://github.com/tortoise/tortoise-cli/pull/4
1315

poetry.lock

Lines changed: 59 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ include = ["CHANGELOG.md", "LICENSE", "README.md"]
1010
requires-python = ">=3.9"
1111
dependencies = [
1212
"tortoise-orm",
13-
"click",
1413
"ptpython",
14+
"asyncclick (>=8.1.7,<9.0.0)",
1515
"tomlkit (>=0.11.4,<1.0.0); python_version < '3.11'",
1616
]
1717

tortoise_cli/cli.py

Lines changed: 25 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,23 @@
11
from __future__ import annotations
22

3-
import asyncio
43
import contextlib
5-
import os
64
import sys
7-
from functools import wraps
8-
from pathlib import Path
5+
from collections.abc import AsyncGenerator
96

10-
import click
7+
import asyncclick as click
118
from ptpython.repl import embed
12-
from tortoise import Tortoise
9+
from tortoise import Tortoise, connections
1310

1411
from tortoise_cli import __version__, utils
1512

16-
if sys.version_info >= (3, 11):
17-
import tomllib
18-
else:
19-
import tomlkit as tomllib
2013

21-
22-
def coro(f):
23-
@wraps(f)
24-
def wrapper(*args, **kwargs):
25-
loop = asyncio.get_event_loop()
26-
try:
27-
loop.run_until_complete(f(*args, **kwargs))
28-
finally:
29-
if f.__name__ != "cli":
30-
loop.run_until_complete(Tortoise.close_connections())
31-
32-
return wrapper
14+
@contextlib.asynccontextmanager
15+
async def aclose_tortoise() -> AsyncGenerator[None]:
16+
try:
17+
yield
18+
finally:
19+
if Tortoise._inited:
20+
await connections.close_all()
3321

3422

3523
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@@ -40,16 +28,8 @@ def wrapper(*args, **kwargs):
4028
help="TortoiseORM config dictionary path, like settings.TORTOISE_ORM",
4129
)
4230
@click.pass_context
43-
@coro
44-
async def cli(ctx: click.Context, config: str | None):
45-
if (
46-
not config
47-
and not (config := os.getenv("TORTOISE_ORM"))
48-
and (p := Path("pyproject.toml")).exists()
49-
):
50-
doc = tomllib.loads(p.read_text("utf-8"))
51-
config = doc.get("tool", {}).get("aerich", {}).get("tortoise_orm", "")
52-
if not config:
31+
async def cli(ctx: click.Context, config: str | None) -> None:
32+
if not config and not (config := utils.tortoise_orm_config()):
5333
raise click.UsageError(
5434
"You must specify TORTOISE_ORM in option or env, or config file pyproject.toml from config of aerich",
5535
ctx=ctx,
@@ -61,19 +41,19 @@ async def cli(ctx: click.Context, config: str | None):
6141

6242
@cli.command(help="Start a interactive shell.")
6343
@click.pass_context
64-
@coro
65-
async def shell(ctx: click.Context):
66-
with contextlib.suppress(EOFError, ValueError):
67-
await embed(
68-
globals=globals(),
69-
title="Tortoise Shell",
70-
vi_mode=True,
71-
return_asyncio_coroutine=True,
72-
patch_stdout=True,
73-
)
74-
75-
76-
def main():
44+
async def shell(ctx: click.Context) -> None:
45+
async with aclose_tortoise():
46+
with contextlib.suppress(EOFError, ValueError):
47+
await embed(
48+
globals=globals(),
49+
title="Tortoise Shell",
50+
vi_mode=True,
51+
return_asyncio_coroutine=True,
52+
patch_stdout=True,
53+
)
54+
55+
56+
def main() -> None:
7757
if sys.path[0] != ".":
7858
sys.path.insert(0, ".")
7959
cli()

tortoise_cli/utils.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,27 @@
11
import importlib
2+
import os
3+
import sys
4+
from pathlib import Path
25

3-
from click import BadOptionUsage, ClickException, Context
6+
from asyncclick import BadOptionUsage, ClickException, Context
7+
8+
if sys.version_info >= (3, 11):
9+
import tomllib
10+
else:
11+
import tomlkit as tomllib
12+
13+
14+
def tortoise_orm_config(file="pyproject.toml") -> str:
15+
"""
16+
get tortoise orm config from os environment variable or aerich item in pyproject.toml
17+
18+
:param file: toml file that aerich item loads from it
19+
:return: module path and var name that store the tortoise config, e.g.: 'settings.TORTOISE_ORM'
20+
"""
21+
if not (config := os.getenv("TORTOISE_ORM", "")) and (p := Path(file)).exists():
22+
doc = tomllib.loads(p.read_text("utf-8"))
23+
config = doc.get("tool", {}).get("aerich", {}).get("tortoise_orm", "")
24+
return config
425

526

627
def get_tortoise_config(ctx: Context, config: str) -> dict:

0 commit comments

Comments
 (0)