draft of using a form to sanitize query params

This commit is contained in:
Jón Levy 2019-04-14 14:33:37 +00:00
parent cc93eb2457
commit ba38fc0729
2 changed files with 15 additions and 3 deletions

View File

@ -8,6 +8,7 @@ import operator
import warnings import warnings
from functools import reduce from functools import reduce
from django import forms
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.db import models from django.db import models
from django.db.models.constants import LOOKUP_SEP from django.db.models.constants import LOOKUP_SEP
@ -24,6 +25,12 @@ from rest_framework.compat import (
from rest_framework.settings import api_settings from rest_framework.settings import api_settings
class SearchFilterForm(forms.Form):
def __init__(self, search_field, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields[search_field] = forms.CharField()
class BaseFilterBackend(object): class BaseFilterBackend(object):
""" """
A base class from which all filter backend classes should inherit. A base class from which all filter backend classes should inherit.
@ -67,8 +74,11 @@ class SearchFilter(BaseFilterBackend):
Search terms are set by a ?search=... query parameter, Search terms are set by a ?search=... query parameter,
and may be comma and/or whitespace delimited. and may be comma and/or whitespace delimited.
""" """
params = request.query_params.get(self.search_param, '') form = SearchFilterForm(self.search_param, request.query_params.dict())
return params.replace(',', ' ').split() if form.is_valid():
return form.cleaned_data[
self.search_param
].replace(',', ' ').split()
def construct_search(self, field_name): def construct_search(self, field_name):
lookup = self.lookup_prefixes.get(field_name[0]) lookup = self.lookup_prefixes.get(field_name[0])

View File

@ -189,8 +189,10 @@ class SearchFilterTests(TestCase):
filter_backends = (filters.SearchFilter,) filter_backends = (filters.SearchFilter,)
search_fields = ('title', 'text') search_fields = ('title', 'text')
payload = {'search': 'some funky string'}
view = SearchListViewSet.as_view({'get': 'list'}) view = SearchListViewSet.as_view({'get': 'list'})
request = factory.get('/', {'search': ',,,,'}) # print(SearchListViewSet.__dict__)
request = factory.get('/', payload)
response = view(request) response = view(request)
assert len(response.data) == 0 assert len(response.data) == 0