♻️Refactor App/Project
- also fix ohmyapi.core.scaffolding.startapp
This commit is contained in:
parent
69bd447374
commit
557bda6045
2 changed files with 63 additions and 62 deletions
|
|
@ -15,67 +15,6 @@ from fastapi import FastAPI, APIRouter
|
||||||
from ohmyapi.db.model import Model
|
from ohmyapi.db.model import Model
|
||||||
|
|
||||||
|
|
||||||
class App:
|
|
||||||
"""App container holding runtime data like detected models and routes."""
|
|
||||||
|
|
||||||
def __init__(self, project: "OhMyAPI Project", name: str):
|
|
||||||
self.project = project
|
|
||||||
self.name = name
|
|
||||||
|
|
||||||
# The list of module paths (e.g. "ohmyapi_auth.models") for Tortoise and Aerich
|
|
||||||
self.model_modules: List[str] = []
|
|
||||||
|
|
||||||
# The APIRouter
|
|
||||||
self.router: Optional[APIRouter] = None
|
|
||||||
|
|
||||||
# Import the app, so its __init__.py runs.
|
|
||||||
importlib.import_module(self.name)
|
|
||||||
|
|
||||||
# Load the models
|
|
||||||
try:
|
|
||||||
models_mod = importlib.import_module(f"{self.name}.models")
|
|
||||||
self.model_modules.append(f"{self.name}.models")
|
|
||||||
except ModuleNotFoundError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Locate the APIRouter
|
|
||||||
try:
|
|
||||||
routes_mod = importlib.import_module(f"{self.name}.routes")
|
|
||||||
router = getattr(routes_mod, "router", None)
|
|
||||||
if isinstance(router, APIRouter):
|
|
||||||
self.router = router
|
|
||||||
except ModuleNotFoundError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def __repr__(self):
|
|
||||||
out = ""
|
|
||||||
out += f"App: {self.name}\n"
|
|
||||||
out += f"Models:\n"
|
|
||||||
for model in self.models:
|
|
||||||
out += f" - {model.__name__}\n"
|
|
||||||
out += "Routes:\n"
|
|
||||||
for route in (self.routes or []):
|
|
||||||
out += f" - {route}\n"
|
|
||||||
return out
|
|
||||||
|
|
||||||
def __str__(self):
|
|
||||||
return self.__repr__()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def models(self) -> List[Model]:
|
|
||||||
models: List[Model] = []
|
|
||||||
for mod in self.model_modules:
|
|
||||||
models_mod = importlib.import_module(mod)
|
|
||||||
for obj in models_mod.__dict__.values():
|
|
||||||
if isinstance(obj, type) and getattr(obj, "_meta", None) is not None and obj.__name__ != 'Model':
|
|
||||||
models.append(obj)
|
|
||||||
return models
|
|
||||||
|
|
||||||
@property
|
|
||||||
def routes(self):
|
|
||||||
return self.router.routes
|
|
||||||
|
|
||||||
|
|
||||||
class Project:
|
class Project:
|
||||||
"""
|
"""
|
||||||
Project runtime loader + Tortoise/Aerich integration.
|
Project runtime loader + Tortoise/Aerich integration.
|
||||||
|
|
@ -244,3 +183,65 @@ class Project:
|
||||||
# No migrations yet, initialize then retry upgrade
|
# No migrations yet, initialize then retry upgrade
|
||||||
await c.init_db(safe=True)
|
await c.init_db(safe=True)
|
||||||
await c.upgrade()
|
await c.upgrade()
|
||||||
|
|
||||||
|
|
||||||
|
class App:
|
||||||
|
"""App container holding runtime data like detected models and routes."""
|
||||||
|
|
||||||
|
def __init__(self, project: Project, name: str):
|
||||||
|
self.project = project
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
# The list of module paths (e.g. "ohmyapi_auth.models") for Tortoise and Aerich
|
||||||
|
self.model_modules: List[str] = []
|
||||||
|
|
||||||
|
# The APIRouter
|
||||||
|
self.router: Optional[APIRouter] = None
|
||||||
|
|
||||||
|
# Import the app, so its __init__.py runs.
|
||||||
|
importlib.import_module(self.name)
|
||||||
|
|
||||||
|
# Load the models
|
||||||
|
try:
|
||||||
|
models_mod = importlib.import_module(f"{self.name}.models")
|
||||||
|
self.model_modules.append(f"{self.name}.models")
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Locate the APIRouter
|
||||||
|
try:
|
||||||
|
routes_mod = importlib.import_module(f"{self.name}.routes")
|
||||||
|
router = getattr(routes_mod, "router", None)
|
||||||
|
if isinstance(router, APIRouter):
|
||||||
|
self.router = router
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
out = ""
|
||||||
|
out += f"App: {self.name}\n"
|
||||||
|
out += f"Models:\n"
|
||||||
|
for model in self.models:
|
||||||
|
out += f" - {model.__name__}\n"
|
||||||
|
out += "Routes:\n"
|
||||||
|
for route in (self.routes or []):
|
||||||
|
out += f" - {route}\n"
|
||||||
|
return out
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.__repr__()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def models(self) -> List[Model]:
|
||||||
|
models: List[Model] = []
|
||||||
|
for mod in self.model_modules:
|
||||||
|
models_mod = importlib.import_module(mod)
|
||||||
|
for obj in models_mod.__dict__.values():
|
||||||
|
if isinstance(obj, type) and getattr(obj, "_meta", None) is not None and obj.__name__ != 'Model':
|
||||||
|
models.append(obj)
|
||||||
|
return models
|
||||||
|
|
||||||
|
@property
|
||||||
|
def routes(self):
|
||||||
|
return self.router.routes
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -55,7 +55,7 @@ def startapp(name: str, project: str):
|
||||||
"""Create a new app inside a project: templates go into <project_dir>/<name>/"""
|
"""Create a new app inside a project: templates go into <project_dir>/<name>/"""
|
||||||
target_dir = Path(project)
|
target_dir = Path(project)
|
||||||
os.makedirs(target_dir, exist_ok=True)
|
os.makedirs(target_dir, exist_ok=True)
|
||||||
render_template_dir("app", target_dir, {"project_name": project, "app_name": name}, subdir_name=name)
|
render_template_dir("app", target_dir, {"project_name": target_dir.resolve().name, "app_name": name}, subdir_name=name)
|
||||||
print(f"✅ App '{name}' created in project '{target_dir}' successfully.")
|
print(f"✅ App '{name}' created in project '{target_dir}' successfully.")
|
||||||
print(f"🔧 Remember to add '{name}' to your INSTALLED_APPS!")
|
print(f"🔧 Remember to add '{name}' to your INSTALLED_APPS!")
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue