11from __future__ import annotations
22
3- import asyncio
43import contextlib
5- import os
64import 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
118from ptpython .repl import embed
12- from tortoise import Tortoise
9+ from tortoise import Tortoise , connections
1310
1411from 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 ()
0 commit comments