-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathcontext.py
175 lines (129 loc) · 4.75 KB
/
context.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# Standard library
import copy
import datetime
import calendar
import logging
import json
from urllib.parse import parse_qs, urlencode
# Packages
import flask
import requests
import yaml
import dateutil.parser
from canonicalwebteam.http import CachedSession
logger = logging.getLogger(__name__)
api_session = CachedSession(fallback_cache_duration=3600)
# Read navigation.yaml
with open("navigation.yaml") as navigation_file:
nav_sections = yaml.load(navigation_file.read(), Loader=yaml.FullLoader)
# Process data from YAML files
# ===
def releases():
"""
Read releases as a dictionary from releases.yaml,
and provide the contents as a dictionary in the global
template context
"""
with open("releases.yaml") as releases:
return yaml.load(releases, Loader=yaml.FullLoader)
def _remove_hidden(pages):
filtered_pages = []
# Filter out hidden pages
for child in pages:
if not child.get("hidden"):
filtered_pages.append(child)
return filtered_pages
def navigation(path):
"""
Set "nav_sections" and "breadcrumbs" dictionaries
as global template variables
"""
breadcrumbs = {}
is_topic_page = path.startswith("/blog/topics/")
sections = copy.deepcopy(nav_sections)
for nav_section_name, nav_section in sections.items():
# Persist parent navigation on child pages in certain cases
if nav_section.get("persist") and path.startswith(nav_section["path"]):
breadcrumbs["section"] = nav_section
breadcrumbs["children"] = nav_section.get("children", [])
for child in nav_section["children"]:
if is_topic_page and child["path"] == "/blog/topics":
# always show "Topics" as active on child topic pages
child["active"] = True
break
elif child["path"] == path:
child["active"] = True
nav_section["active"] = True
breadcrumbs["section"] = nav_section
grandchildren = breadcrumbs["grandchildren"] = _remove_hidden(
child.get("children", [])
)
# Build up siblings
if child.get("hidden") or grandchildren:
# Hidden nodes appear alone
breadcrumbs["children"] = [child]
else:
# Otherwise, include all siblings
breadcrumbs["children"] = _remove_hidden(
nav_section.get("children", [])
)
break
else:
for grandchild in child.get("children", []):
if grandchild["path"] == path:
grandchild["active"] = True
nav_section["active"] = True
breadcrumbs["section"] = nav_section
breadcrumbs["children"] = [child]
if grandchild.get("hidden"):
# Hidden nodes appear alone
breadcrumbs["grandchildren"] = [grandchild]
else:
# Otherwise, include all siblings
breadcrumbs["grandchildren"] = _remove_hidden(
child.get("children", [])
)
break
return {"nav_sections": sections, "breadcrumbs": breadcrumbs}
# Helper functions
# ===
def current_year():
return datetime.datetime.now().year
def format_date(datestring):
date = dateutil.parser.parse(datestring)
return date.strftime("%-d %B %Y")
def modify_query(params):
query_params = parse_qs(flask.request.query_string.decode("utf-8"))
query_params.update(params)
return urlencode(query_params, doseq=True)
def months_list(year):
months = []
now = datetime.datetime.now()
for i in range(1, 13):
date = datetime.date(year, i, 1)
if date < now.date():
months.append({"name": date.strftime("%b"), "number": i})
return months
def month_name(string):
month = int(string)
return calendar.month_name[month]
def descending_years(end_year):
now = datetime.datetime.now()
return range(now.year, end_year, -1)
def get_json_feed(url, offset=0, limit=None):
"""
Get the entries in a JSON feed
"""
end = limit + offset if limit is not None else None
try:
response = api_session.get(url, timeout=10)
content = json.loads(response.text)
except (
json.JSONDecodeError,
requests.exceptions.RequestException,
) as fetch_error:
logger.warning(
"Error getting feed from {}: {}".format(url, str(fetch_error))
)
return False
return content[offset:end]