feat(backend): 🚧 stub out new exporter service (WIP) (#715)

* chore(backend): 🎨 add isort path to vscode settings

* style(frontend): 💄 remove fab and add general create button

* feat(backend): 🚧 stub out new exporter service

* comment out stub tests

Co-authored-by: Hayden <hay-kot@pm.me>
This commit is contained in:
Hayden
2021-10-02 11:37:04 -08:00
committed by GitHub
parent 476aefeeb0
commit 4bdba9f3af
26 changed files with 714 additions and 50 deletions

View File

@@ -24,11 +24,11 @@ async def get_events(session: Session = Depends(generate_session)):
async def delete_events(session: Session = Depends(generate_session)):
""" Get event from the Database """
db = get_database(session)
return db.events.delete_all(session)
return db.events.delete_all()
@router.delete("/{id}")
async def delete_event(id: int, session: Session = Depends(generate_session)):
""" Delete event from the Database """
db = get_database(session)
return db.events.delete(session, id)
return db.events.delete(id)

View File

@@ -11,7 +11,7 @@ from mealie.core.root_logger import get_logger
from mealie.core.security import create_file_token
from mealie.db.db_setup import generate_session
from mealie.routes.routers import AdminAPIRouter
from mealie.schema.admin import BackupJob, ImportJob, Imports, LocalBackup
from mealie.schema.admin import AllBackups, BackupFile, CreateBackup, ImportJob
from mealie.schema.user.user import PrivateUser
from mealie.services.backups import imports
from mealie.services.backups.exports import backup_all
@@ -21,22 +21,24 @@ router = AdminAPIRouter(prefix="/api/backups", tags=["Backups"])
logger = get_logger()
@router.get("/available", response_model=Imports)
@router.get("/available", response_model=AllBackups)
def available_imports():
"""Returns a list of avaiable .zip files for import into Mealie."""
imports = []
for archive in app_dirs.BACKUP_DIR.glob("*.zip"):
backup = LocalBackup(name=archive.name, date=archive.stat().st_ctime)
backup = BackupFile(name=archive.name, date=archive.stat().st_ctime)
imports.append(backup)
templates = [template.name for template in app_dirs.TEMPLATE_DIR.glob("*.*")]
imports.sort(key=operator.attrgetter("date"), reverse=True)
return Imports(imports=imports, templates=templates)
return AllBackups(imports=imports, templates=templates)
@router.post("/export/database", status_code=status.HTTP_201_CREATED)
def export_database(background_tasks: BackgroundTasks, data: BackupJob, session: Session = Depends(generate_session)):
def export_database(
background_tasks: BackgroundTasks, data: CreateBackup, session: Session = Depends(generate_session)
):
"""Generates a backup of the recipe database in json format."""
try:
export_path = backup_all(

View File

@@ -1,12 +1,20 @@
from fastapi import APIRouter
from mealie.routes.recipe import all_recipe_routes, comments, image_and_assets, ingredient_parser, recipe_crud_routes
from mealie.routes.recipe import (
all_recipe_routes,
comments,
image_and_assets,
ingredient_parser,
recipe_crud_routes,
recipe_export,
)
prefix = "/recipes"
router = APIRouter()
router.include_router(all_recipe_routes.router, prefix=prefix, tags=["Recipe: Query All"])
router.include_router(recipe_export.user_router, prefix=prefix, tags=["Recipe: Exports"])
router.include_router(recipe_crud_routes.user_router, prefix=prefix, tags=["Recipe: CRUD"])
router.include_router(image_and_assets.user_router, prefix=prefix, tags=["Recipe: Images and Assets"])
router.include_router(comments.router, prefix=prefix, tags=["Recipe: Comments"])

View File

@@ -1,5 +1,3 @@
import json
import shutil
from zipfile import ZipFile
from fastapi import Depends, File
@@ -15,7 +13,6 @@ from mealie.db.db_setup import generate_session
from mealie.routes.routers import UserAPIRouter
from mealie.schema.recipe import CreateRecipeByURL, Recipe, RecipeImageTypes
from mealie.schema.recipe.recipe import CreateRecipe, RecipeSummary
from mealie.services.image.image import write_image
from mealie.services.recipe.recipe_service import RecipeService
from mealie.services.scraper.scraper import create_from_url
@@ -48,36 +45,15 @@ def test_parse_recipe_url(url: CreateRecipeByURL):
return scrape_url(url.url)
@user_router.post("/create-from-zip")
@user_router.post("/create-from-zip", status_code=201)
async def create_recipe_from_zip(
session: Session = Depends(generate_session),
recipe_service: RecipeService = Depends(RecipeService.private),
temp_path=Depends(temporary_zip_path),
archive: UploadFile = File(...),
):
""" Create recipe from archive """
with temp_path.open("wb") as buffer:
shutil.copyfileobj(archive.file, buffer)
recipe_dict = None
recipe_image = None
with ZipFile(temp_path) as myzip:
for file in myzip.namelist():
if file.endswith(".json"):
with myzip.open(file) as myfile:
recipe_dict = json.loads(myfile.read())
elif file.endswith(".webp"):
with myzip.open(file) as myfile:
recipe_image = myfile.read()
db = get_database(session)
recipe: Recipe = db.recipes.create(Recipe(**recipe_dict))
write_image(recipe.slug, recipe_image, "webp")
return recipe
recipe = recipe_service.create_from_zip(archive, temp_path)
return recipe.slug
@user_router.get("/{slug}", response_model=Recipe)

View File

@@ -0,0 +1,40 @@
from fastapi import Depends
from pydantic import BaseModel, Field
from starlette.responses import FileResponse
from mealie.core.dependencies.dependencies import temporary_dir
from mealie.core.root_logger import get_logger
from mealie.routes.routers import UserAPIRouter
from mealie.services.recipe.recipe_service import RecipeService
from mealie.services.recipe.template_service import TemplateService
user_router = UserAPIRouter()
logger = get_logger()
class FormatResponse(BaseModel):
jjson: list[str] = Field(..., alias="json")
zip: list[str]
jinja2: list[str]
@user_router.get("/exports", response_model=FormatResponse)
async def get_recipe_formats_and_templates(_: RecipeService = Depends(RecipeService.private)):
return TemplateService().templates
@user_router.get("/{slug}/exports", response_class=FileResponse)
def get_recipe_as_format(
template_name: str,
recipe_service: RecipeService = Depends(RecipeService.write_existing),
temp_dir=Depends(temporary_dir),
):
"""
## Parameters
`template_name`: The name of the template to use to use in the exports listed. Template type will automatically
be set on the backend. Because of this, it's important that your templates have unique names. See available
names and formats in the /api/recipes/exports endpoint.
"""
file = recipe_service.render_template(temp_dir, template_name)
return FileResponse(file)