Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Add helper to save images

Roland Geiderd63cddb7bdff
diff --git a/wger/exercises/models/image.py b/wger/exercises/models/image.py
index 18c4115f2..d0b6c9ef5 100644
--- a/wger/exercises/models/image.py
+++ b/wger/exercises/models/image.py
@@ -27,6 +27,7 @@ from django.utils.translation import gettext_lazy as _
from wger.core.models import Language
from wger.exercises.models import ExerciseBase
from wger.utils.cache import delete_template_fragment_cache
+from wger.utils.helpers import BaseImage
from wger.utils.managers import SubmissionManager
from wger.utils.models import (
AbstractLicenseModel,
@@ -42,7 +43,7 @@ def exercise_image_upload_dir(instance, filename):
return "exercise-images/{0}/{1}{2}".format(instance.exercise_base.id, instance.uuid, ext)
-class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
+class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model, BaseImage):
"""
Model for an exercise image
"""
@@ -171,3 +172,24 @@ class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model)
str(message),
fail_silently=True,
)
+
+ @classmethod
+ def from_json(
+ cls,
+ connect_to: ExerciseBase,
+ retrieved_image,
+ json_data: dict,
+ headers,
+ generate_uuid: bool = False
+ ):
+ image: cls = super().from_json(
+ connect_to, retrieved_image, json_data, headers, generate_uuid
+ )
+ image.exercise_base = connect_to
+ image.is_main = json_data['is_main']
+ image.status = json_data['status']
+
+ image.save_image(retrieved_image, json_data)
+
+ image.save()
+ return image
diff --git a/wger/nutrition/migrations/0009_auto_20210801_1350.py b/wger/nutrition/migrations/0009_auto_20210802_1526.py
similarity index 86%
rename from wger/nutrition/migrations/0009_auto_20210801_1350.py
rename to wger/nutrition/migrations/0009_auto_20210802_1526.py
index cd56fee9a..1b313b340 100644
--- a/wger/nutrition/migrations/0009_auto_20210801_1350.py
+++ b/wger/nutrition/migrations/0009_auto_20210802_1526.py
@@ -1,9 +1,10 @@
-# Generated by Django 3.2.3 on 2021-08-01 11:50
+# Generated by Django 3.2.3 on 2021-08-02 13:26
from django.db import migrations, models
import django.db.models.deletion
import uuid
import wger.nutrition.models.image
+import wger.utils.helpers
def generate_uuids(apps, schema_editor):
@@ -64,6 +65,14 @@ class Migration(migrations.Migration):
('last_update', models.DateTimeField(auto_now=True)),
('size', models.IntegerField()),
('source_url', models.URLField()),
+ (
+ 'ingredient',
+ models.OneToOneField(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to='nutrition.ingredient'
+ )
+ ),
(
'license',
models.ForeignKey(
@@ -77,13 +86,7 @@ class Migration(migrations.Migration):
options={
'abstract': False,
},
- ),
- migrations.AddField(
- model_name='ingredient',
- name='image',
- field=models.OneToOneField(
- null=True, on_delete=django.db.models.deletion.CASCADE, to='nutrition.image'
- ),
+ bases=(models.Model, wger.utils.helpers.BaseImage),
),
migrations.RunPython(generate_uuids),
]
diff --git a/wger/nutrition/models/image.py b/wger/nutrition/models/image.py
index 60730861d..852756105 100644
--- a/wger/nutrition/models/image.py
+++ b/wger/nutrition/models/image.py
@@ -48,6 +48,13 @@ class Image(AbstractLicenseModel, models.Model, BaseImage):
)
"""Globally unique ID, to identify the image across installations"""
+ ingredient = models.OneToOneField(
+ 'Ingredient',
+ null=True,
+ on_delete=models.CASCADE,
+ )
+ """Image for this ingredient"""
+
image = models.ImageField(
verbose_name=_('Image'),
help_text=_('Only PNG and JPEG formats are supported'),
@@ -66,7 +73,12 @@ class Image(AbstractLicenseModel, models.Model, BaseImage):
@classmethod
def from_json(
- cls, connect_to, retrieved_image, json_data: dict, headers, generate_uuid: bool = False
+ cls,
+ connect_to,
+ retrieved_image,
+ json_data: dict,
+ headers,
+ generate_uuid: bool = False,
):
image: cls = super().from_json(
connect_to, retrieved_image, json_data, headers, generate_uuid
diff --git a/wger/nutrition/models/ingredient.py b/wger/nutrition/models/ingredient.py
index 518ccab4c..766677b93 100644
--- a/wger/nutrition/models/ingredient.py
+++ b/wger/nutrition/models/ingredient.py
@@ -17,21 +17,17 @@
# Standard Library
import logging
import os
-import pathlib
+import uuid as uuid
from decimal import Decimal
+from typing import Optional
# Django
-import uuid as uuid
-
-import requests
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core import mail
from django.core.cache import cache
from django.core.exceptions import ValidationError
-from django.core.files import File
-from django.core.files.temp import NamedTemporaryFile
from django.core.validators import (
MaxValueValidator,
MinLengthValidator,
@@ -45,10 +41,12 @@ from django.utils import translation
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
-# wger
+# Third Party
+import requests
from requests.utils import default_user_agent
-from wger.core.models import Language, License
+# wger
+from wger.core.models import Language
from wger.utils.cache import cache_mapper
from wger.utils.constants import TWOPLACES
from wger.utils.managers import SubmissionManager
@@ -58,10 +56,11 @@ from wger.utils.models import (
)
# Local
+from ... import get_version
from ..consts import ENERGY_FACTOR
-from .ingredient_category import IngredientCategory
from .image import Image
-from ... import get_version
+from .ingredient_category import IngredientCategory
+
logger = logging.getLogger(__name__)
@@ -114,13 +113,6 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
)
"""Globally unique ID, to identify the ingredient across installations"""
- image = models.OneToOneField(
- Image,
- null=True,
- on_delete=models.CASCADE,
- )
- """Image for this ingredient"""
-
# Product infos
name = models.CharField(
max_length=200,
@@ -439,8 +431,10 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
If it is not available locally, it is fetched from Open Food Facts servers
"""
- if self.image:
+ try:
return self.image
+ except Ingredient.image.RelatedObjectDoesNotExist:
+ pass
if not request.user.is_authenticated:
return
@@ -455,6 +449,7 @@ class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
return
# Everything looks fine, go ahead
+ logger.info(f'Trying to fetch image from OFF for {self.name}')
headers = {
'User-agent':
default_user_agent(f'wger/{get_version()} - https://github.com/wger-project')
diff --git a/wger/settings_global.py b/wger/settings_global.py
index 963e5bf9f..b96095a6a 100644
--- a/wger/settings_global.py
+++ b/wger/settings_global.py
@@ -20,6 +20,7 @@ import os
import re
import sys
+
"""
This file contains the global settings that don't usually need to be changed.
For a full list of options, visit:
@@ -432,6 +433,5 @@ WGER_SETTINGS = {
'DOWNLOAD_FROM_OFF': False
}
-
# Whether the application is being run regularly or during tests
TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'
diff --git a/wger/utils/helpers.py b/wger/utils/helpers.py
index 763e300f5..948424780 100644
--- a/wger/utils/helpers.py
+++ b/wger/utils/helpers.py
@@ -27,6 +27,8 @@ from functools import wraps
# Django
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
+from django.core.files import File
+from django.core.files.temp import NamedTemporaryFile
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.encoding import force_bytes
@@ -273,3 +275,30 @@ def random_string(length=32):
Generates a random string
"""
return ''.join(random.choice(string.ascii_uppercase) for i in range(length))
+
+
+class BaseImage:
+
+ def save_image(self, retrieved_image, json_data: dict):
+ # Save the downloaded image
+ # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to
+ if os.name == 'nt':
+ img_temp = NamedTemporaryFile()
+ else:
+ img_temp = NamedTemporaryFile(delete=True)
+ img_temp.write(retrieved_image.content)
+ img_temp.flush()
+
+ self.image.save(
+ os.path.basename(json_data['image']),
+ File(img_temp),
+ )
+
+ @classmethod
+ def from_json(
+ cls, connect_to, retrieved_image, json_data: dict, headers, generate_uuid: bool = False
+ ):
+ image: cls = cls()
+ if not generate_uuid:
+ image.uuid = json_data['uuid']
+ return image