Skip to content

Commit 09b4fe2

Browse files
Naveen-Palarkid15r
andauthored
Improved Backend docstrings with Google-style defined params (#1206)
* backend docstrings with Google-style defined params * fix long lines/check errors * fix spell * Update code * Remove unnecessary docstring separators --------- Co-authored-by: Arkadii Yakovets <[email protected]> Co-authored-by: Arkadii Yakovets <[email protected]>
1 parent 322a80c commit 09b4fe2

File tree

104 files changed

+1950
-212
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

104 files changed

+1950
-212
lines changed

backend/apps/common/geocoding.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,15 @@
88

99

1010
def get_location_coordinates(query, delay=2):
11-
"""Get location geo coordinates."""
11+
"""Get location geo coordinates.
12+
13+
Args:
14+
query (str): The location query string.
15+
delay (int, optional): Delay in seconds before making the request.
16+
17+
Returns:
18+
Location|None: The geopy Location object or None if not found.
19+
20+
"""
1221
time.sleep(delay)
1322
return Nominatim(timeout=3, user_agent=get_nest_user_agent()).geocode(query)

backend/apps/common/index.py

Lines changed: 85 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,24 @@ def get_instance(cls):
4949
return cls._instance
5050

5151
def is_indexable(self, name: str):
52-
"""Check if index is on."""
52+
"""Check if an index is enabled for indexing.
53+
54+
Args:
55+
name (str): The name of the index.
56+
57+
Returns:
58+
bool: True if the index is enabled, False otherwise.
59+
60+
"""
5361
return name.lower() not in self.excluded_local_index_names if IS_LOCAL_BUILD else True
5462

5563
def load_excluded_local_index_names(self):
56-
"""Load excluded local index names."""
64+
"""Load excluded local index names from settings.
65+
66+
Returns
67+
IndexRegistry: The current instance of the registry.
68+
69+
"""
5770
excluded_names = settings.ALGOLIA_EXCLUDED_LOCAL_INDEX_NAMES
5871
self.excluded_local_index_names = set(
5972
(
@@ -69,12 +82,29 @@ def load_excluded_local_index_names(self):
6982

7083

7184
def is_indexable(index_name: str):
72-
"""Determine if an index should be created based on configuration."""
85+
"""Determine if an index should be created based on configuration.
86+
87+
Args:
88+
index_name (str): The name of the index.
89+
90+
Returns:
91+
bool: True if the index is indexable, False otherwise.
92+
93+
"""
7394
return IndexRegistry.get_instance().is_indexable(index_name)
7495

7596

7697
def register(model, **kwargs):
77-
"""Register index if configuration allows."""
98+
"""Register an index if configuration allows.
99+
100+
Args:
101+
model (Model): The Django model to register.
102+
**kwargs: Additional arguments for the registration.
103+
104+
Returns:
105+
Callable: A wrapper function for the index class.
106+
107+
"""
78108

79109
def wrapper(index_cls):
80110
return (
@@ -91,7 +121,15 @@ class IndexBase(AlgoliaIndex):
91121

92122
@staticmethod
93123
def get_client(ip_address=None):
94-
"""Return an instance of search client."""
124+
"""Return an instance of the search client.
125+
126+
Args:
127+
ip_address (str, optional): The IP address for the client.
128+
129+
Returns:
130+
SearchClientSync: The search client instance.
131+
132+
"""
95133
config = SearchConfig(
96134
settings.ALGOLIA_APPLICATION_ID,
97135
settings.ALGOLIA_WRITE_API_KEY,
@@ -103,7 +141,13 @@ def get_client(ip_address=None):
103141

104142
@staticmethod
105143
def configure_replicas(index_name: str, replicas: dict):
106-
"""Configure replicas."""
144+
"""Configure replicas for an index.
145+
146+
Args:
147+
index_name (str): The name of the base index.
148+
replicas (dict): A dictionary of replica names and their ranking configurations.
149+
150+
"""
107151
if not is_indexable(index_name):
108152
return # Skip replicas configuration if base index is off.
109153

@@ -125,7 +169,15 @@ def configure_replicas(index_name: str, replicas: dict):
125169

126170
@staticmethod
127171
def _parse_synonyms_file(file_path):
128-
"""Parse synonyms file."""
172+
"""Parse a synonyms file and return its content.
173+
174+
Args:
175+
file_path (str): The path to the synonyms file.
176+
177+
Returns:
178+
list: A list of parsed synonyms or None if the file is not found.
179+
180+
"""
129181
try:
130182
with Path(file_path).open("r", encoding="utf-8") as f:
131183
file_content = f.read()
@@ -163,7 +215,16 @@ def _parse_synonyms_file(file_path):
163215

164216
@staticmethod
165217
def reindex_synonyms(app_name, index_name):
166-
"""Reindex synonyms."""
218+
"""Reindex synonyms for a specific index.
219+
220+
Args:
221+
app_name (str): The name of the application.
222+
index_name (str): The name of the index.
223+
224+
Returns:
225+
int or None: The number of synonyms reindexed, or None if an error occurs.
226+
227+
"""
167228
file_path = Path(f"{settings.BASE_DIR}/apps/{app_name}/index/synonyms/{index_name}.txt")
168229

169230
if not (synonyms := IndexBase._parse_synonyms_file(file_path)):
@@ -186,7 +247,16 @@ def reindex_synonyms(app_name, index_name):
186247
@staticmethod
187248
@lru_cache(maxsize=1024)
188249
def get_total_count(index_name, search_filters=None):
189-
"""Get total count of records in index."""
250+
"""Get the total count of records in an index.
251+
252+
Args:
253+
index_name (str): The name of the index.
254+
search_filters (str, optional): Filters to apply to the search.
255+
256+
Returns:
257+
int: The total count of records in the index.
258+
259+
"""
190260
client = IndexBase.get_client()
191261
try:
192262
search_params = {
@@ -205,7 +275,12 @@ def get_total_count(index_name, search_filters=None):
205275
return 0
206276

207277
def get_queryset(self):
208-
"""Get queryset."""
278+
"""Get the queryset for the index.
279+
280+
Returns
281+
QuerySet: The queryset of entities to index.
282+
283+
"""
209284
qs = self.get_entities()
210285

211286
return qs[:LOCAL_INDEX_LIMIT] if IS_LOCAL_BUILD else qs

backend/apps/common/management/commands/algolia_update_replicas.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@ class Command(BaseCommand):
99
help = "Update OWASP Nest index replicas."
1010

1111
def handle(self, *_args, **_options):
12+
"""Update replicas for Algolia indices.
13+
14+
Args:
15+
*_args: Positional arguments (not used).
16+
**_options: Keyword arguments (not used).
17+
18+
"""
1219
print("\n Starting replica configuration...")
1320
ProjectIndex.configure_replicas()
1421
print("\n Replica have been Successfully created.")

backend/apps/common/management/commands/algolia_update_synonyms.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ class Command(BaseCommand):
1010
help = "Update OWASP Nest index synonyms."
1111

1212
def handle(self, *_args, **_options):
13+
"""Update synonyms for Algolia indices.
14+
15+
Args:
16+
*_args: Positional arguments (not used).
17+
**_options: Keyword arguments (not used).
18+
19+
"""
1320
print("\nThe following models synonyms were reindexed:")
1421
for index in (IssueIndex, ProjectIndex):
1522
count = index.update_synonyms()

backend/apps/common/management/commands/generate_sitemap.py

Lines changed: 98 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,26 @@ class Command(BaseCommand):
2929
}
3030

3131
def add_arguments(self, parser):
32+
"""Add command-line arguments to the parser.
33+
34+
Args:
35+
parser (ArgumentParser): The argument parser instance.
36+
37+
"""
3238
parser.add_argument(
3339
"--output-dir",
3440
default=settings.STATIC_ROOT,
3541
help="Directory where sitemap files will be saved",
3642
)
3743

3844
def handle(self, *args, **options):
45+
"""Generate sitemaps for the OWASP Nest application.
46+
47+
Args:
48+
*args: Positional arguments (not used).
49+
**options: Command-line options.
50+
51+
"""
3952
output_dir = Path(options["output_dir"])
4053
output_dir.mkdir(parents=True, exist_ok=True)
4154

@@ -58,7 +71,12 @@ def handle(self, *args, **options):
5871
self.stdout.write(self.style.SUCCESS(f"Successfully generated sitemaps in {output_dir}"))
5972

6073
def generate_project_sitemap(self, output_dir):
61-
"""Generate sitemap for projects."""
74+
"""Generate a sitemap for projects.
75+
76+
Args:
77+
output_dir (Path): The directory to save the sitemap.
78+
79+
"""
6280
routes = self.static_routes["projects"]
6381
projects = Project.objects.all()
6482
indexable_projects = [project for project in projects if project.is_indexable]
@@ -74,7 +92,12 @@ def generate_project_sitemap(self, output_dir):
7492
self.save_sitemap(content, output_dir / "sitemap-project.xml")
7593

7694
def generate_chapter_sitemap(self, output_dir):
77-
"""Generate sitemap for chapters."""
95+
"""Generate a sitemap for chapters.
96+
97+
Args:
98+
output_dir (Path): The directory to save the sitemap.
99+
100+
"""
78101
routes = self.static_routes["chapters"]
79102
chapters = Chapter.objects.filter(is_active=True)
80103
indexable_chapters = [chapter for chapter in chapters if chapter.is_indexable]
@@ -90,7 +113,12 @@ def generate_chapter_sitemap(self, output_dir):
90113
self.save_sitemap(content, output_dir / "sitemap-chapters.xml")
91114

92115
def generate_committee_sitemap(self, output_dir):
93-
"""Generate sitemap for committees."""
116+
"""Generate a sitemap for committees.
117+
118+
Args:
119+
output_dir (Path): The directory to save the sitemap.
120+
121+
"""
94122
routes = self.static_routes["committees"]
95123
indexable_committees = Committee.objects.filter(is_active=True)
96124

@@ -109,7 +137,12 @@ def generate_committee_sitemap(self, output_dir):
109137
self.save_sitemap(content, output_dir / "sitemap-committees.xml")
110138

111139
def generate_user_sitemap(self, output_dir):
112-
"""Generate sitemap for users."""
140+
"""Generate a sitemap for users.
141+
142+
Args:
143+
output_dir (Path): The directory to save the sitemap.
144+
145+
"""
113146
routes = self.static_routes["users"]
114147
users = User.objects.all()
115148
indexable_users = [user for user in users if user.is_indexable]
@@ -125,7 +158,15 @@ def generate_user_sitemap(self, output_dir):
125158
self.save_sitemap(content, output_dir / "sitemap-users.xml")
126159

127160
def generate_sitemap_content(self, routes):
128-
"""Generate sitemap content for a set of routes."""
161+
"""Generate the XML content for a sitemap.
162+
163+
Args:
164+
routes (list): A list of route dictionaries.
165+
166+
Returns:
167+
str: The XML content of the sitemap.
168+
169+
"""
129170
urls = []
130171
lastmod = datetime.now(timezone.utc).strftime("%Y-%m-%d")
131172

@@ -141,7 +182,15 @@ def generate_sitemap_content(self, routes):
141182
return self.create_sitemap(urls)
142183

143184
def generate_index_sitemap(self, sitemap_files):
144-
"""Generate the sitemap index file."""
185+
"""Generate the sitemap index file.
186+
187+
Args:
188+
sitemap_files (list): A list of sitemap file names.
189+
190+
Returns:
191+
str: The XML content of the sitemap index.
192+
193+
"""
145194
sitemaps = []
146195
lastmod = datetime.now(timezone.utc).strftime("%Y-%m-%d")
147196

@@ -152,7 +201,15 @@ def generate_index_sitemap(self, sitemap_files):
152201
return self.create_sitemap_index(sitemaps)
153202

154203
def create_url_entry(self, url_data):
155-
"""Create a URL entry for the sitemap."""
204+
"""Create a URL entry for the sitemap.
205+
206+
Args:
207+
url_data (dict): A dictionary containing URL data.
208+
209+
Returns:
210+
str: The XML entry for the URL.
211+
212+
"""
156213
return (
157214
" <url>\n"
158215
" <loc>{loc}</loc>\n"
@@ -163,13 +220,29 @@ def create_url_entry(self, url_data):
163220
).format(**url_data)
164221

165222
def create_sitemap_index_entry(self, sitemap_data):
166-
"""Create a sitemap entry for the index."""
223+
"""Create a sitemap index entry.
224+
225+
Args:
226+
sitemap_data (dict): A dictionary containing sitemap data.
227+
228+
Returns:
229+
str: The XML entry for the sitemap index.
230+
231+
"""
167232
return (
168233
" <sitemap>\n <loc>{loc}</loc>\n <lastmod>{lastmod}</lastmod>\n </sitemap>"
169234
).format(**sitemap_data)
170235

171236
def create_sitemap(self, urls):
172-
"""Create the complete sitemap XML."""
237+
"""Create the complete sitemap XML.
238+
239+
Args:
240+
urls (list): A list of URL entries.
241+
242+
Returns:
243+
str: The XML content of the sitemap.
244+
245+
"""
173246
return (
174247
'<?xml version="1.0" encoding="UTF-8"?>\n'
175248
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
@@ -178,7 +251,15 @@ def create_sitemap(self, urls):
178251
)
179252

180253
def create_sitemap_index(self, sitemaps):
181-
"""Create the complete sitemap index XML."""
254+
"""Create the complete sitemap index XML.
255+
256+
Args:
257+
sitemaps (list): A list of sitemap index entries.
258+
259+
Returns:
260+
str: The XML content of the sitemap index.
261+
262+
"""
182263
return (
183264
'<?xml version="1.0" encoding="UTF-8"?>\n'
184265
'<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
@@ -188,6 +269,12 @@ def create_sitemap_index(self, sitemaps):
188269

189270
@staticmethod
190271
def save_sitemap(content, filepath):
191-
"""Save the sitemap content to a file."""
272+
"""Save the sitemap content to a file.
273+
274+
Args:
275+
content (str): The XML content of the sitemap.
276+
filepath (Path): The file path to save the sitemap.
277+
278+
"""
192279
with filepath.open("w", encoding="utf-8") as f:
193280
f.write(content)

0 commit comments

Comments
 (0)