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.pyindex 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 Languagefrom wger.exercises.models import ExerciseBasefrom wger.utils.cache import delete_template_fragment_cache+from wger.utils.helpers import BaseImagefrom wger.utils.managers import SubmissionManagerfrom 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 imagediff --git a/wger/nutrition/migrations/0009_auto_20210801_1350.py b/wger/nutrition/migrations/0009_auto_20210802_1526.pysimilarity index 86%rename from wger/nutrition/migrations/0009_auto_20210801_1350.pyrename to wger/nutrition/migrations/0009_auto_20210802_1526.pyindex 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:26from django.db import migrations, modelsimport django.db.models.deletionimport uuidimport wger.nutrition.models.image+import wger.utils.helpersdef 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.pyindex 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):@classmethoddef 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_uuiddiff --git a/wger/nutrition/models/ingredient.py b/wger/nutrition/models/ingredient.pyindex 518ccab4c..766677b93 100644--- a/wger/nutrition/models/ingredient.py+++ b/wger/nutrition/models/ingredient.py@@ -17,21 +17,17 @@# Standard Libraryimport loggingimport os-import pathlib+import uuid as uuidfrom decimal import Decimal+from typing import Optional# Django-import uuid as uuid--import requestsfrom django.conf import settingsfrom django.contrib.auth.models import Userfrom django.contrib.sites.models import Sitefrom django.core import mailfrom django.core.cache import cachefrom django.core.exceptions import ValidationError-from django.core.files import File-from django.core.files.temp import NamedTemporaryFilefrom django.core.validators import (MaxValueValidator,MinLengthValidator,@@ -45,10 +41,12 @@ from django.utils import translationfrom django.utils.text import slugifyfrom django.utils.translation import gettext_lazy as _-# wger+# Third Party+import requestsfrom requests.utils import default_user_agent-from wger.core.models import Language, License+# wger+from wger.core.models import Languagefrom wger.utils.cache import cache_mapperfrom wger.utils.constants import TWOPLACESfrom wger.utils.managers import SubmissionManager@@ -58,10 +56,11 @@ from wger.utils.models import ()# Local+from ... import get_versionfrom ..consts import ENERGY_FACTOR-from .ingredient_category import IngredientCategoryfrom .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 infosname = 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:+ passif 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.pyindex 963e5bf9f..b96095a6a 100644--- a/wger/settings_global.py+++ b/wger/settings_global.py@@ -20,6 +20,7 @@ import osimport reimport 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 testsTESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'diff --git a/wger/utils/helpers.py b/wger/utils/helpers.pyindex 763e300f5..948424780 100644--- a/wger/utils/helpers.py+++ b/wger/utils/helpers.py@@ -27,6 +27,8 @@ from functools import wraps# Djangofrom django.contrib.auth.models import Userfrom django.contrib.auth.tokens import default_token_generator+from django.core.files import File+from django.core.files.temp import NamedTemporaryFilefrom django.http import Http404from django.shortcuts import get_object_or_404from 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