From 27315dacdc76e07ee910e31fe65c9357de34bcaf Mon Sep 17 00:00:00 2001
From: ks129 <45097959+ks129@users.noreply.github.com>
Date: Mon, 21 Sep 2020 16:10:56 +0300
Subject: Move guides and categories getting logic to utils for better
testability
---
pydis_site/apps/guides/utils.py | 71 +++++++++++++++++++++++++++++++
pydis_site/apps/guides/views/category.py | 31 ++------------
pydis_site/apps/guides/views/guide.py | 51 +++++++++-------------
pydis_site/apps/guides/views/guides.py | 30 ++-----------
pydis_site/templates/guides/category.html | 2 +-
pydis_site/templates/guides/guide.html | 16 +++----
pydis_site/templates/guides/guides.html | 4 +-
7 files changed, 109 insertions(+), 96 deletions(-)
create mode 100644 pydis_site/apps/guides/utils.py
diff --git a/pydis_site/apps/guides/utils.py b/pydis_site/apps/guides/utils.py
new file mode 100644
index 00000000..c7d03dc3
--- /dev/null
+++ b/pydis_site/apps/guides/utils.py
@@ -0,0 +1,71 @@
+import os
+from typing import Dict, Optional, Union
+
+import yaml
+from django.conf import settings
+from django.http import Http404
+from markdown import Markdown
+
+
+def get_category(category: str) -> Dict[str, str]:
+ """Load category information by name from _info.yml."""
+ path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides", category)
+ if not os.path.exists(path) or not os.path.isdir(path):
+ raise Http404("Category not found.")
+
+ with open(os.path.join(path, "_info.yml")) as f:
+ return yaml.load(f.read())
+
+
+def get_categories() -> Dict[str, Dict]:
+ """Get all categories information."""
+ base_path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides")
+ categories = {}
+
+ for name in os.listdir(base_path):
+ if os.path.isdir(os.path.join(base_path, name)):
+ categories[name] = get_category(name)
+
+ return categories
+
+
+def get_guides(category: Optional[str] = None) -> Dict[str, Dict]:
+ """Get all root guides when category is not specified. Otherwise get all this category guides."""
+ if category is None:
+ base_dir = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides")
+ else:
+ base_dir = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides", category)
+
+ guides = {}
+
+ for filename in os.listdir(base_dir):
+ if os.path.isfile(os.path.join(base_dir, filename)) and filename.endswith(".md"):
+ md = Markdown(extensions=['meta'])
+ with open(os.path.join(base_dir, filename)) as f:
+ md.convert(f.read())
+
+ guides[os.path.splitext(filename)[0]] = md.Meta
+
+ return guides
+
+
+def get_guide(guide: str, category: Optional[str]) -> Dict[str, Union[str, Dict]]:
+ """Get one specific guide. When category is specified, get it from there."""
+ if category is None:
+ base_path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides")
+ else:
+ base_path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides", category)
+
+ if not os.path.exists(base_path) or not os.path.isdir(base_path):
+ raise Http404("Category not found.")
+
+ guide_path = os.path.join(base_path, f"{guide}.md")
+ if not os.path.exists(guide_path) or not os.path.isfile(guide_path):
+ raise Http404("Guide not found.")
+
+ md = Markdown(extensions=['meta', 'attr_list', 'fenced_code'])
+
+ with open(guide_path) as f:
+ html = md.convert(f.read())
+
+ return {"guide": html, "metadata": md.Meta}
diff --git a/pydis_site/apps/guides/views/category.py b/pydis_site/apps/guides/views/category.py
index e51b3fed..33e8c97b 100644
--- a/pydis_site/apps/guides/views/category.py
+++ b/pydis_site/apps/guides/views/category.py
@@ -1,12 +1,9 @@
-import os
-
-import yaml
-from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest
-from django.http import HttpResponse, Http404
+from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
-from markdown import Markdown
+
+from pydis_site.apps.guides.utils import get_category, get_guides
class CategoryView(View):
@@ -14,28 +11,8 @@ class CategoryView(View):
def get(self, request: WSGIRequest, category: str) -> HttpResponse:
"""Handles page that displays category guides."""
- path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides", category)
- if not os.path.exists(path) or not os.path.isdir(path):
- raise Http404("Category not found.")
-
- with open(os.path.join(path, "_info.yml")) as f:
- category_info = yaml.load(f.read())
-
- guides = {}
-
- for filename in os.listdir(path):
- if filename.endswith(".md"):
- md = Markdown(extensions=["meta"])
- with open(os.path.join(path, filename)) as f:
- md.convert(f.read())
-
- guides[os.path.splitext(filename)[0]] = {
- "title": md.Meta["title"],
- "short_description": md.Meta["shortdescription"]
- }
-
return render(
request,
"guides/category.html",
- {"category_info": category_info, "guides": guides, "category_name": category}
+ {"category_info": get_category(category), "guides": get_guides(category), "category_name": category}
)
diff --git a/pydis_site/apps/guides/views/guide.py b/pydis_site/apps/guides/views/guide.py
index deb1b8c4..bcd68bc4 100644
--- a/pydis_site/apps/guides/views/guide.py
+++ b/pydis_site/apps/guides/views/guide.py
@@ -2,13 +2,13 @@ import os
from datetime import datetime
from typing import Optional
-import yaml
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest
-from django.http import HttpResponse, Http404
+from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
-from markdown import Markdown
+
+from pydis_site.apps.guides.utils import get_category, get_guide
class GuideView(View):
@@ -16,44 +16,33 @@ class GuideView(View):
def get(self, request: WSGIRequest, guide: str, category: Optional[str] = None) -> HttpResponse:
"""Collect guide content and display it. When guide don't exist, return 404."""
- if category is None:
- path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides", f"{guide}.md")
- category_name = None
- else:
- dir_path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides", category)
- if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
- raise Http404("Category not found.")
-
- path = os.path.join(dir_path, f"{guide}.md")
- with open(os.path.join(dir_path, "_info.yml")) as f:
- category_name = yaml.load(f.read())["name"]
-
- if not os.path.exists(path) or not os.path.isfile(path):
- raise Http404(f"Guide not found")
+ guide_result = get_guide(guide, category)
- md = Markdown(extensions=['meta', 'attr_list', 'fenced_code'])
- with open(path) as f:
- html = md.convert(f.read())
- f.close()
+ if category is not None:
+ path = os.path.join(
+ settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides", category, f"{guide}.md"
+ )
+ else:
+ path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides", f"{guide}.md")
- category_data = {
- "title": category_name,
- "name": category,
- }
+ if category is not None:
+ category_data = get_category(category)
+ category_data["raw_name"] = category
+ else:
+ category_data = {"name": None, "raw_name": None}
return render(
request,
"guides/guide.html",
{
- "guide": html,
- "metadata": md.Meta,
+ "guide": guide_result,
"last_modified": datetime.fromtimestamp(os.path.getmtime(path)).strftime("%dth %B %Y"),
+ "category_data": category_data,
"relevant_links": {
link: value for link, value in zip(
- md.Meta.get("relevantlinks", []),
- md.Meta.get("relevantlinkvalues", [])
+ guide_result["metadata"].get("relevantlinks", []),
+ guide_result["metadata"].get("relevantlinkvalues", [])
)
- },
- "category_data": category_data,
+ }
}
)
diff --git a/pydis_site/apps/guides/views/guides.py b/pydis_site/apps/guides/views/guides.py
index f457adc1..bb8b565e 100644
--- a/pydis_site/apps/guides/views/guides.py
+++ b/pydis_site/apps/guides/views/guides.py
@@ -1,12 +1,9 @@
-import os
-
-import yaml
-from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
-from markdown import Markdown
+
+from pydis_site.apps.guides.utils import get_categories, get_guides
class GuidesView(View):
@@ -14,25 +11,4 @@ class GuidesView(View):
def get(self, request: WSGIRequest) -> HttpResponse:
"""Shows all guides and categories."""
- guides = {}
- categories = {}
-
- guides_path = os.path.join(settings.BASE_DIR, "pydis_site", "apps", "guides", "resources", "guides")
- for name in os.listdir(guides_path):
- full_path = os.path.join(guides_path, name)
- if os.path.isdir(full_path):
- with open(os.path.join(full_path, "_info.yml")) as f:
- category = yaml.load(f.read())
-
- categories[name] = {"name": category["name"], "description": category["description"]}
- elif os.path.isfile(full_path) and name.endswith(".md"):
- md = Markdown(extensions=['meta'])
- with open(full_path) as f:
- md.convert(f.read())
-
- guides[os.path.splitext(name)[0]] = {
- "name": md.Meta["title"],
- "short_description": md.Meta["shortdescription"]
- }
-
- return render(request, "guides/guides.html", {"guides": guides, "categories": categories})
+ return render(request, "guides/guides.html", {"guides": get_guides(), "categories": get_categories()})
diff --git a/pydis_site/templates/guides/category.html b/pydis_site/templates/guides/category.html
index f70a668f..b5cd9ce0 100644
--- a/pydis_site/templates/guides/category.html
+++ b/pydis_site/templates/guides/category.html
@@ -32,7 +32,7 @@
{{ data.title.0 }}
-
{{ data.short_description.0 }}
+ {{ data.shortdescription.0 }}
{% endfor %}
diff --git a/pydis_site/templates/guides/guide.html b/pydis_site/templates/guides/guide.html
index 8f841c53..bab82415 100644
--- a/pydis_site/templates/guides/guide.html
+++ b/pydis_site/templates/guides/guide.html
@@ -4,9 +4,9 @@
{% block title %}{{ metadata.title|first }}{% endblock %}
{% block head %}
-
+
-
+
@@ -21,10 +21,10 @@
@@ -33,13 +33,13 @@
-
{{ metadata.title|first }}
+
{{ guide.metadata.title|first }}
- {{ guide|safe }}
+ {{ guide.guide|safe }}
Last modified: {{ last_modified }}
- Contributors: {{ metadata.contributors|join:", " }}
+ Contributors: {{ guide.metadata.contributors|join:", " }}
diff --git a/pydis_site/templates/guides/guides.html b/pydis_site/templates/guides/guides.html
index 66878048..0e6f2073 100644
--- a/pydis_site/templates/guides/guides.html
+++ b/pydis_site/templates/guides/guides.html
@@ -29,9 +29,9 @@
- {{ data.name.0 }}
+ {{ data.title.0 }}
-
{{ data.short_description.0 }}
+
{{ data.shortdescription.0 }}
{% endfor %}
{% for category, data in categories.items %}
--
cgit v1.2.3