Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle exceptions #162

Open
wants to merge 4 commits into
base: 7.0
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions seeker/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def __init__(self, field, label=None, sort=None, value_format=None, template=Non
self.export = export
self.highlight = highlight
self.field_definition = field_definition
self.sr_class = 'sr-only'

def __str__(self):
return self.label
Expand Down Expand Up @@ -114,7 +115,7 @@ def header(self):
else:
q['s'] = self.field
next_sort = 'descending' if sort == 'Ascending' else 'ascending'
sr_label = format_html(' <span class="sr-only">({})</span>', sort) if sort else ''
sr_label = format_html(f' <span class="{self.sr_class}">({sort})</span>') if sort else ''
if self.field_definition:
data_attributes_html = ' '.join(f'data-{name}="{value}"' for name, value in self.view.field_definition_data_attrs.items())
span = format_html('<span {} title="{{}}" class="fa fa-question-circle"></span>'.format(data_attributes_html), self.field_definition)
Expand Down Expand Up @@ -1194,7 +1195,7 @@ def header(self, results=None):
data_sort = self.field

next_sort = 'descending' if sort == 'Ascending' else 'ascending'
sr_label = format_html(' <span class="sr-only">({})</span>', sort) if sort else ''
sr_label = format_html(f' <span class="{self.sr_class}">({sort})</span>') if sort else ''

# If results provided, we check to see if header has space to allow for wordwrapping. If it already wordwrapped
# (i.e. has <br> in header) we skip it.
Expand Down Expand Up @@ -1518,6 +1519,8 @@ def post(self, request, *args, **kwargs):
if is_ajax(request) or export:
try:
string_search_object = request.POST.get('search_object')
if not isinstance(string_search_object, (str, bytes, bytearray)):
return Http404(f'Invalid POST data type: {type(string_search_object)}')
# We attach this to self so AdvancedColumn can have access to it
self.search_object = json.loads(string_search_object)
except KeyError:
Expand Down Expand Up @@ -1659,10 +1662,13 @@ def render_results(self, export):
# Finally, grab the results.
sort = self.get_sort_field(columns, self.search_object['sort'], display)
if sort:
if (self.missing_sort is None or isinstance(sort, dict)) and isinstance(sort, list):
results = search.sort(*self.sort_descriptor(sort))[offset:upper_paging_limit].execute()
else:
results = search.sort(self.sort_descriptor(sort))[offset:upper_paging_limit].execute()
try:
if (self.missing_sort is None or isinstance(sort, dict)) and isinstance(sort, list):
results = search.sort(*self.sort_descriptor(sort))[offset:upper_paging_limit].execute()
else:
results = search.sort(self.sort_descriptor(sort))[offset:upper_paging_limit].execute()
except Exception as e:
return Http404(f'Invalid sort: {str(e)}')
else:
results = search[offset:upper_paging_limit].execute()

Expand Down Expand Up @@ -1784,6 +1790,8 @@ def build_query(self, advanced_query, facet_lookup, excluded_facets=[]):
if all(k in advanced_query for k in ('id', 'operator', 'value')):
if advanced_query['id'] not in excluded_facets:
facet = facet_lookup.get(advanced_query['id'])
if not facet:
raise Http404(f'Invalid facet: {advanced_query["id"]}')
return facet.query(advanced_query['operator'], advanced_query['value']), [facet.field]
return None, None

Expand All @@ -1792,7 +1800,7 @@ def build_query(self, advanced_query, facet_lookup, excluded_facets=[]):
condition = advanced_query.get('condition')
group_operator = self.boolean_translations.get(condition, None)
if not group_operator:
raise ValueError("'{}' is not a valid boolean operator.".format(condition))
return Http404(f"'{condition}' is not a valid boolean operator.")

queries = []
selected_facets = []
Expand Down Expand Up @@ -1878,7 +1886,7 @@ def get(self, request, *args, **kwargs):
try:
url = request.GET.get(self.url_parameter)
except KeyError:
return JsonResponse({ 'error': 'No URL provided.' }, 400)
return JsonResponse({ 'error': 'No URL provided.' }, status=400)

SavedSearchModel = self.get_saved_search_model()
saved_searches = self.get_saved_searches(url, SavedSearchModel)
Expand All @@ -1887,7 +1895,7 @@ def get(self, request, *args, **kwargs):
try:
saved_search = saved_searches.get(pk=search_pk)
except SavedSearchModel.DoesNotExist:
return JsonResponse({ 'error': 'Saved search not found.' }, 400)
return JsonResponse({ 'error': 'Saved search not found.' }, status=400)
else:
# By design this will return None if there are no default searches found
saved_search = saved_searches.filter(default=True).first()
Expand Down Expand Up @@ -1916,7 +1924,7 @@ def post(self, request, *args, **kwargs):
try:
url = request.POST.get(self.url_parameter)
except KeyError:
return JsonResponse({'error': 'No URL provided.'}, 400)
return JsonResponse({'error': 'No URL provided.'}, status=400)

search_pk = kwargs.get(self.pk_parameter, request.POST.get(self.pk_parameter, None))
SavedSearchModel = self.get_saved_search_model()
Expand All @@ -1933,7 +1941,7 @@ def post(self, request, *args, **kwargs):
except SavedSearchModel.DoesNotExist:
# We only want to throw an error if we cannot find the object AND we are NOT trying to delete it anyway
if not delete:
return JsonResponse({'error': 'Saved search not found.'}, 400)
return JsonResponse({'error': 'Saved search not found.'}, status=400)

data = {}
# We have three paths: delete, modify_default, or save
Expand Down