aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar ks129 <[email protected]>2020-09-21 16:10:56 +0300
committerGravatar ks129 <[email protected]>2020-09-21 16:10:56 +0300
commit27315dacdc76e07ee910e31fe65c9357de34bcaf (patch)
tree29df0e6026f5c3de1029d8f46d23045b0098c1c4
parentAdd unit tests for guides app (diff)
Move guides and categories getting logic to utils for better testability
-rw-r--r--pydis_site/apps/guides/utils.py71
-rw-r--r--pydis_site/apps/guides/views/category.py31
-rw-r--r--pydis_site/apps/guides/views/guide.py51
-rw-r--r--pydis_site/apps/guides/views/guides.py30
-rw-r--r--pydis_site/templates/guides/category.html2
-rw-r--r--pydis_site/templates/guides/guide.html16
-rw-r--r--pydis_site/templates/guides/guides.html4
7 files changed, 109 insertions, 96 deletions
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 @@
<a href="/guides/category/{{ category_name }}/{{ guide }}/">
<span class="is-size-4 has-text-weight-bold">{{ data.title.0 }}</span>
</a>
- <p class="is-italic">{{ data.short_description.0 }}</p>
+ <p class="is-italic">{{ data.shortdescription.0 }}</p>
</div>
{% endfor %}
</div>
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 %}
- <meta property="og:title" content="Python Discord - {{ metadata.title|first }}" />
+ <meta property="og:title" content="Python Discord - {{ guide.metadata.title|first }}" />
<meta property="og:type" content="website" />
- <meta property="og:description" content="{{ metadata.shortdescription }}" />
+ <meta property="og:description" content="{{ guide.metadata.shortdescription|first }}" />
<link rel="stylesheet" href="{% static "css/guides/guide.css" %}">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/highlightjs/[email protected]/build/styles/default.min.css">
<script src="//cdn.jsdelivr.net/gh/highlightjs/[email protected]/build/highlight.min.js"></script>
@@ -21,10 +21,10 @@
<nav class="breadcrumb is-pulled-left" aria-label="breadcrumbs">
<ul>
<li><a href="/guides">Guides</a></li>
- {% if category_data.name is not None %}
- <li><a href="/guides/category/{{ category_data.name }}">{{ category_data.title }}</a></li>
+ {% if category_data.raw_name is not None %}
+ <li><a href="/guides/category/{{ category_data.raw_name }}">{{ category_data.name }}</a></li>
{% endif %}
- <li class="is-active"><a href="#">{{ metadata.title|first }}</a></li>
+ <li class="is-active"><a href="#">{{ guide.metadata.title|first }}</a></li>
</ul>
</nav>
</div>
@@ -33,13 +33,13 @@
<section class="section">
<div class="content">
<div class="container">
- <h1 class="title">{{ metadata.title|first }}</h1>
+ <h1 class="title">{{ guide.metadata.title|first }}</h1>
<div class="columns is-variable is-8">
<div class="column is-two-thirds">
- {{ guide|safe }}
+ {{ guide.guide|safe }}
<p class="has-text-weight-light is-size-7">
<strong>Last modified:</strong> {{ last_modified }}<br/>
- <strong>Contributors:</strong> {{ metadata.contributors|join:", " }}
+ <strong>Contributors:</strong> {{ guide.metadata.contributors|join:", " }}
</p>
</div>
<div class="column">
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 @@
<i class="fab fa-python is-size-3 is-black has-icon-padding" aria-hidden="true"></i>
</span>
<a href="{{ guide }}/">
- <span class="is-size-4 has-text-weight-bold">{{ data.name.0 }}</span>
+ <span class="is-size-4 has-text-weight-bold">{{ data.title.0 }}</span>
</a>
- <p class="is-italic">{{ data.short_description.0 }}</p>
+ <p class="is-italic">{{ data.shortdescription.0 }}</p>
</div>
{% endfor %}
{% for category, data in categories.items %}