mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-30 18:09:59 +03:00
draft of using a form to sanitize query params
This commit is contained in:
parent
cc93eb2457
commit
ba38fc0729
|
@ -8,6 +8,7 @@ import operator
|
|||
import warnings
|
||||
from functools import reduce
|
||||
|
||||
from django import forms
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.db import models
|
||||
from django.db.models.constants import LOOKUP_SEP
|
||||
|
@ -24,6 +25,12 @@ from rest_framework.compat import (
|
|||
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):
|
||||
"""
|
||||
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,
|
||||
and may be comma and/or whitespace delimited.
|
||||
"""
|
||||
params = request.query_params.get(self.search_param, '')
|
||||
return params.replace(',', ' ').split()
|
||||
form = SearchFilterForm(self.search_param, request.query_params.dict())
|
||||
if form.is_valid():
|
||||
return form.cleaned_data[
|
||||
self.search_param
|
||||
].replace(',', ' ').split()
|
||||
|
||||
def construct_search(self, field_name):
|
||||
lookup = self.lookup_prefixes.get(field_name[0])
|
||||
|
|
|
@ -189,8 +189,10 @@ class SearchFilterTests(TestCase):
|
|||
filter_backends = (filters.SearchFilter,)
|
||||
search_fields = ('title', 'text')
|
||||
|
||||
payload = {'search': 'some funky string'}
|
||||
view = SearchListViewSet.as_view({'get': 'list'})
|
||||
request = factory.get('/', {'search': ',,,,'})
|
||||
# print(SearchListViewSet.__dict__)
|
||||
request = factory.get('/', payload)
|
||||
response = view(request)
|
||||
assert len(response.data) == 0
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user