export users

This commit is contained in:
hay-kot 2021-03-15 21:03:21 -08:00
commit b067cdbfb1
4 changed files with 70 additions and 67 deletions

View file

@ -5,6 +5,7 @@ from schema.settings import SiteSettings as SiteSettingsSchema
from schema.sign_up import SignUpOut from schema.sign_up import SignUpOut
from schema.theme import SiteTheme from schema.theme import SiteTheme
from schema.user import GroupInDB, UserInDB from schema.user import GroupInDB, UserInDB
from sqlalchemy.orm import load_only
from sqlalchemy.orm.session import Session from sqlalchemy.orm.session import Session
from db.db_base import BaseDocument from db.db_base import BaseDocument
@ -94,6 +95,27 @@ class _Groups(BaseDocument):
self.orm_mode = True self.orm_mode = True
self.schema = GroupInDB 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): class _SignUps(BaseDocument):
def __init__(self) -> None: def __init__(self) -> None:

View file

@ -42,7 +42,6 @@ class MealPlanModel(SqlAlchemyBase, BaseMixins):
self.meals = [Meal(**meal) for meal in meals] self.meals = [Meal(**meal) for meal in meals]
def update(self, session, startDate, endDate, meals, uid, group) -> None: def update(self, session, startDate, endDate, meals, uid, group) -> None:
# MealPlanModel._sql_remove_list(session, [Meal], uid)
self.__init__( self.__init__(
startDate=startDate, startDate=startDate,

View file

@ -19,9 +19,8 @@ def get_all_meals(
session: Session = Depends(generate_session), session: Session = Depends(generate_session),
): ):
""" Returns a list of all available Meal Plan """ """ Returns a list of all available Meal Plan """
print(current_user.group)
group_entry: GroupInDB = db.groups.get(session, current_user.group, "name") return db.groups.get_meals(session, current_user.group)
return group_entry.mealplans
@router.post("/create") @router.post("/create")
@ -65,13 +64,7 @@ def get_this_week(
): ):
""" Returns the meal plan data for this week """ """ Returns the meal plan data for this week """
group_in_db: GroupInDB = db.groups.get(session, current_user.group, "name") return db.groups.get_meals(session, current_user.group)[0]
meals_sorted = sorted(
group_in_db.mealplans, key=lambda mealplan: mealplan.startDate
)
return meals_sorted[0]
@router.get("/today", tags=["Meal Plan"]) @router.get("/today", tags=["Meal Plan"])

View file

@ -2,19 +2,21 @@ import json
import shutil import shutil
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import Union
from core.config import BACKUP_DIR, IMG_DIR, TEMP_DIR, TEMPLATE_DIR from core.config import BACKUP_DIR, IMG_DIR, TEMP_DIR, TEMPLATE_DIR
from db.database import db from db.database import db
from db.db_setup import create_session from db.db_setup import create_session
from fastapi.logger import logger from fastapi.logger import logger
from jinja2 import Template from jinja2 import Template
from pydantic.main import BaseModel
from schema.recipe import Recipe from schema.recipe import Recipe
class ExportDatabase: 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 """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 Jinja2 templates are rendered
@ -27,14 +29,9 @@ class ExportDatabase:
else: else:
export_tag = datetime.now().strftime("%Y-%b-%d") export_tag = datetime.now().strftime("%Y-%b-%d")
self.session = session
self.main_dir = TEMP_DIR.joinpath(export_tag) self.main_dir = TEMP_DIR.joinpath(export_tag)
self.img_dir = self.main_dir.joinpath("images") 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.templates_dir = self.main_dir.joinpath("templates")
self.mealplans_dir = self.main_dir.joinpath("mealplans")
try: try:
self.templates = [TEMPLATE_DIR.joinpath(x) for x in templates] self.templates = [TEMPLATE_DIR.joinpath(x) for x in templates]
@ -45,71 +42,50 @@ class ExportDatabase:
required_dirs = [ required_dirs = [
self.main_dir, self.main_dir,
self.img_dir, self.img_dir,
self.recipe_dir,
self.themes_dir,
self.settings_dir,
self.templates_dir, self.templates_dir,
self.mealplans_dir,
] ]
for dir in required_dirs: for dir in required_dirs:
dir.mkdir(parents=True, exist_ok=True) dir.mkdir(parents=True, exist_ok=True)
def export_recipes(self): def export_templates(self, recipe_list: list[BaseModel]):
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):
for template_path in self.templates: 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: with open(template_path, "r") as f:
template = Template(f.read()) template = Template(f.read())
filename = recipe_data.name + template_path.suffix for recipe in recipe_list:
out_file = self.templates_dir.joinpath(filename) 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: with open(out_file, "w") as f:
f.write(content) f.write(content)
def export_images(self): def export_images(self):
for file in IMG_DIR.iterdir(): for file in IMG_DIR.iterdir():
shutil.copy(file, self.img_dir.joinpath(file.name)) shutil.copy(file, self.img_dir.joinpath(file.name))
def export_settings(self): def export_items(self, items: list[BaseModel], folder_name: str, export_list=True):
all_settings = db.settings.get(self.session, "main") items = [x.dict() for x in items]
out_file = self.settings_dir.joinpath("settings.json") out_dir = self.main_dir.joinpath(folder_name)
ExportDatabase._write_json_file(all_settings, out_file) out_dir.mkdir(parents=True, exist_ok=True)
def export_themes(self): if export_list:
all_themes = db.themes.get_all(self.session) ExportDatabase._write_json_file(
if all_themes: items, out_dir.joinpath(f"{folder_name}.json")
out_file = self.themes_dir.joinpath("themes.json") )
ExportDatabase._write_json_file(all_themes, out_file) else:
for item in items:
def export_meals(self): ExportDatabase._write_json_file(
#! Problem Parseing Datetime Objects... May come back to this item, out_dir.joinpath(f"{item.get('name')}.json")
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)
@staticmethod @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) json_data = json.dumps(data, indent=4, default=str)
with open(out_file, "w") as f: with open(out_file, "w") as f:
@ -131,19 +107,32 @@ def backup_all(
export_recipes=True, export_recipes=True,
export_settings=True, export_settings=True,
export_themes=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: 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() db_export.export_images()
if export_settings: if export_settings:
db_export.export_settings() all_settings = db.settings.get_all(session)
db_export.export_items(all_settings, "settings")
if export_themes: if export_themes:
db_export.export_themes() all_themes = db.themes.get_all(session)
# db_export.export_meals() db_export.export_items(all_themes, "themes")
return db_export.finish_export() return db_export.finish_export()