From b067cdbfb100918b2a84bcbc4b4b40936dcebedd Mon Sep 17 00:00:00 2001 From: hay-kot Date: Mon, 15 Mar 2021 21:03:21 -0800 Subject: [PATCH] export users --- mealie/db/database.py | 22 +++++++ mealie/db/models/mealplan.py | 1 - mealie/routes/mealplans/crud.py | 13 +--- mealie/services/backups/exports.py | 101 +++++++++++++---------------- 4 files changed, 70 insertions(+), 67 deletions(-) diff --git a/mealie/db/database.py b/mealie/db/database.py index 831136a5e..87f9a2786 100644 --- a/mealie/db/database.py +++ b/mealie/db/database.py @@ -5,6 +5,7 @@ from schema.settings import SiteSettings as SiteSettingsSchema from schema.sign_up import SignUpOut from schema.theme import SiteTheme from schema.user import GroupInDB, UserInDB +from sqlalchemy.orm import load_only from sqlalchemy.orm.session import Session from db.db_base import BaseDocument @@ -94,6 +95,27 @@ class _Groups(BaseDocument): self.orm_mode = True self.schema = GroupInDB + def get_meals( + self, session: Session, match_value: str, match_key: str = "name" + ) -> list[MealPlanInDB]: + """A Helper function to get the group from the database and return a sorted list of + + Args: + session (Session): SqlAlchemy Session + match_value (str): Match Value + match_key (str, optional): Match Key. Defaults to "name". + + Returns: + list[MealPlanInDB]: [description] + """ + group: GroupInDB = ( + session.query(self.sql_model) + .filter_by(**{match_key: match_value}) + .one_or_none() + ) + + return sorted(group.mealplans, key=lambda mealplan: mealplan.startDate) + class _SignUps(BaseDocument): def __init__(self) -> None: diff --git a/mealie/db/models/mealplan.py b/mealie/db/models/mealplan.py index 7ce8b3994..12d164d0a 100644 --- a/mealie/db/models/mealplan.py +++ b/mealie/db/models/mealplan.py @@ -42,7 +42,6 @@ class MealPlanModel(SqlAlchemyBase, BaseMixins): self.meals = [Meal(**meal) for meal in meals] def update(self, session, startDate, endDate, meals, uid, group) -> None: - # MealPlanModel._sql_remove_list(session, [Meal], uid) self.__init__( startDate=startDate, diff --git a/mealie/routes/mealplans/crud.py b/mealie/routes/mealplans/crud.py index 484f928ef..2d2255e41 100644 --- a/mealie/routes/mealplans/crud.py +++ b/mealie/routes/mealplans/crud.py @@ -19,9 +19,8 @@ def get_all_meals( session: Session = Depends(generate_session), ): """ Returns a list of all available Meal Plan """ - print(current_user.group) - group_entry: GroupInDB = db.groups.get(session, current_user.group, "name") - return group_entry.mealplans + + return db.groups.get_meals(session, current_user.group) @router.post("/create") @@ -65,13 +64,7 @@ def get_this_week( ): """ Returns the meal plan data for this week """ - group_in_db: GroupInDB = db.groups.get(session, current_user.group, "name") - - meals_sorted = sorted( - group_in_db.mealplans, key=lambda mealplan: mealplan.startDate - ) - - return meals_sorted[0] + return db.groups.get_meals(session, current_user.group)[0] @router.get("/today", tags=["Meal Plan"]) diff --git a/mealie/services/backups/exports.py b/mealie/services/backups/exports.py index c5ee04aa6..49b23f2ad 100644 --- a/mealie/services/backups/exports.py +++ b/mealie/services/backups/exports.py @@ -2,19 +2,21 @@ import json import shutil from datetime import datetime from pathlib import Path +from typing import Union from core.config import BACKUP_DIR, IMG_DIR, TEMP_DIR, TEMPLATE_DIR from db.database import db from db.db_setup import create_session from fastapi.logger import logger from jinja2 import Template +from pydantic.main import BaseModel from schema.recipe import Recipe class ExportDatabase: - def __init__(self, session, tag=None, templates=None) -> None: + def __init__(self, tag=None, templates=None) -> None: """Export a Mealie database. Export interacts directly with class objects and can be used - with any supported backend database platform. By default tags are timestands, and no + with any supported backend database platform. By default tags are timestamps, and no Jinja2 templates are rendered @@ -27,14 +29,9 @@ class ExportDatabase: else: export_tag = datetime.now().strftime("%Y-%b-%d") - self.session = session self.main_dir = TEMP_DIR.joinpath(export_tag) self.img_dir = self.main_dir.joinpath("images") - self.recipe_dir = self.main_dir.joinpath("recipes") - self.themes_dir = self.main_dir.joinpath("themes") - self.settings_dir = self.main_dir.joinpath("settings") self.templates_dir = self.main_dir.joinpath("templates") - self.mealplans_dir = self.main_dir.joinpath("mealplans") try: self.templates = [TEMPLATE_DIR.joinpath(x) for x in templates] @@ -45,71 +42,50 @@ class ExportDatabase: required_dirs = [ self.main_dir, self.img_dir, - self.recipe_dir, - self.themes_dir, - self.settings_dir, self.templates_dir, - self.mealplans_dir, ] for dir in required_dirs: dir.mkdir(parents=True, exist_ok=True) - def export_recipes(self): - all_recipes = db.recipes.get_all(self.session) - - for recipe in all_recipes: - recipe: Recipe - logger.info(f"Backing Up Recipes: {recipe}") - - filename = recipe.slug + ".json" - file_path = self.recipe_dir.joinpath(filename) - - ExportDatabase._write_json_file(recipe.dict(), file_path) - - if self.templates: - self._export_template(recipe) - - def _export_template(self, recipe_data: Recipe): + def export_templates(self, recipe_list: list[BaseModel]): for template_path in self.templates: + out_dir = self.templates_dir.joinpath(template_path.name) + out_dir.mkdir(parents=True, exist_ok=True) with open(template_path, "r") as f: template = Template(f.read()) - filename = recipe_data.name + template_path.suffix - out_file = self.templates_dir.joinpath(filename) + for recipe in recipe_list: + filename = recipe.slug + template_path.suffix + out_file = out_dir.joinpath(filename) - content = template.render(recipe=recipe_data) + content = template.render(recipe=recipe) - with open(out_file, "w") as f: - f.write(content) + with open(out_file, "w") as f: + f.write(content) def export_images(self): for file in IMG_DIR.iterdir(): shutil.copy(file, self.img_dir.joinpath(file.name)) - def export_settings(self): - all_settings = db.settings.get(self.session, "main") - out_file = self.settings_dir.joinpath("settings.json") - ExportDatabase._write_json_file(all_settings, out_file) + def export_items(self, items: list[BaseModel], folder_name: str, export_list=True): + items = [x.dict() for x in items] + out_dir = self.main_dir.joinpath(folder_name) + out_dir.mkdir(parents=True, exist_ok=True) - def export_themes(self): - all_themes = db.themes.get_all(self.session) - if all_themes: - out_file = self.themes_dir.joinpath("themes.json") - ExportDatabase._write_json_file(all_themes, out_file) - - def export_meals(self): - #! Problem Parseing Datetime Objects... May come back to this - meal_plans = db.meals.get_all(self.session) - if meal_plans: - meal_plans = [x.dict() for x in meal_plans] - - out_file = self.mealplans_dir.joinpath("mealplans.json") - ExportDatabase._write_json_file(meal_plans, out_file) + if export_list: + ExportDatabase._write_json_file( + items, out_dir.joinpath(f"{folder_name}.json") + ) + else: + for item in items: + ExportDatabase._write_json_file( + item, out_dir.joinpath(f"{item.get('name')}.json") + ) @staticmethod - def _write_json_file(data: dict, out_file: Path): + def _write_json_file(data: Union[dict, list], out_file: Path): json_data = json.dumps(data, indent=4, default=str) with open(out_file, "w") as f: @@ -131,19 +107,32 @@ def backup_all( export_recipes=True, export_settings=True, export_themes=True, + export_users=True, + export_groups=True, ): - db_export = ExportDatabase(session=session, tag=tag, templates=templates) + db_export = ExportDatabase(tag=tag, templates=templates) + + if export_users: + all_users = db.users.get_all(session) + db_export.export_items(all_users, "users") + + if export_groups: + all_groups = db.groups.get_all(session) + db_export.export_items(all_groups, "groups") if export_recipes: - db_export.export_recipes() + all_recipes = db.recipes.get_all(session) + db_export.export_items(all_recipes, "recipes", export_list=False) + db_export.export_templates(all_recipes) db_export.export_images() if export_settings: - db_export.export_settings() + all_settings = db.settings.get_all(session) + db_export.export_items(all_settings, "settings") if export_themes: - db_export.export_themes() - # db_export.export_meals() + all_themes = db.themes.get_all(session) + db_export.export_items(all_themes, "themes") return db_export.finish_export()