Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Re-add the old search endpoint

Roland Geidercb7079299a07
diff --git a/wger/nutrition/api/views.py b/wger/nutrition/api/views.py
index 2e11bdf59..1e3403bc2 100644
--- a/wger/nutrition/api/views.py
+++ b/wger/nutrition/api/views.py
@@ -20,12 +20,17 @@ import logging
# Django
from django.conf import settings
+from django.contrib.postgres.search import TrigramSimilarity
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
-
# Third Party
+from easy_thumbnails.alias import aliases
+from easy_thumbnails.files import get_thumbnailer
from rest_framework import viewsets
-from rest_framework.decorators import action
+from rest_framework.decorators import (
+ action,
+ api_view,
+)
from rest_framework.response import Response
# wger
@@ -57,9 +62,14 @@ from wger.nutrition.models import (
NutritionPlan,
WeightUnit,
)
+from wger.utils.constants import (
+ ENGLISH_SHORT_NAME,
+ SEARCH_ALL_LANGUAGES,
+)
+from wger.utils.db import is_postgres_db
+from wger.utils.language import load_language
from wger.utils.viewsets import WgerOwnerObjectModelViewSet
-
logger = logging.getLogger(__name__)
@@ -132,6 +142,68 @@ class IngredientInfoViewSet(IngredientViewSet):
serializer_class = IngredientInfoSerializer
+@api_view(['GET'])
+def search(request):
+ """
+ NOTE: this endpoint is not used anymore and will be removed in the very
+ near future, but is kept here for backwards compatibility. When that
+ happens, SEARCH_ALL_LANGUAGES can be removed as well.
+ """
+ term = request.GET.get('term', None)
+ language_codes = request.GET.get('language', ENGLISH_SHORT_NAME)
+ results = []
+ response = {}
+
+ if not term:
+ return Response(response)
+
+ query = Ingredient.objects.all()
+
+ # Filter the appropriate languages
+ languages = [load_language(l) for l in language_codes.split(',')]
+ if language_codes != SEARCH_ALL_LANGUAGES:
+ query = query.filter(
+ language__in=languages,
+ )
+
+ query = query.only('name')
+
+ # Postgres uses a full-text search
+ if is_postgres_db():
+ query = (
+ query.annotate(similarity=TrigramSimilarity('name', term))
+ .filter(similarity__gt=0.15)
+ .order_by('-similarity', 'name')
+ )
+ else:
+ query = query.filter(name__icontains=term)
+
+ for ingredient in query[:150]:
+ if hasattr(ingredient, 'image'):
+ image_obj = ingredient.image
+ image = image_obj.image.url
+ t = get_thumbnailer(image_obj.image)
+ thumbnail = t.get_thumbnail(aliases.get('micro_cropped')).url
+ else:
+ ingredient.get_image(request)
+ image = None
+ thumbnail = None
+
+ ingredient_json = {
+ 'value': ingredient.name,
+ 'data': {
+ 'id': ingredient.id,
+ 'name': ingredient.name,
+ 'image': image,
+ 'image_thumbnail': thumbnail,
+ },
+ }
+ results.append(ingredient_json)
+ response['suggestions'] = results
+
+ return Response(response)
+
+
class ImageViewSet(viewsets.ReadOnlyModelViewSet):
"""
API endpoint for ingredient images
diff --git a/wger/urls.py b/wger/urls.py
index 8f2fd796b..4853c6128 100644
--- a/wger/urls.py
+++ b/wger/urls.py
@@ -25,7 +25,6 @@ from django.contrib.sitemaps.views import (
sitemap,
)
from django.urls import path
-
# Third Party
from django_email_verification import urls as email_urls
from drf_spectacular.views import (
@@ -51,7 +50,6 @@ from wger.nutrition.api import views as nutrition_api_views
from wger.utils.generic_views import TextTemplateView
from wger.weight.api import views as weight_api_views
-
#
# REST API
#
@@ -290,6 +288,7 @@ urlpatterns += [
path('robots.txt', TextTemplateView.as_view(template_name='robots.txt'), name='robots'),
# API
path('api/v2/exercise/search/', exercises_api_views.search, name='exercise-search'),
+ path('api/v2/ingredient/search/', nutrition_api_views.search, name='ingredient-search'),
path('api/v2/', include(router.urls)),
# The api user login
path(