Skip to content

Commit 0d82fb5

Browse files
committed
pep8 refactoring (part 2)
1 parent db4a8fa commit 0d82fb5

17 files changed

Lines changed: 429 additions & 237 deletions

egsim/api/models.py

Lines changed: 39 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@ class EgsimDbModel(DjangoDbModel):
2727
_meta: Options # https://docs.djangoproject.com/en/stable/ref/models/options/
2828

2929
name = TextField(null=False, unique=True, help_text="Unique name")
30-
hidden = BooleanField(default=False, null=False,
31-
help_text="Hide this item, i.e. make it publicly "
32-
"unavailable to the whole API. This field "
33-
"is intended to hide/show items quickly from "
34-
"the admin panel without executing management "
35-
"scrips")
30+
hidden = BooleanField(
31+
default=False,
32+
null=False,
33+
help_text="Hide this item, i.e. make it publicly unavailable to the whole API. "
34+
"This field is intended to hide/show items quickly without re-creating "
35+
"the DB data"
36+
)
3637

3738
class Meta:
3839
abstract = True
@@ -70,23 +71,29 @@ class Gsim(EgsimDbModel):
7071
is populated with valid OpenQuake models only (`passing valid.gsim` or not
7172
deprecated)
7273
"""
73-
imts = TextField(null=False,
74-
help_text='The intensity measure types '
75-
'defined for the model, space separated '
76-
'(e.g.: "PGA SA")')
77-
min_sa_period = FloatField(null=True,
78-
help_text='The minimum SA period supported '
79-
'by the model, or None (no lower limit)')
80-
max_sa_period = FloatField(null=True,
81-
help_text='The maximum SA period supported '
82-
'by the model, or None (no upper limit)')
74+
imts = TextField(
75+
null=False,
76+
help_text='The intensity measure types defined for the model, '
77+
'space separated (e.g.: "PGA SA")'
78+
)
79+
min_sa_period = FloatField(
80+
null=True,
81+
help_text='The minimum SA period supported by the model, or None (no lower limit)'
82+
)
83+
max_sa_period = FloatField(
84+
null=True,
85+
help_text='The maximum SA period supported by the model, or None (no upper limit)'
86+
)
8387

8488
unverified = BooleanField(default=False, help_text="not independently verified")
85-
experimental = BooleanField(default=False, help_text="experimental: may "
86-
"change in future versions")
87-
adapted = BooleanField(default=False, help_text="not intended for general use: "
88-
"the behaviour may not be "
89-
"as expected")
89+
experimental = BooleanField(
90+
default=False,
91+
help_text="experimental: may change in future versions"
92+
)
93+
adapted = BooleanField(
94+
default=False,
95+
help_text="not intended for general use: the behaviour may not be as expected"
96+
)
9097
# Note: `superseded_by` is not used (we do not save deprecated Gsims)
9198

9299

@@ -98,8 +105,11 @@ class Reference(DjangoDbModel):
98105
display_name = TextField(default=None, null=True)
99106
url = URLField(default=None, null=True)
100107
license = TextField(default=None, null=True)
101-
citation = TextField(default=None, null=True,
102-
help_text="Bibliographic citation, as text")
108+
citation = TextField(
109+
default=None,
110+
null=True,
111+
help_text="Bibliographic citation, as text"
112+
)
103113
doi = TextField(default=None, null=True)
104114

105115
class Meta:
@@ -109,9 +119,12 @@ class Meta:
109119
class MediaFile(EgsimDbModel):
110120
"""Abstract class handling any data file in the MEDIA directory of eGSIM"""
111121
# for safety, do not store full file paths in the db (see `filepath` for details):
112-
filepath = TextField(unique=True, null=False,
113-
help_text="the file absolute path (usually within the "
114-
"MEDIA_ROOT path defined in Django settings)")
122+
filepath = TextField(
123+
unique=True,
124+
null=False,
125+
help_text="the file absolute path (usually within the MEDIA_ROOT path "
126+
"defined in Django settings)"
127+
)
115128

116129
def read_from_filepath(self, **kwargs) -> Any:
117130
raise NotImplementedError()

egsim/api/views.py

Lines changed: 48 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,13 @@
99

1010
import yaml
1111
import pandas as pd
12-
from django.http import (JsonResponse, HttpRequest, QueryDict, FileResponse,
13-
HttpResponseBase)
12+
from django.http import (
13+
JsonResponse,
14+
HttpRequest,
15+
QueryDict,
16+
FileResponse,
17+
HttpResponseBase
18+
)
1419
from django.http.response import HttpResponse
1520
from django.views.generic.base import View
1621

@@ -68,9 +73,11 @@ def post(self, request: HttpRequest) -> HttpResponseBase:
6873
if request.FILES:
6974
# request.content_type='multipart/form-data' (see link below for details)
7075
# https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest.FILES # noqa
71-
return self.response(request,
72-
data=self.parse_query_dict(request.POST),
73-
files=request.FILES)
76+
return self.response(
77+
request,
78+
data=self.parse_query_dict(request.POST),
79+
files=request.FILES
80+
)
7481
else:
7582
# request.content_type might be anything (most likely
7683
# 'application/json' or 'application/x-www-form-urlencoded')
@@ -83,10 +90,12 @@ def post(self, request: HttpRequest) -> HttpResponseBase:
8390
except Exception as exc:
8491
return self.handle_exception(exc, request)
8592

86-
def response(self,
87-
request: HttpRequest,
88-
data: dict,
89-
files: Optional[dict] = None) -> HttpResponseBase:
93+
def response(
94+
self,
95+
request: HttpRequest,
96+
data: dict,
97+
files: Optional[dict] = None
98+
) -> HttpResponseBase:
9099
"""
91100
Return a Django HttpResponse from the given arguments extracted from a GET
92101
or POST request. Any Exception raised here will be returned as 500 HttpResponse
@@ -114,15 +123,18 @@ def handle_exception(self, exc: Exception, request) -> HttpResponse: # noqa
114123
server error (HttpResponse 500) with the exception string representation
115124
as response body / content
116125
"""
117-
return self.error_response((
118-
f'Server error ({exc.__class__.__name__}): {exc}'.strip() +
119-
f'. Please contact the server administrator '
120-
f'if you think this error is due to a code bug'
121-
), status=self.SERVER_ERR_CODE)
122-
123-
def error_response(self,
124-
message: Union[str, Exception, bytes] = '',
125-
**kwargs) -> HttpResponse:
126+
return self.error_response(
127+
(f'Server error ({exc.__class__.__name__}): {exc}'.strip() +
128+
f'. Please contact the server administrator '
129+
f'if you think this error is due to a code bug'),
130+
status=self.SERVER_ERR_CODE
131+
)
132+
133+
def error_response(
134+
self,
135+
message: Union[str, Exception, bytes] = '',
136+
**kwargs
137+
) -> HttpResponse:
126138
"""
127139
Return a HttpResponse with default status set to self.CLIENT_ERR_CODE
128140
and custom message in the response body / content. For custom status,
@@ -166,10 +178,12 @@ def parse_query_dict( # noqa
166178
class NotFound(EgsimView):
167179
"""View for the 404 Not Found HttpResponse"""
168180

169-
def response(self,
170-
request: HttpRequest,
171-
data: dict,
172-
files: Optional[dict] = None) -> HttpResponse:
181+
def response(
182+
self,
183+
request: HttpRequest,
184+
data: dict,
185+
files: Optional[dict] = None
186+
) -> HttpResponse:
173187
return self.error_response(status=404)
174188

175189

@@ -229,10 +243,12 @@ def response_hdf(form: APIForm) -> HttpResponse:
229243
'json': lambda form: JsonResponse(form.output(), status=200)
230244
}
231245

