Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add django REST framework
Roland Geiderf906cc8c287c
diff --git a/requirements.txt b/requirements.txtindex e7ff1d20e..454a1d07c 100644--- a/requirements.txt+++ b/requirements.txt@@ -11,4 +11,5 @@ python-mimeparsepilloweasy-thumbnailsdjango_compressor-icalendar\ No newline at end of file+icalendar+djangorestframework\ No newline at end of filediff --git a/wger/core/api/views.py b/wger/core/api/views.pynew file mode 100644index 000000000..93c410ea0--- /dev/null+++ b/wger/core/api/views.py@@ -0,0 +1,73 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++from rest_framework import viewsets++from wger.core.models import UserProfile, Language, DaysOfWeek, License+++class UserProfileViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = UserProfile++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return UserProfile.objects.filter(user=self.request.user)+++class LanguageViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = Language++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return Language.objects.all()+++class DaysOfWeekViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = DaysOfWeek++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return DaysOfWeek.objects.all()+++class LicenseViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = License++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return License.objects.all()+diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.pynew file mode 100644index 000000000..cc2886dc3--- /dev/null+++ b/wger/exercises/api/views.py@@ -0,0 +1,121 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++from rest_framework import viewsets+from rest_framework.decorators import link+from rest_framework.response import Response+from easy_thumbnails.alias import aliases+from easy_thumbnails.files import get_thumbnailer++from wger.exercises.api.serializers import ExerciseImageSerializer+from wger.exercises.models import Exercise+from wger.exercises.models import Equipment+from wger.exercises.models import ExerciseCategory+from wger.exercises.models import ExerciseImage+from wger.exercises.models import ExerciseComment+from wger.exercises.models import Muscle+++class ExerciseViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = Exercise++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return Exercise.objects.all()+++class EquipmentViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = Equipment++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return Equipment.objects.all()+++class ExerciseCategoryViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = ExerciseCategory++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return ExerciseCategory.objects.all()+++class ExerciseImageViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for exercise image objects+ '''+ model = ExerciseImage++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return ExerciseImage.objects.all()++ @link()+ def thumbnails(self, request, pk):+ '''+ Return a list of the image's thumbnails+ '''+ image = ExerciseImage.objects.get(pk=pk)+ thumbnails = {}+ for alias in aliases.all():+ t = get_thumbnailer(image.image)+ thumbnails[alias] = {'url': t.get_thumbnail(aliases.get(alias)).url,+ 'settings': aliases.get(alias)}+ return Response(thumbnails)+++class ExerciseCommentViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = ExerciseComment++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return ExerciseComment.objects.all()+++class MuscleViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = Muscle++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return Muscle.objects.all()\ No newline at end of filediff --git a/wger/manager/api/serializers.py b/wger/manager/api/serializers.pynew file mode 100644index 000000000..4174a796a--- /dev/null+++ b/wger/manager/api/serializers.py@@ -0,0 +1,47 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++from rest_framework import serializers+from rest_framework.decorators import link+from rest_framework.response import Response++from wger.manager.models import Workout+from wger.manager.models import WorkoutSession+++class WorkoutSerializer(serializers.ModelSerializer):+ '''+ Workout serializer+ '''++ #canonical_representation = serializers.SerializerMethodField('get_canonical_representation')++ class Meta:+ model = Workout+ exclude = ('user',)++ def get_canonical_representation(self, obj):+ return obj.canonical_representation+++class WorkoutSessionSerializer(serializers.ModelSerializer):+ '''+ Workout session serializer+ '''+ class Meta:+ model = WorkoutSession+ exclude = ('user',)diff --git a/wger/manager/api/views.py b/wger/manager/api/views.pynew file mode 100644index 000000000..bcab828cb--- /dev/null+++ b/wger/manager/api/views.py@@ -0,0 +1,137 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.+from django.http.response import HttpResponse++from rest_framework import viewsets+from rest_framework.decorators import link+from rest_framework.response import Response++from wger.manager.api.serializers import WorkoutSerializer+from wger.manager.api.serializers import WorkoutSessionSerializer++from wger.manager.models import Workout+from wger.manager.models import ScheduleStep+from wger.manager.models import Schedule+from wger.manager.models import Day+from wger.manager.models import Setting+from wger.manager.models import WorkoutLog+from wger.manager.models import WorkoutSession+++class WorkoutViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout objects+ '''+ model = Workout+ serializer_class = WorkoutSerializer++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return Workout.objects.filter(user=self.request.user)++ def pre_save(self, obj):+ '''+ Set the owner+ '''+ obj.user = self.request.user+++class WorkoutSessionViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout sessions objects+ '''+ model = WorkoutSession+ serializer_class = WorkoutSessionSerializer++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return WorkoutSession.objects.filter(user=self.request.user)++ def pre_save(self, obj):+ '''+ Set the owner+ '''+ obj.user = self.request.user+++class ScheduleStepViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for schedule step objects+ '''+ model = ScheduleStep++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return ScheduleStep.objects.filter(schedule__user=self.request.user)+++class ScheduleViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for schedule objects+ '''+ model = Schedule++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return Schedule.objects.filter(user=self.request.user)+++class DayViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for training day objects+ '''+ model = Day++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return Day.objects.filter(training__user=self.request.user)+++class SettingViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for repetition setting objects+ '''+ model = Setting++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return Setting.objects.filter(set__exerciseday__training__user=self.request.user)+++class WorkoutLogViewSet(viewsets.ModelViewSet):+ '''+ API endpoint for workout log objects+ '''+ model = WorkoutLog++ def get_queryset(self):+ '''+ Only allow access to appropriate objects+ '''+ return WorkoutLog.objects.filter(user=self.request.user)\ No newline at end of filediff --git a/wger/settings_global.py b/wger/settings_global.pyindex 35bfaf017..a0faaee12 100644--- a/wger/settings_global.py+++ b/wger/settings_global.py@@ -223,6 +223,9 @@ INSTALLED_APPS = (# CSS/JS compressor'compressor',++ # REST framework+ 'rest_framework',)@@ -330,3 +333,10 @@ THUMBNAIL_ALIASES = {# The default is not DEBUG, override if needed# COMPRESS_ENABLED = TrueCOMPRESS_ROOT = STATIC_ROOT+++REST_FRAMEWORK = {+ 'DEFAULT_PERMISSION_CLASSES': ('wger.utils.permissions.WgerPermission',),+ 'PAGINATE_BY': 20,+ 'PAGINATE_BY_PARAM': 'limit', # Allow client to override, using `?limit=xxx`.+}\ No newline at end of filediff --git a/wger/urls.py b/wger/urls.pyindex a70c2198f..0f9a1d679 100644--- a/wger/urls.py+++ b/wger/urls.py@@ -16,27 +16,35 @@# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.from tastypie.api import Api+from rest_framework import routersfrom django.conf.urls import include, urlfrom django.conf.urls.i18n import i18n_patternsfrom django.conf.urls.i18n import patterns-from wger.exercises.sitemap import ExercisesSitemap-from wger.exercises.api import resources as exercises_apifrom wger.nutrition.sitemap import NutritionSitemap-from wger.nutrition.api import resources as nutrition_api+from wger.exercises.sitemap import ExercisesSitemap+from wger.utils.generic_views import TextTemplateViewfrom wger.utils.generic_views import WebappManifestView++from wger.exercises.api import resources as exercises_api+from wger.nutrition.api import resources as nutrition_apifrom wger.manager.api import resources as manager_apifrom wger.core.api import resources as core_apifrom wger.weight.api import resources as weight_api+from wger.manager.api import views as manager_api_views+from wger.core.api import views as core_api_views+from wger.exercises.api import views as exercises_api_views+## REST API#++### /api/v1 - tastypie - deprecatedv1_api = Api(api_name='v1')-# Exercises appv1_api.register(exercises_api.ExerciseCategoryResource())v1_api.register(exercises_api.ExerciseCommentResource())v1_api.register(exercises_api.ExerciseImageResource())@@ -44,7 +52,6 @@ v1_api.register(exercises_api.ExerciseResource())v1_api.register(exercises_api.MuscleResource())v1_api.register(exercises_api.EquipmentResource())-# Nutrition appv1_api.register(nutrition_api.IngredientResource())v1_api.register(nutrition_api.WeightUnitResource())v1_api.register(nutrition_api.NutritionPlanResource())@@ -52,7 +59,6 @@ v1_api.register(nutrition_api.MealResource())v1_api.register(nutrition_api.MealItemResource())v1_api.register(nutrition_api.IngredientToWeightUnit())-# Manager appv1_api.register(manager_api.WorkoutResource())v1_api.register(manager_api.ScheduleResource())v1_api.register(manager_api.ScheduleStepResource())@@ -62,17 +68,45 @@ v1_api.register(manager_api.SettingResource())v1_api.register(manager_api.WorkoutLogResource())v1_api.register(manager_api.WorkoutSessionResource())-# Weight appv1_api.register(weight_api.WeightEntryResource())--# Core appv1_api.register(core_api.LanguageResource())v1_api.register(core_api.DaysOfWeekResource())v1_api.register(core_api.UserProfileResource())v1_api.register(core_api.LicenseResource())+### /api/v2 - django rest framework+router = routers.DefaultRouter()++# Manager app+router.register(r'workout', manager_api_views.WorkoutViewSet)+router.register(r'workoutsession', manager_api_views.WorkoutSessionViewSet)+router.register(r'schedulestep', manager_api_views.ScheduleStepViewSet)+router.register(r'schedule', manager_api_views.ScheduleViewSet)+router.register(r'day', manager_api_views.DayViewSet)+router.register(r'setting', manager_api_views.SettingViewSet)+router.register(r'workoutlog', manager_api_views.WorkoutLogViewSet)++# Core app+router.register(r'userprofile', core_api_views.UserProfileViewSet)+router.register(r'language', core_api_views.LanguageViewSet)+router.register(r'daysofweek', core_api_views.DaysOfWeekViewSet)+router.register(r'license', core_api_views.LicenseViewSet)++# Exercises app+router.register(r'exercise', exercises_api_views.ExerciseViewSet)+router.register(r'equipment', exercises_api_views.EquipmentViewSet)+router.register(r'exercisecategory', exercises_api_views.ExerciseCategoryViewSet)+router.register(r'exerciseimage', exercises_api_views.ExerciseImageViewSet)+router.register(r'exercisecomment', exercises_api_views.ExerciseCommentViewSet)+router.register(r'muscle', exercises_api_views.MuscleViewSet)++# Nutrition app++# Weight app++from django.contrib import adminadmin.autodiscover()@@ -82,7 +116,6 @@ admin.autodiscover()sitemaps = {'exercises': ExercisesSitemap,'nutrition': NutritionSitemap}-## The actual URLs#@@ -102,15 +135,15 @@ urlpatterns = i18n_patterns('',name='sitemap'))-# Send these static files without any language prefix+#+# URLs without language prefix+#urlpatterns = urlpatterns + patterns('',url(r'^robots\.txt$',TextTemplateView.as_view(template_name="robots.txt"),name='robots'),- url(r'^manifest\.webapp$',- WebappManifestView.as_view(template_name="manifest.webapp"),- ),url(r'^amazon-manifest\.webapp$',- WebappManifestView.as_view(template_name="amazon-manifest.webapp"),- ),- (r'^api/', include(v1_api.urls)),+ url(r'^manifest\.webapp$', WebappManifestView.as_view(template_name="manifest.webapp")),+ url(r'^amazon-manifest\.webapp$', WebappManifestView.as_view(template_name="amazon-manifest.webapp")),+ url(r'api/v2/', include(router.urls)),+ url(r'^api/', include(v1_api.urls)),)diff --git a/wger/utils/permissions.py b/wger/utils/permissions.pynew file mode 100644index 000000000..f4f62d92b--- /dev/null+++ b/wger/utils/permissions.py@@ -0,0 +1,45 @@+# -*- coding: utf-8 -*-++# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++from rest_framework import permissions+++class WgerPermission(permissions.BasePermission):+ '''+ Checks that the user has access to the object++ If the object has a 'owner_object' method, only allow access for the owner+ user. For the other objects (system wide objects like exercises, etc.) allow+ only safe methods (GET, HEAD or OPTIONS)+ '''++ def has_object_permission(self, request, view, obj):+ '''+ Perform the check+ '''+ owner_object = obj.get_owner_object() if hasattr(obj, 'get_owner_object') else False++ # Owner+ if owner_object and owner_object.user == request.user:+ return True++ # 'global' objects only for GET, HEAD or OPTIONS+ if not owner_object and request.method in permissions.SAFE_METHODS:+ return True++ # Everything else is a no-no+ return False\ No newline at end of file