Skip to content
Merged

Ruff #233

Show file tree
Hide file tree
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
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,10 @@ repos:
hooks:
- id: django-upgrade
args: ["--target-version=3.1"]

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.14.9
hooks:
- id: ruff-check
args: [ --fix ]
- id: ruff-format
96 changes: 49 additions & 47 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,31 @@
import re
import sys
from datetime import date
from importlib.util import find_spec

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
os.environ['RUNTIME_ENV'] = 'TESTSUITE'
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
try:
import django
import sphinx_rtd_theme
sys.path.insert(0, os.path.abspath(".."))
os.environ["RUNTIME_ENV"] = "TESTSUITE"
os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings"

if find_spec("django") and find_spec("sphinx_rtd_theme"):
use_sphinx_rtd_theme = True

import django

if hasattr(django, "setup"):
django.setup()

except ImportError:
use_sphinx_rtd_theme = os.environ.get('READTHEDOCS', False)
else:
use_sphinx_rtd_theme = os.environ.get("READTHEDOCS", False)


def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, '__init__.py')).read()
init_py = open(os.path.join(package, "__init__.py")).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)


Expand All @@ -40,35 +41,37 @@ def get_version(package):
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.extlinks',
'sphinx.ext.todo',
'sphinx.ext.viewcode']
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.extlinks",
"sphinx.ext.todo",
"sphinx.ext.viewcode",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"

# The master toctree document.
master_doc = 'index'
master_doc = "index"

# General information about the project.
project = 'drf_haystack'
copyright = '%d, Rolf Håvard Blindheim' % date.today().year
author = 'Rolf Håvard Blindheim'
project = "drf_haystack"
copyright = "%d, Rolf Håvard Blindheim" % date.today().year
author = "Rolf Håvard Blindheim"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The full version, including alpha/beta/rc tags.
version = release = get_version(os.path.join('..', 'drf_haystack'))
version = release = get_version(os.path.join("..", "drf_haystack"))

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand All @@ -80,10 +83,10 @@ def get_version(package):
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
Expand All @@ -94,7 +97,7 @@ def get_version(package):
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme' if use_sphinx_rtd_theme else 'alabaster'
html_theme = "sphinx_rtd_theme" if use_sphinx_rtd_theme else "alabaster"

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
Expand All @@ -105,28 +108,25 @@ def get_version(package):
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]


# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'drfhaystackdoc'
htmlhelp_basename = "drfhaystackdoc"


# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
'papersize': 'a4paper',

"papersize": "a4paper",
# The font size ('10pt', '11pt' or '12pt').
'pointsize': '11pt',

"pointsize": "11pt",
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',

# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
Expand All @@ -136,19 +136,15 @@ def get_version(package):
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'drf-haystack.tex', 'drf-haystack documentation',
'Inonit', 'manual'),
("index", "drf-haystack.tex", "drf-haystack documentation", "Inonit", "manual"),
]


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'drf-haystack', 'drf-haystack documentation',
['Inonit'], 1)
]
man_pages = [("index", "drf-haystack", "drf-haystack documentation", ["Inonit"], 1)]


# -- Options for Texinfo output -------------------------------------------
Expand All @@ -157,21 +153,27 @@ def get_version(package):
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'drf-haystack', 'drf-haystack documentation',
'Inonit', 'drf-haystack', 'Haystack for Django REST Framework',
'Miscellaneous'),
(
"index",
"drf-haystack",
"drf-haystack documentation",
"Inonit",
"drf-haystack",
"Haystack for Django REST Framework",
"Miscellaneous",
),
]

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'http://docs.python.org/': None,
'django': ('https://django.readthedocs.io/en/latest/', None),
'haystack': ('https://django-haystack.readthedocs.io/en/latest/', None)
"http://docs.python.org/": None,
"django": ("https://django.readthedocs.io/en/latest/", None),
"haystack": ("https://django-haystack.readthedocs.io/en/latest/", None),
}

# Configurations for extlinks
extlinks = {
'drf-pr': ('https://github.com/rhblind/drf-haystack/pull/%s', 'PR#'),
'drf-issue': ('https://github.com/rhblind/drf-haystack/issues/%s', '#'),
'haystack-issue': ('https://github.com/django-haystack/django-haystack/issues/%s', '#')
"drf-pr": ("https://github.com/rhblind/drf-haystack/pull/%s", "PR#"),
"drf-issue": ("https://github.com/rhblind/drf-haystack/issues/%s", "#"),
"haystack-issue": ("https://github.com/django-haystack/django-haystack/issues/%s", "#"),
}
1 change: 0 additions & 1 deletion drf_haystack/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import warnings


__title__ = "drf-haystack"
__version__ = "1.9.1"
__author__ = "Rolf Haavard Blindheim"
Expand Down
17 changes: 6 additions & 11 deletions drf_haystack/fields.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import six
from rest_framework import fields


class DRFHaystackFieldMixin:
prefix_field_names = False

def __init__(self, **kwargs):
self.prefix_field_names = kwargs.pop('prefix_field_names', False)
self.prefix_field_names = kwargs.pop("prefix_field_names", False)
super().__init__(**kwargs)

def bind(self, field_name, parent):
Expand All @@ -23,27 +22,26 @@ def bind(self, field_name, parent):
assert self.source != field_name, (
"It is redundant to specify `source='%s'` on field '%s' in "
"serializer '%s', because it is the same as the field name. "
"Remove the `source` keyword argument." %
(field_name, self.__class__.__name__, parent.__class__.__name__)
"Remove the `source` keyword argument." % (field_name, self.__class__.__name__, parent.__class__.__name__)
)

self.field_name = field_name
self.parent = parent