232-
def response(self,
233-
request: HttpRequest,
234-
data: dict,
235-
files: Optional[dict] = None):
246+
def response(
247+
self,
248+
request: HttpRequest,
249+
data: dict,
250+
files: Optional[dict] = None
251+
) -> HttpResponseBase:
236252
"""
237253
Return a HttpResponse from the given arguments. The Response body / content
238254
will be populated with the output of this class Form
@@ -269,10 +285,12 @@ class SmtkView(APIFormView):
269285
'csv': lambda form: SmtkView.response_csv(form)
270286
}
271287

272-
def response(self,
273-
request: HttpRequest,
274-
data: dict,
275-
files: Optional[dict] = None):
288+
def response(
289+
self,
290+
request: HttpRequest,
291+
data: dict,
292+
files: Optional[dict] = None
293+
) -> HttpResponseBase:
276294
"""
277295
Call superclass method but catch ModelError(s) returning the appropriate
278296
HTTPResponse (Client error)

egsim/app/forms.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,16 @@
1313

1414
from egsim.smtk.flatfile import ColumnType
1515
from egsim.smtk.registry import Clabel, sa_period
16-
from .plotly import (colors_cycle, axis_type, axis_range, scatter_trace,
17-
bar_trace, line_trace, histogram_trace, AxisType)
16+
from .plotly import (
17+
colors_cycle,
18+
axis_type,
19+
axis_range,
20+
scatter_trace,
21+
bar_trace,
22+
line_trace,
23+
histogram_trace,
24+
AxisType
25+
)
1826
from ..smtk.converters import datetime2float
1927

