Skip to content

Commit c401312

Browse files
committed
code cleanup
1 parent 9723409 commit c401312

File tree

4 files changed

+43
-25
lines changed

4 files changed

+43
-25
lines changed

src/reliqua/api.py

+16-3
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def __init__(
6565
:param dict info: Application information
6666
:param dict openapi: OpenAPI configuration options
6767
68-
:return: api instance
68+
:return: API instance
6969
"""
7070
info = info or {}
7171
openapi = openapi or {}
@@ -107,6 +107,7 @@ def __init__(
107107
self._add_docs()
108108

109109
def _add_handlers(self):
110+
"""Add custom media handlers."""
110111
extra_handlers = {
111112
"application/yaml": YAMLHandler(),
112113
"text/html; charset=utf-8": TextHandler(),
@@ -118,6 +119,7 @@ def _add_handlers(self):
118119
self.resp_options.media_handlers.update(extra_handlers)
119120

120121
def _load_resources(self):
122+
"""Load resource classes from the specified resource path."""
121123
resources = []
122124
path = f"{self.resource_path}/*.py"
123125
print(f"searching {path}")
@@ -128,10 +130,11 @@ def _load_resources(self):
128130
classes = self._get_classes(file)
129131
resources.extend(classes)
130132

131-
# add config to resource
133+
# Add config to resource
132134
self.resources = [x(app_config=self.config, **self.resource_attributes) for x in resources]
133135

134136
def _is_route_method(self, name, suffix):
137+
"""Check if a method name is a route method."""
135138
if not name.startswith("on_"):
136139
return None
137140

@@ -141,6 +144,7 @@ def _is_route_method(self, name, suffix):
141144
return re.search(r"^on_([a-z]+)$", name)
142145

143146
def _parse_methods(self, resource, route, methods):
147+
"""Parse methods of a resource for a given route."""
144148
parser = SphinxParser()
145149
for name in methods:
146150
operation_id = f"{resource.__class__.__name__}.{name}"
@@ -149,23 +153,30 @@ def _parse_methods(self, resource, route, methods):
149153
resource.__data__[route][action] = parser.parse(method, operation_id=operation_id)
150154

151155
def _parse_resource(self, resource):
156+
"""Parse a resource to extract routes and methods."""
152157
for route, data in resource.__routes__.items():
153158
resource.__data__[route] = {}
154159
suffix = data.get("suffix", None)
155160
methods = [x for x in dir(resource) if self._is_route_method(x, suffix)]
156161
self._parse_methods(resource, route, methods)
157162

158163
def _parse_docstrings(self):
164+
"""Parse docstrings of all resources."""
159165
for resource in self.resources:
160166
resource.__data__ = {}
161167
self._parse_resource(resource)
162168

163169
def _get_classes(self, filename):
170+
"""Get resource classes from a file."""
164171
classes = []
165172
module_name = str(uuid.uuid3(uuid.NAMESPACE_OID, filename))
166173
spec = importlib.util.spec_from_file_location(module_name, filename)
167174
module = importlib.util.module_from_spec(spec)
168-
spec.loader.exec_module(module)
175+
try:
176+
spec.loader.exec_module(module)
177+
except Exception as e:
178+
print(f"Error loading module {module_name}: {e}")
179+
return classes
169180

170181
for _, c in inspect.getmembers(module, inspect.isclass):
171182
if issubclass(c, Resource) and hasattr(c, "__routes__"):
@@ -174,12 +185,14 @@ def _get_classes(self, filename):
174185
return classes
175186

176187
def _add_routes(self):
188+
"""Add routes for all resources."""
177189
for resource in self.resources:
178190
routes = resource.__routes__
179191
for route, kwargs in routes.items():
180192
self.add_route(route, resource, **kwargs)
181193

182194
def _add_docs(self):
195+
"""Add Swagger and OpenAPI documentation routes."""
183196
swagger = Swagger(
184197
self.openapi["static_url"],
185198
self.openapi["spec_url"],

src/reliqua/app.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -43,18 +43,19 @@
4343

4444
def update_dict(a, b):
4545
"""
46-
Update dictionary A with values from dictionary B.
46+
Update dictionary a with values from dictionary b.
4747
48-
Update the diction A with values from dictionary B. Remove
49-
keys from A that are not in B.
48+
Update dictionary a with values from dictionary b. Remove
49+
keys from a that are not in b.
5050
51-
:param dict a: Dictionary A
52-
:param dict b: Dictionary B
51+
:param dict a: Dictionary to update
52+
:param dict b: Dictionary with new values
53+
:return dict: Updated dictionary
5354
"""
54-
# Create a new dictionary with keys from A that are also in B
55+
# Create a new dictionary with keys from a that are also in b
5556
updated_dict = {key: a[key] for key in a if key in b}
5657

57-
# Add keys from B that are not in A
58+
# Add keys from b that are not in a
5859
for key in b:
5960
if key not in updated_dict:
6061
updated_dict[key] = b[key]
@@ -78,8 +79,9 @@ def load_config(config_file):
7879

7980
for option in config.options(section):
8081
params[option] = config.get(section, option)
81-
except TypeError:
82-
pass
82+
except (TypeError, configparser.Error) as e:
83+
# Log the error or handle it appropriately
84+
print(f"Error loading config file: {e}")
8385

8486
return params
8587

@@ -125,7 +127,7 @@ def __init__(
125127

126128
middleware.append(ProcessParams())
127129

128-
# trim slashes from proxy URL if specified; otherwise set default proxy url
130+
# Trim slashes from proxy URL if specified; otherwise set default proxy URL
129131
bind = self.gunicorn_options["bind"]
130132
openapi["api_url"] = openapi["api_url"].rstrip("/") if openapi["api_url"] else f"http://{bind}"
131133

src/reliqua/openapi.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def __init__(
115115
self.examples = examples
116116
self._datatype = datatype
117117

118-
# path parameters are always required
118+
# Path parameters are always required
119119
if self.location == "path":
120120
self.required = True
121121

@@ -125,7 +125,7 @@ def datatype(self):
125125
value = self._datatype
126126
a, _, b = value.partition("|")
127127

128-
# handle defined list type ex: list[str]
128+
# Handle defined list type ex: list[str]
129129
if re.search(r"list\[(\w+)]", a):
130130
a = "list"
131131

src/reliqua/swagger.py

+13-10
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,13 @@ def index(spec, server, sort="alpha", highlight="true"):
1313
"""
1414
Return the Swagger index HTML.
1515
16-
This returns the Swagger index html contents.
16+
This returns the Swagger index HTML contents.
17+
18+
:param str spec: URL to the OpenAPI spec
19+
:param str server: URL to the server hosting Swagger UI assets
20+
:param str sort: Sort order for operations and tags
21+
:param str highlight: Enable syntax highlighting
22+
:return str: HTML content for Swagger UI
1723
"""
1824
highlight = "true" if highlight else "false"
1925

@@ -60,7 +66,7 @@ def index(spec, server, sort="alpha", highlight="true"):
6066

6167

6268
class Swagger(Resource):
63-
"""Class to server the static swagger files."""
69+
"""Class to serve the static Swagger files."""
6470

6571
no_auth = True
6672

@@ -70,24 +76,21 @@ def __init__(self, url, openapi_url, sort="alpha", highlight=True):
7076
7177
:param str url: URL to Swagger instance
7278
:param str openapi_url: URL to OpenAPI spec
73-
:param srt sort: Tag/Endpoint sort order
79+
:param str sort: Tag/Endpoint sort order
7480
:param bool highlight: Syntax highlighting
75-
:param bool authenticate: Docs need authentication
76-
:return: None
7781
"""
82+
super().__init__()
7883
self.url = url
7984
self.openapi_url = openapi_url
8085
self.highlight = highlight
8186
self.sort = sort
8287

8388
def on_get(self, _req, resp):
8489
"""
85-
Return the static swagger file.
90+
Return the static Swagger file.
8691
87-
:param Request request: Request object
88-
:param Response response: Response object
89-
:param str filename: Filename contents to return
90-
:return text: File contents
92+
:param Request _req: Request object
93+
:param Response resp: Response object
9194
"""
9295
resp.status = HTTP(200)
9396
resp.content_type = "text/html"

0 commit comments

Comments
 (0)