# `self.label` should default to being based on the field name.
if self.label is None:
self.label = field_name.replace('_', ' ').capitalize()
self.label = field_name.replace("_", " ").capitalize()

# self.source should default to being the same as the field name.
if self.source is None:
self.source = self.convert_field_name(field_name)

# self.source_attrs is a list of attributes that need to be looked up
# when serializing the instance, or populating the validated data.
if self.source == '*':
if self.source == "*":
self.source_attrs = []
else:
self.source_attrs = self.source.split('.')
self.source_attrs = self.source.split(".")

def convert_field_name(self, field_name):
if not self.prefix_field_names:
Expand Down Expand Up @@ -91,10 +89,7 @@ class FacetDictField(fields.DictField):
"""

def to_representation(self, value):
return {
str(key): self.child.to_representation(key, val)
for key, val in value.items()
}
return {str(key): self.child.to_representation(key, val) for key, val in value.items()}


class FacetListField(fields.ListField):
Expand Down
24 changes: 10 additions & 14 deletions drf_haystack/filters.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import operator
import six
from functools import reduce

import six
from django.core.exceptions import ImproperlyConfigured
from haystack.query import SearchQuerySet
from rest_framework.filters import BaseFilterBackend, OrderingFilter

from drf_haystack.query import BoostQueryBuilder, FilterQueryBuilder, FacetQueryBuilder, SpatialQueryBuilder
from drf_haystack.query import BoostQueryBuilder, FacetQueryBuilder, FilterQueryBuilder, SpatialQueryBuilder


class BaseHaystackFilterBackend(BaseFilterBackend):
Expand Down Expand Up @@ -57,7 +57,7 @@ def filter_queryset(self, request, queryset, view):
return self.apply_filters(
queryset=queryset,
applicable_filters=self.process_filters(applicable_filters, queryset, view),
applicable_exclusions=self.process_filters(applicable_exclusions, queryset, view)
applicable_exclusions=self.process_filters(applicable_exclusions, queryset, view),
)

def get_query_builder(self, *args, **kwargs):
Expand Down Expand Up @@ -109,9 +109,7 @@ def process_filters(self, filters, queryset, view):
for field_name, query in filters.children:
for word in query.split(" "):
bit = queryset.query.clean(word.strip())
kwargs = {
field_name: bit
}
kwargs = {field_name: bit}
query_bits.append(view.query_object(**kwargs))
return six.moves.reduce(operator.and_, filter(lambda x: x, query_bits))

Expand Down Expand Up @@ -243,16 +241,14 @@ def get_valid_fields(self, queryset, view, context={}):
"Cannot use %s with '__all__' as 'ordering_fields' attribute on a view "
"which has no 'index_models' set. Either specify some 'ordering_fields', "
"set the 'index_models' attribute or override the 'get_queryset' "
"method and pass some 'index_models'."
% self.__class__.__name__)
"method and pass some 'index_models'." % self.__class__.__name__
)

model_fields = map(lambda model: [(field.name, field.verbose_name) for field in model._meta.fields],
queryset.query.models)
model_fields = map(
lambda model: [(field.name, field.verbose_name) for field in model._meta.fields], queryset.query.models
)
valid_fields = list(set(reduce(operator.concat, model_fields)))
else:
valid_fields = [
(item, item) if isinstance(item, str) else item
for item in valid_fields
]
valid_fields = [(item, item) if isinstance(item, str) else item for item in valid_fields]

return valid_fields
10 changes: 5 additions & 5 deletions drf_haystack/generics.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import six

from django.contrib.contenttypes.models import ContentType
from django.http import Http404

from haystack.backends import SQ
from haystack.query import SearchQuerySet
from rest_framework.generics import GenericAPIView
Expand All @@ -14,6 +11,7 @@ class HaystackGenericAPIView(GenericAPIView):
"""
Base class for all haystack generic views.
"""

# Use `index_models` to filter on which search index models we
# should include in the search result.
index_models = []
Expand Down Expand Up @@ -72,8 +70,10 @@ def get_object(self):
ctype = ContentType.objects.get(app_label=app_label, model=model)
queryset = self.get_queryset(index_models=[ctype.model_class()])
except (ValueError, ContentType.DoesNotExist):
raise Http404("Could not find any models matching '%s'. Make sure to use a valid "
"'app_label.model' name for the 'model' query parameter." % self.request.query_params["model"])
raise Http404(
"Could not find any models matching '%s'. Make sure to use a valid "
"'app_label.model' name for the 'model' query parameter." % self.request.query_params["model"]
)

lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg not in self.kwargs:
Expand Down
6 changes: 2 additions & 4 deletions drf_haystack/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class FacetMixin:
facet_filter_backends = [HaystackFacetFilter]
facet_serializer_class = None
facet_objects_serializer_class = None
facet_query_params_text = 'selected_facets'
facet_query_params_text = "selected_facets"

@action(detail=False, methods=["get"], url_path="facets")
def facets(self, request):
Expand All @@ -48,7 +48,6 @@ def facets(self, request):
queryset = self.filter_facet_queryset(self.get_queryset())

for facet in request.query_params.getlist(self.facet_query_params_text):

if ":" not in facet:
continue

Expand Down Expand Up @@ -95,8 +94,7 @@ def get_facet_serializer_class(self):
if self.facet_serializer_class is None:
raise AttributeError(
"%(cls)s should either include a `facet_serializer_class` attribute, "
"or override %(cls)s.get_facet_serializer_class() method." %
{"cls": self.__class__.__name__}
"or override %(cls)s.get_facet_serializer_class() method." % {"cls": self.__class__.__name__}
)
return self.facet_serializer_class

Expand Down
Loading