2028

egsim/app/urls.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,22 @@
2323

2424

2525
urlpatterns = [
26-
re_path(r'^$', RedirectView.as_view(pattern_name='main', url='home',
27-
permanent=False)),
28-
re_path((r'^(?P<page>' +
29-
'|'.join([URLS.WEBPAGE_HOME, URLS.WEBPAGE_PREDICTIONS,
30-
URLS.WEBPAGE_RESIDUALS,
31-
URLS.WEBPAGE_FLATFILE_INSPECTION_PLOT,
32-
URLS.WEBPAGE_FLATFILE_COMPILATION_INFO,
33-
URLS.WEBPAGE_API_DOC,
34-
URLS.WEBPAGE_IMPRINT, URLS.WEBPAGE_CITATIONS_AND_LICENSE]) +
35-
')/?$'), main),
26+
re_path(
27+
r'^$',
28+
RedirectView.as_view(pattern_name='main', url='home', permanent=False)
29+
),
30+
re_path(
31+
(r'^(?P<page>' +
32+
'|'.join([
33+
URLS.WEBPAGE_HOME, URLS.WEBPAGE_PREDICTIONS,
34+
URLS.WEBPAGE_RESIDUALS,
35+
URLS.WEBPAGE_FLATFILE_INSPECTION_PLOT,
36+
URLS.WEBPAGE_FLATFILE_COMPILATION_INFO,
37+
URLS.WEBPAGE_API_DOC,
38+
URLS.WEBPAGE_IMPRINT, URLS.WEBPAGE_CITATIONS_AND_LICENSE
39+
]) + ')/?$'),
40+
main
41+
),
3642

3743
re_path(
3844
fr'^{URLS.DOWNLOAD_PREDICTIONS_DATA}.(?:{"|".join(data_ext)})$',

egsim/app/views.py

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@
1414
from django.conf import settings
1515

1616
from ..api import models
17-
from ..api.forms.flatfile import (FlatfileMetadataInfoForm,
18-
FlatfileValidationForm)
17+
from ..api.forms.flatfile import (
18+
FlatfileMetadataInfoForm, FlatfileValidationForm
19+
)
1920
from ..api.forms import APIForm, EgsimBaseForm, GsimForm
2021
from ..api.forms.residuals import ResidualsForm
2122
from ..api.forms.scenarios import PredictionsForm
@@ -72,8 +73,10 @@ class URLS: # noqa
7273
"/" in getattr(URLS, _) and not getattr(URLS, _).startswith('https://')
7374
for _ in dir(URLS) if 'WEBPAGE' in _
7475
):
75-
raise SystemError("Remove '/' in URL WEBPAGES: '/' create nested paths which might "
76-
"mess up requests performed on the page (error 404)")
76+
raise SystemError(
77+
"Remove '/' in URL WEBPAGES: '/' create nested paths which might "
78+
"mess up requests performed on the page (error 404)"
79+
)
7780

7881

7982
############################################
@@ -109,10 +112,12 @@ def main(request, page=''):
109112
class GsimFromRegion(EgsimView):
110113
"""View handling clicks on the GUI map and returning region-selected model(s)"""
111114

112-
def response(self,
113-
request: HttpRequest,
114-
data: dict,
115-
files: Optional[dict] = None) -> HttpResponseBase:
115+
def response(
116+
self,
117+
request: HttpRequest,
118+
data: dict,
119+
files: Optional[dict] = None
120+
) -> HttpResponseBase:
116121
form = GsimForm(data)
117122
if form.is_valid():
118123
gm_models = form.cleaned_data['regionalization']
@@ -124,10 +129,12 @@ def response(self,
124129
class PlotsImgDownloader(EgsimView):
125130
"""View returning the browser displayed plots in image format"""
126131

127-
def response(self,
128-
request: HttpRequest,
129-
data: dict,
130-
files: Optional[dict] = None) -> HttpResponseBase:
132+
def response(
133+
self,
134+
request: HttpRequest,
135+
data: dict,
136+
files: Optional[dict] = None
137+
) -> HttpResponseBase:
131138
"""
132139
Process the response from a given request and the data / files
133140
extracted from it
@@ -157,10 +164,12 @@ def response(self,
157164
class PredictionsHtmlTutorial(EgsimView):
158165
"""View returning the HTML page(s) explaining predictions table structure"""
159166

160-
def response(self,
161-
request: HttpRequest,
162-
data: dict,
163-
files: Optional[dict] = None) -> HttpResponseBase:
167+
def response(
168+
self,
169+
request: HttpRequest,
170+
data: dict,
171+
files: Optional[dict] = None
172+
) -> HttpResponseBase:
164173
"""Process the response from a given request and the data / files extracted from it"""
165174
from egsim.api.client.snippets.get_egsim_predictions import \
166175
get_egsim_predictions
@@ -182,10 +191,12 @@ def response(self,
182191
class ResidualsHtmlTutorial(EgsimView):
183192
"""View returning the HTML page(s) explaining residuals table structure"""
184193

185-
def response(self,
186-
request: HttpRequest,
187-
data: dict,
188-
files: Optional[dict] = None) -> HttpResponseBase:
194+
def response(
195+
self,
196+
request: HttpRequest,
197+
data: dict,
198+
files: Optional[dict] = None
199+
) -> HttpResponseBase:
189200
"""Process the response from a given request and the data / files
190201
extracted from it"""
191202
from egsim.api.client.snippets.get_egsim_residuals import \
@@ -240,8 +251,9 @@ def get_init_data_json(
240251
model_warnings.append(models.Gsim.adapted.field.help_text)
241252
if model_warnings:
242253
warning_text = "; ".join(model_warnings)
243-
warning_group_index = warning_groups.setdefault(warning_text,
244-
len(warning_groups))
254+
warning_group_index = warning_groups.setdefault(
255+
warning_text, len(warning_groups)
256+
)
245257
gsims.append([gsim.name, imt_group_index, sa_limits, warning_group_index])
246258
else:
247259
gsims.append([gsim.name, imt_group_index, sa_limits])

0 commit comments

Comments
 (0)