-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathcontext.py
More file actions
202 lines (146 loc) · 4.95 KB
/
context.py
File metadata and controls
202 lines (146 loc) · 4.95 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# Standard library
import copy
import datetime
import calendar
import logging
import json
import numpy
from urllib.parse import parse_qs, urlencode
# Packages
import flask
import requests
import yaml
import dateutil.parser
from slugify import slugify
from canonicalwebteam.http import CachedSession
logger = logging.getLogger(__name__)
api_session = CachedSession(fallback_cache_duration=3600)
# Read secondary-navigation.yaml
with open("secondary-navigation.yaml") as secondary_navigation_file:
nav_sections = yaml.load(
secondary_navigation_file.read(), Loader=yaml.FullLoader
)
# Read navigation.yaml
with open("navigation.yaml") as navigation_file:
navigation = 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.
Exposes them as "releases_yaml".
"""
with open("releases.yaml") as releases:
return yaml.load(releases, Loader=yaml.FullLoader)
def get_navigation(section):
"""
Set "navigation_section" as global template variable
"""
sections = {}
navigation_sections = copy.deepcopy(navigation)
if section == "all":
return navigation_sections
for section_name, navigation_section in navigation_sections.items():
if section_name == section:
sections = navigation_section
return {"sections": sections}
def get_secondary_navigation(path):
"""
Set "nav_sections" and "breadcrumbs" dictionaries
as global template variables
"""
breadcrumbs = {}
sections = copy.deepcopy(nav_sections)
for nav_section_name, nav_section in sections.items():
longest_match_path = 0
child_to_set_active = None
for child in nav_section["children"]:
if (
child["path"] == path and path.startswith(nav_section["path"])
) or (path.startswith(child["path"])):
# look for the closest patch match
if len(child["path"]) > longest_match_path:
longest_match_path = len(child["path"])
child_to_set_active = child
nav_section["active"] = True
breadcrumbs["section"] = nav_section
# Include all siblings
breadcrumbs["children"] = nav_section.get("children", [])
# set the child most closely matching the current path as active
if child_to_set_active:
child_to_set_active["active"] = True
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, dayfirst=True)
return date.strftime("%-d %B %Y")
def modify_query(params):
query_params = parse_qs(
flask.request.query_string.decode("utf-8"), keep_blank_values=True
)
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 split_list(array, parts):
return numpy.array_split(array, parts)
def format_to_id(string):
return slugify(string)
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]
def schedule_banner(start_date: str, end_date: str):
try:
end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
present = datetime.datetime.now()
return start <= present < end
except ValueError:
return False
def date_has_passed(date_str):
try:
date = datetime.strptime(date_str, "%Y-%m-%d")
present = datetime.now()
return present > date
except ValueError:
return False
def sort_by_key_and_ordered_list(list_to_sort, obj_key, ordered_list):
return sorted(
list_to_sort,
key=lambda item: (
ordered_list.index(item[obj_key])
if item[obj_key] in ordered_list
else len(ordered_list)
),
)