imrpove api docs

This commit is contained in:
Hayden
2021-01-07 15:25:01 -09:00
parent cbb68a7ea8
commit 048114f2f2
16 changed files with 387 additions and 23 deletions

View File

@@ -1,5 +1,4 @@
from pathlib import Path
import os
import uvicorn
from fastapi import FastAPI
@@ -15,8 +14,8 @@ from routes import (
static_routes,
user_routes,
)
from routes.setting_routes import scheduler
from settings import PORT
from routes.setting_routes import scheduler # ! This has to be imported for scheduling
from settings import PORT, PRODUCTION
from utils.logger import logger
CWD = Path(__file__).parent
@@ -26,10 +25,10 @@ app = FastAPI()
# Mount Vue Frontend only in production
env = os.environ.get("ENV")
if(env == "prod"):
if PRODUCTION:
app.mount("/static", StaticFiles(directory=WEB_PATH, html=True))
# API Routes
app.include_router(recipe_routes.router)
app.include_router(meal_routes.router)
@@ -49,6 +48,9 @@ app.include_router(static_routes.router)
startup.ensure_dirs()
startup.generate_default_theme()
# Generate API Documentation
if not PRODUCTION:
startup.generate_api_docs(app)
if __name__ == "__main__":
logger.info("-----SYSTEM STARTUP-----")

View File

@@ -1,5 +1,5 @@
# from datetime import datetime
from typing import Optional
from typing import List, Optional
from pydantic import BaseModel
@@ -7,3 +7,24 @@ from pydantic import BaseModel
class BackupJob(BaseModel):
tag: Optional[str]
template: Optional[str]
class Config:
schema_extra = {
"example": {
"tag": "July 23rd 2021",
"template": "recipes.md",
}
}
class Imports(BaseModel):
imports: List[str]
templates: List[str]
class Config:
schema_extra = {
"example": {
"imports": ["sample_data.zip", "sampe_data2.zip"],
"templates": ["recipes.md", "custom_template.md"],
}
}

View File

@@ -1,14 +1,20 @@
from fastapi import APIRouter, HTTPException
from models.backup_models import BackupJob
from services.backup_services import (BACKUP_DIR, TEMPLATE_DIR, export_db,
import_from_archive)
from models.backup_models import BackupJob, Imports
from pydantic.main import BaseModel
from services.backup_services import (
BACKUP_DIR,
TEMPLATE_DIR,
export_db,
import_from_archive,
)
from utils.snackbar import SnackResponse
router = APIRouter()
@router.get("/api/backups/available/", tags=["Import / Export"])
@router.get("/api/backups/available/", tags=["Import / Export"], response_model=Imports)
async def available_imports():
"""Returns a list of avaiable .zip files for import into Mealie."""
imports = []
templates = []
for archive in BACKUP_DIR.glob("*.zip"):
@@ -17,12 +23,12 @@ async def available_imports():
for template in TEMPLATE_DIR.glob("*.md"):
templates.append(template.name)
return {"imports": imports, "templates": templates}
return Imports(imports=imports, templates=templates)
@router.post("/api/backups/export/database/", tags=["Import / Export"], status_code=201)
async def export_database(data: BackupJob):
"""Generates a backup of the recipe database in json format."""
try:
export_path = export_db(data.tag, data.template)
except:
@@ -38,6 +44,7 @@ async def export_database(data: BackupJob):
"/api/backups/{file_name}/import/", tags=["Import / Export"], status_code=200
)
async def import_database(file_name: str):
""" Import a database backup file generated from Mealie. """
imported = import_from_archive(file_name)
return imported
@@ -48,6 +55,7 @@ async def import_database(file_name: str):
status_code=200,
)
async def delete_backup(backup_name: str):
""" Removes a database backup from the file system """
try:
BACKUP_DIR.joinpath(backup_name).unlink()

View File

@@ -16,13 +16,10 @@ async def get_all_meals():
@router.post("/api/meal-plan/create/", tags=["Meal Plan"])
async def set_meal_plan(data: MealPlan):
""" Creates Mealplan from Frontend Data"""
""" Creates a mealplan database entry"""
data.process_meals()
data.save_to_db()
# try:
# except:
# raise HTTPException(
# status_code=404,
# detail=SnackResponse.error("Unable to Create Mealplan See Log"),

View File

@@ -8,6 +8,7 @@ ENV = CWD.joinpath(".env")
dotenv.load_dotenv(ENV)
# General
PRODUCTION = os.environ.get("ENV")
PORT = int(os.getenv("mealie_port", 9000))
# Mongo Database

View File

@@ -1,3 +1,4 @@
import json
from pathlib import Path
from services.settings_services import Colors, SiteTheme
@@ -37,5 +38,43 @@ def generate_default_theme():
default_theme.save_to_db()
"""Script to export the ReDoc documentation page into a standalone HTML file."""
HTML_TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>My Project - ReDoc</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="https://fastapi.tiangolo.com/img/favicon.png">
<style>
body {
margin: 0;
padding: 0;
}
</style>
<style data-styled="" data-styled-version="4.4.1"></style>
</head>
<body>
<div id="redoc-container"></div>
<script src="https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js"> </script>
<script>
var spec = %s;
Redoc.init(spec, {}, document.getElementById("redoc-container"));
</script>
</body>
</html>
"""
CWD = Path(__file__).parent
out_path = CWD.joinpath("temp", "api.html")
def generate_api_docs(app):
with open(out_path, "w") as fd:
print(HTML_TEMPLATE % json.dumps(app.openapi()), file=fd)
if __name__ == "__main__":
pass

26
mealie/temp/api.html Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
import datetime