Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add helper to fetch results from a paginated endpoint

Roland Geider607d43487506
diff --git a/wger/core/models/profile.py b/wger/core/models/profile.py
index 8edda7b73..ba7ca646f 100644
--- a/wger/core/models/profile.py
+++ b/wger/core/models/profile.py
@@ -523,8 +523,8 @@ by the US Department of Agriculture. It is extremely complete, with around
"""
if (
not WeightEntry.objects.filter(user=self.user).exists() or (
- datetime.date.today() - WeightEntry.objects.filter(user=self.user).latest().date
- > datetime.timedelta(days=3)
+ datetime.date.today() - WeightEntry.objects.filter(user=self.user).latest().date >
+ datetime.timedelta(days=3)
)
):
entry = WeightEntry()
diff --git a/wger/exercises/sync.py b/wger/exercises/sync.py
index 6ce24eb20..829aceffe 100644
--- a/wger/exercises/sync.py
+++ b/wger/exercises/sync.py
@@ -53,7 +53,10 @@ from wger.exercises.models import (
ExerciseVideo,
Muscle,
)
-from wger.utils.requests import wger_headers
+from wger.utils.requests import (
+ get_paginated,
+ wger_headers,
+)
from wger.utils.url import make_uri
@@ -65,71 +68,63 @@ def sync_exercises(
"""Synchronize the exercises from the remote server"""
print_fn('*** Synchronizing exercises...')
- page = 1
- all_exercise_processed = False
url = make_uri(EXERCISE_ENDPOINT, server_url=remote_url, query={'limit': 100})
headers = wger_headers()
- result = requests.get(url, headers=headers).json()
- while not all_exercise_processed:
-
- for data in result['results']:
-
- uuid = data['uuid']
- license_id = data['license']['id']
- category_id = data['category']['id']
- license_author = data['license_author']
- equipment = [Equipment.objects.get(pk=i['id']) for i in data['equipment']]
- muscles = [Muscle.objects.get(pk=i['id']) for i in data['muscles']]
- muscles_sec = [Muscle.objects.get(pk=i['id']) for i in data['muscles_secondary']]
-
- base, base_created = ExerciseBase.objects.update_or_create(
- uuid=uuid,
- defaults={'category_id': category_id},
+ result = get_paginated(url, headers=headers)
+
+ for data in result:
+
+ uuid = data['uuid']
+ license_id = data['license']['id']
+ category_id = data['category']['id']
+ license_author = data['license_author']
+ equipment = [Equipment.objects.get(pk=i['id']) for i in data['equipment']]
+ muscles = [Muscle.objects.get(pk=i['id']) for i in data['muscles']]
+ muscles_sec = [Muscle.objects.get(pk=i['id']) for i in data['muscles_secondary']]
+
+ base, base_created = ExerciseBase.objects.update_or_create(
+ uuid=uuid,
+ defaults={'category_id': category_id},
+ )
+ print_fn(f"{'created' if base_created else 'updated'} exercise {uuid}")
+
+ base.muscles.set(muscles)
+ base.muscles_secondary.set(muscles_sec)
+ base.equipment.set(equipment)
+ base.save()
+
+ for translation_data in data['exercises']:
+ trans_uuid = translation_data['uuid']
+ name = translation_data['name']
+ description = translation_data['description']
+ language_id = translation_data['language']
+
+ translation, translation_created = Exercise.objects.update_or_create(
+ uuid=trans_uuid,
+ defaults={
+ 'exercise_base': base,
+ 'name': name,
+ 'description': description,
+ 'license_id': license_id,
+ 'license_author': license_author,
+ 'language_id': language_id,
+ },
)
- print_fn(f"{'created' if base_created else 'updated'} exercise {uuid}")
-
- base.muscles.set(muscles)
- base.muscles_secondary.set(muscles_sec)
- base.equipment.set(equipment)
- base.save()
-
- for translation_data in data['exercises']:
- trans_uuid = translation_data['uuid']
- name = translation_data['name']
- description = translation_data['description']
- language_id = translation_data['language']
-
- translation, translation_created = Exercise.objects.update_or_create(
- uuid=trans_uuid,
- defaults={
- 'exercise_base': base,
- 'name': name,
- 'description': description,
- 'license_id': license_id,
- 'license_author': license_author,
- 'language_id': language_id,
- },
+ out = f"- {'created' if translation_created else 'updated'} translation " \
+ f"{translation.language.short_name} {trans_uuid} - {name}"
+ print_fn(out)
+
+ for note in translation_data['notes']:
+ ExerciseComment.objects.get_or_create(
+ exercise=translation,
+ comment=note['comment'],
)
- out = f"- {'created' if translation_created else 'updated'} translation " \
- f"{translation.language.short_name} {trans_uuid} - {name}"
- print_fn(out)
-
- for note in translation_data['notes']:
- ExerciseComment.objects.get_or_create(
- exercise=translation,
- comment=note['comment'],
- )
- for alias in translation_data['aliases']:
- Alias.objects.get_or_create(exercise=translation, alias=alias)
+ for alias in translation_data['aliases']:
+ Alias.objects.get_or_create(exercise=translation, alias=alias)
- print_fn('')
+ print_fn('')
- if result['next']:
- page += 1
- result = requests.get(result['next'], headers=headers).json()
- else:
- all_exercise_processed = True
print_fn(style_fn('done!\n'))
@@ -142,8 +137,8 @@ def sync_languages(
print_fn('*** Synchronizing languages...')
headers = wger_headers()
url = make_uri(LANGUAGE_ENDPOINT, server_url=remote_url)
- result = requests.get(url, headers=headers).json()
- for data in result['results']:
+ result = get_paginated(url, headers=headers)
+ for data in result:
short_name = data['short_name']
full_name = data['full_name']
@@ -167,8 +162,8 @@ def sync_licenses(
print_fn('*** Synchronizing licenses...')
headers = wger_headers()
url = make_uri(LICENSE_ENDPOINT, server_url=remote_url)
- result = requests.get(url, headers=headers).json()
- for data in result['results']:
+ result = get_paginated(url, headers=headers)
+ for data in result:
short_name = data['short_name']
full_name = data['full_name']
license_url = data['url']
@@ -197,8 +192,8 @@ def sync_categories(
print_fn('*** Synchronizing categories...')
headers = wger_headers()
url = make_uri(CATEGORY_ENDPOINT, server_url=remote_url)
- result = requests.get(url, headers=headers).json()
- for data in result['results']:
+ result = get_paginated(url, headers=headers)
+ for data in result:
category_id = data['id']
category_name = data['name']
@@ -223,8 +218,9 @@ def sync_muscles(
print_fn('*** Synchronizing muscles...')
headers = wger_headers()
url = make_uri(MUSCLE_ENDPOINT, server_url=remote_url)
- result = requests.get(url, headers=headers).json()
- for data in result['results']:
+ result = get_paginated(url, headers=headers)
+
+ for data in result:
muscle_id = data['id']
muscle_name = data['name']
muscle_is_front = data['is_front']
@@ -259,8 +255,9 @@ def sync_equipment(
headers = wger_headers()
url = make_uri(EQUIPMENT_ENDPOINT, server_url=remote_url)
- result = requests.get(url, headers=headers).json()
- for data in result['results']:
+ result = get_paginated(url, headers=headers)
+
+ for data in result:
equipment_id = data['id']
equipment_name = data['name']
@@ -283,54 +280,45 @@ def delete_entries(
"""Delete exercises that were removed on the server"""
print_fn('*** Deleting exercises data that was removed on the server...')
- page = 1
- all_entries_processed = False
headers = wger_headers()
url = make_uri(DELETION_LOG_ENDPOINT, server_url=remote_url, query={'limit': 100})
- result = requests.get(url, headers=headers).json()
- while not all_entries_processed:
- for data in result['results']:
- uuid = data['uuid']
- model_type = data['model_type']
-
- if model_type == DeletionLog.MODEL_BASE:
- try:
- obj = ExerciseBase.objects.get(uuid=uuid)
- obj.delete()
- print_fn(f'Deleted exercise base {uuid}')
- except ExerciseBase.DoesNotExist:
- pass
-
- elif model_type == DeletionLog.MODEL_TRANSLATION:
- try:
- obj = Exercise.objects.get(uuid=uuid)
- obj.delete()
- print_fn(f"Deleted translation {uuid} ({data['comment']})")
- except Exercise.DoesNotExist:
- pass
-
- elif model_type == DeletionLog.MODEL_IMAGE:
- try:
- obj = ExerciseImage.objects.get(uuid=uuid)
- obj.delete()
- print_fn(f'Deleted image {uuid}')
- except ExerciseImage.DoesNotExist:
- pass
-
- elif model_type == DeletionLog.MODEL_VIDEO:
- try:
- obj = ExerciseVideo.objects.get(uuid=uuid)
- obj.delete()
- print_fn(f'Deleted video {uuid}')
- except ExerciseVideo.DoesNotExist:
- pass
-
- if result['next']:
- page += 1
- result = requests.get(result['next'], headers=headers).json()
- else:
- all_entries_processed = True
- print_fn(style_fn('done!\n'))
+ result = get_paginated(url, headers=headers)
+
+ for data in result:
+ uuid = data['uuid']
+ model_type = data['model_type']
+
+ if model_type == DeletionLog.MODEL_BASE:
+ try:
+ obj = ExerciseBase.objects.get(uuid=uuid)
+ obj.delete()
+ print_fn(f'Deleted exercise base {uuid}')
+ except ExerciseBase.DoesNotExist:
+ pass
+
+ elif model_type == DeletionLog.MODEL_TRANSLATION:
+ try:
+ obj = Exercise.objects.get(uuid=uuid)
+ obj.delete()
+ print_fn(f"Deleted translation {uuid} ({data['comment']})")
+ except Exercise.DoesNotExist:
+ pass
+
+ elif model_type == DeletionLog.MODEL_IMAGE:
+ try:
+ obj = ExerciseImage.objects.get(uuid=uuid)
+ obj.delete()
+ print_fn(f'Deleted image {uuid}')
+ except ExerciseImage.DoesNotExist:
+ pass
+
+ elif model_type == DeletionLog.MODEL_VIDEO:
+ try:
+ obj = ExerciseVideo.objects.get(uuid=uuid)
+ obj.delete()
+ print_fn(f'Deleted video {uuid}')
+ except ExerciseVideo.DoesNotExist:
+ pass
def download_exercise_images(
@@ -338,58 +326,47 @@ def download_exercise_images(
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
- page = 1
- all_images_processed = False
headers = wger_headers()
url = make_uri(IMAGE_ENDPOINT, server_url=remote_url)
- result = requests.get(url, headers=headers).json()
- print_fn('*** Processing images ***')
- while not all_images_processed:
- print_fn('')
- print_fn(f'*** Page {page}')
- print_fn('')
-
- for image_data in result['results']:
- image_uuid = image_data['uuid']
-
- print_fn(f'Processing image {image_uuid}')
-
- try:
- exercise_base = ExerciseBase.objects.get(uuid=image_data['exercise_base_uuid'])
- except ExerciseBase.DoesNotExist:
- print_fn(' Remote exercise base not found in local DB, skipping...')
- continue
+ result = get_paginated(url, headers=headers)
- try:
- ExerciseImage.objects.get(uuid=image_uuid)
- print_fn(' Image already present locally, skipping...')
- continue
- except ExerciseImage.DoesNotExist:
- print_fn(' Image not found in local DB, creating now...')
- retrieved_image = requests.get(image_data['image'], headers=headers)
- image = ExerciseImage.from_json(exercise_base, retrieved_image, image_data)
-
- # Temporary files on Windows don't support the delete attribute
- if os.name == 'nt':
- img_temp = NamedTemporaryFile()
- else:
- img_temp = NamedTemporaryFile(delete=True)
- img_temp.write(retrieved_image.content)
- img_temp.flush()
-
- image.exercise_base = exercise_base
- image.image.save(
- os.path.basename(os.path.basename(image_data['image'])),
- File(img_temp),
- )
- image.save()
- print_fn(style_fn(' successfully saved'))
+ print_fn('*** Processing images ***')
- if result['next']:
- page += 1
- result = requests.get(result['next'], headers=headers).json()
+ for image_data in result:
+ image_uuid = image_data['uuid']
+
+ print_fn(f'Processing image {image_uuid}')
+
+ try:
+ exercise_base = ExerciseBase.objects.get(uuid=image_data['exercise_base_uuid'])
+ except ExerciseBase.DoesNotExist:
+ print_fn(' Remote exercise base not found in local DB, skipping...')
+ continue
+
+ try:
+ ExerciseImage.objects.get(uuid=image_uuid)
+ print_fn(' Image already present locally, skipping...')
+ continue
+ except ExerciseImage.DoesNotExist:
+ print_fn(' Image not found in local DB, creating now...')
+ retrieved_image = requests.get(image_data['image'], headers=headers)
+ image = ExerciseImage.from_json(exercise_base, retrieved_image, image_data)
+
+ # Temporary files on Windows don't support the delete attribute
+ if os.name == 'nt':
+ img_temp = NamedTemporaryFile()
else:
- all_images_processed = True
+ img_temp = NamedTemporaryFile(delete=True)
+ img_temp.write(retrieved_image.content)
+ img_temp.flush()
+
+ image.exercise_base = exercise_base
+ image.image.save(
+ os.path.basename(os.path.basename(image_data['image'])),
+ File(img_temp),
+ )
+ image.save()
+ print_fn(style_fn(' successfully saved'))
def download_exercise_videos(
@@ -397,68 +374,56 @@ def download_exercise_videos(
remote_url=settings.WGER_SETTINGS['WGER_INSTANCE'],
style_fn=lambda x: x,
):
- # Get all videos
- page = 1
- all_videos_processed = False
headers = wger_headers()
url = make_uri(VIDEO_ENDPOINT, server_url=remote_url)
- result = requests.get(url, headers=headers).json()
- print_fn('*** Processing videos ***')
- while not all_videos_processed:
- print_fn('')
- print_fn(f'*** Page {page}')
- print_fn('')
-
- for video_data in result['results']:
- video_uuid = video_data['uuid']
- print_fn(f'Processing video {video_uuid}')
-
- try:
- exercise_base = ExerciseBase.objects.get(uuid=video_data['exercise_base_uuid'])
- except ExerciseBase.DoesNotExist:
- print_fn(' Remote exercise base not found in local DB, skipping...')
- continue
+ result = get_paginated(url, headers=headers)
- try:
- ExerciseVideo.objects.get(uuid=video_uuid)
- print_fn(' Video already present locally, skipping...')
- continue
- except ExerciseVideo.DoesNotExist:
- print_fn(' Video not found in local DB, creating now...')
- video = ExerciseVideo()
- video.exercise_base = exercise_base
- video.uuid = video_uuid
- video.is_main = video_data['is_main']
- video.license_id = video_data['license']
- video.license_author = video_data['license_author']
- video.size = video_data['size']
- video.width = video_data['width']
- video.height = video_data['height']
- video.codec = video_data['codec']
- video.codec_long = video_data['codec_long']
- video.duration = video_data['duration']
-
- # Save the downloaded video
- # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
- retrieved_video = requests.get(video_data['video'], headers=headers)
-
- # Temporary files on Windows don't support the delete attribute
- if os.name == 'nt':
- img_temp = NamedTemporaryFile()
- else:
- img_temp = NamedTemporaryFile(delete=True)
- img_temp.write(retrieved_video.content)
- img_temp.flush()
-
- video.video.save(
- os.path.basename(os.path.basename(video_data['video'])),
- File(img_temp),
- )
- video.save()
- print_fn(style_fn(' saved successfully'))
+ print_fn('*** Processing videos ***')
- if result['next']:
- page += 1
- result = requests.get(result['next'], headers=headers).json()
+ for video_data in result:
+ video_uuid = video_data['uuid']
+ print_fn(f'Processing video {video_uuid}')
+
+ try:
+ exercise_base = ExerciseBase.objects.get(uuid=video_data['exercise_base_uuid'])
+ except ExerciseBase.DoesNotExist:
+ print_fn(' Remote exercise base not found in local DB, skipping...')
+ continue
+
+ try:
+ ExerciseVideo.objects.get(uuid=video_uuid)
+ print_fn(' Video already present locally, skipping...')
+ continue
+ except ExerciseVideo.DoesNotExist:
+ print_fn(' Video not found in local DB, creating now...')
+ video = ExerciseVideo()
+ video.exercise_base = exercise_base
+ video.uuid = video_uuid
+ video.is_main = video_data['is_main']
+ video.license_id = video_data['license']
+ video.license_author = video_data['license_author']
+ video.size = video_data['size']
+ video.width = video_data['width']
+ video.height = video_data['height']
+ video.codec = video_data['codec']
+ video.codec_long = video_data['codec_long']
+ video.duration = video_data['duration']
+
+ # Save the downloaded video
+ # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
+ retrieved_video = requests.get(video_data['video'], headers=headers)
+
+ # Temporary files on Windows don't support the delete attribute
+ if os.name == 'nt':
+ img_temp = NamedTemporaryFile()
else:
- all_videos_processed = True
+ img_temp = NamedTemporaryFile(delete=True)
+ img_temp.write(retrieved_video.content)
+ img_temp.flush()
+
+ video.video.save(
+ os.path.basename(os.path.basename(video_data['video'])),
+ File(img_temp),
+ )
+ video.save()
+ print_fn(style_fn(' saved successfully'))
diff --git a/wger/exercises/tests/test_sync.py b/wger/exercises/tests/test_sync.py
index a87f9cada..534ee3095 100644
--- a/wger/exercises/tests/test_sync.py
+++ b/wger/exercises/tests/test_sync.py
@@ -51,7 +51,7 @@ class MockLanguageResponse:
def json():
return {
"count": 24,
- "next": "http://localhost:8000/api/v2/language/?limit=20&offset=20",
+ "next": None,
"previous": None,
"results": [
{
@@ -95,7 +95,7 @@ class MockLicenseResponse:
def json():
return {
"count": 24,
- "next": "http://localhost:8000/api/v2/language/?limit=20&offset=20",
+ "next": None,
"previous": None,
"results": [
{
diff --git a/wger/utils/requests.py b/wger/utils/requests.py
index 2e570f03c..4723dca65 100644
--- a/wger/utils/requests.py
+++ b/wger/utils/requests.py
@@ -12,6 +12,9 @@
#
# You should have received a copy of the GNU Affero General Public License
+# Third Party
+import requests
+
# wger
from wger import get_version
@@ -22,3 +25,25 @@ def wger_user_agent():
def wger_headers():
return {'User-agent': wger_user_agent()}
+
+
+def get_paginated(url: str, headers=None):
+ """
+ Fetch all results from a paginated endpoint.
+
+ :param url: The URL to fetch from.
+ :param headers: Optional headers to send with the request.
+ :return: A list of all results.
+ """
+ if headers is None:
+ headers = {}
+
+ results = []
+ while True:
+ response = requests.get(url, headers=headers).json()
+ results.extend(response['results'])
+
+ if not response['next']:
+ break
+ url = response['next']
+ return results