示例#1
0
 def save_image(self, exercise, filename, db_filename=None):
     """
     Helper function to save an image to an exercise
     """
     if not db_filename:
         db_filename = filename
     image = ExerciseImage()
     image.exercise = exercise
     image.image.save(filename, File(open("wger/exercises/tests/{0}".format(filename)), "rb"))
     image.save()
示例#2
0
 def save_image(self, exercise, filename, db_filename=None):
     '''
     Helper function to save an image to an exercise
     '''
     if not db_filename:
         db_filename = filename
     image = ExerciseImage()
     image.exercise = exercise
     image.image.save(
         filename,
         File(open('wger/exercises/tests/{0}'.format(filename)), 'rb'))
     image.save()
示例#3
0
 def save_image(self, exercise, filename, db_filename=None):
     '''
     Helper function to save an image to an exercise
     '''
     if not db_filename:
         db_filename = filename
     image = ExerciseImage()
     image.exercise = exercise
     image.image.save(
         filename,
         File(open('wger/exercises/tests/{0}'.format(filename)), 'rb')
     )
     image.save()
示例#4
0
 def save_image(self, exercise, filename, db_filename=None):
     """
     Helper function to save an image to an exercise
     """
     with open('wger/exercises/tests/{0}'.format(filename), 'rb') as inFile:
         if not db_filename:
             db_filename = filename
         image = ExerciseImage()
         image.exercise = exercise
         image.status = ExerciseImage.STATUS_ACCEPTED
         image.image.save(filename, File(inFile))
         image.save()
         return (image.pk)
 def save_image(self, exercise, filename, db_filename=None) -> int:
     """
     Helper function to save an image to an exercise
     """
     with open(f'wger/exercises/tests/{filename}', 'rb') as inFile:
         if not db_filename:
             db_filename = filename
         image = ExerciseImage()
         image.exercise_base = exercise.exercise_base
         image.status = ExerciseImage.STATUS_ACCEPTED
         image.image.save(db_filename, File(inFile))
         image.save()
         return image.pk
 def save_image(self, exercise, filename, db_filename=None):
     '''
     Helper function to save an image to an exercise
     '''
     if not db_filename:
         db_filename = filename
     image = ExerciseImage()
     image.exercise = exercise
     image.status = ExerciseImage.STATUS_ACCEPTED
     # image.license_author = 1
     image.image.save(
         filename,
         File(open('wger/exercises/tests/{0}'.format(filename), 'rb')))
     image.save()
     return (image.pk)
示例#7
0
 def save_image(self, exercise, filename, db_filename=None):
     '''
     Helper function to save an image to an exercise
     '''
     if not db_filename:
         db_filename = filename
     image = ExerciseImage()
     image.exercise = exercise
     image.status = ExerciseImage.STATUS_ACCEPTED
     if six.PY2:
         image.image.save(
             filename,
             File(open('wger/exercises/tests/{0}'.format(filename)), 'rb')
         )
     else:
         image.image.save(
             filename,
             File(open('wger/exercises/tests/{0}'.format(filename), encoding='latin1'), 'rb')
         )
     image.save()
    def handle(self, **options):

        if not settings.MEDIA_ROOT:
            raise ImproperlyConfigured(
                'Please set MEDIA_ROOT in your settings file')

        remote_url = options['remote_url']
        try:
            val = URLValidator()
            val(remote_url)
        except ValidationError:
            raise CommandError('Please enter a valid URL')

        exercise_api = "{0}/api/v2/exercise/?limit=999"
        image_api = "{0}/api/v2/exerciseimage/?exercise={1}"
        thumbnail_api = "{0}/api/v2/exerciseimage/{1}/thumbnails/"

        headers = {
            'User-agent':
            default_user_agent('wger/{} + requests'.format(get_version()))
        }

        # Get all exercises
        result = requests.get(
            exercise_api.format(remote_url), headers=headers).json()
        for exercise_json in result['results']:
            exercise_name = exercise_json['name'].encode('utf-8')
            exercise_uuid = exercise_json['uuid']
            exercise_id = exercise_json['id']

            self.stdout.write('')
            self.stdout.write(
                u"*** Processing {0} (ID: {1}, UUID: {2})".format(
                    exercise_name, exercise_id, exercise_uuid))

            try:
                exercise = Exercise.objects.get(uuid=exercise_uuid)
            except Exercise.DoesNotExist:
                self.stdout.write(
                    '    Remote exercise not found in local DB, skipping...')
                continue

            # Get all images
            images = requests.get(
                image_api.format(remote_url, exercise_id),
                headers=headers).json()

            if images['count']:

                for image_json in images['results']:
                    image_id = image_json['id']
                    result = requests.get(
                        thumbnail_api.format(remote_url, image_id),
                        headers=headers).json()

                    image_name = os.path.basename(result['original'])
                    self.stdout.write('    Fetching image {0} - {1}'.format(
                        image_id, image_name))

                    try:
                        image = ExerciseImage.objects.get(pk=image_id)
                        self.stdout.write(
                            '    --> Image already present locally, skipping...'
                        )
                        continue
                    except ExerciseImage.DoesNotExist:
                        self.stdout.write(
                            '    --> Image not found in local DB, creating now...'
                        )
                        image = ExerciseImage()
                        image.pk = image_id

                    # Save the downloaded image, see link for details
                    # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
                    retrieved_image = requests.get(
                        result['original'], headers=headers)
                    img_temp = NamedTemporaryFile(delete=True)
                    img_temp.write(retrieved_image.content)
                    img_temp.flush()

                    image.exercise = exercise
                    image.is_main = image_json['is_main']
                    image.status = image_json['status']
                    image.image.save(
                        os.path.basename(image_name),
                        File(img_temp),
                    )
                    image.save()

            else:
                self.stdout.write(
                    '    No images for this exercise, nothing to do')
    def handle(self, **options):

        if not settings.MEDIA_ROOT:
            raise ImproperlyConfigured('Please set MEDIA_ROOT in your settings file')

        remote_url = options['remote_url']
        try:
            val = URLValidator()
            val(remote_url)
        except ValidationError:
            raise CommandError('Please enter a valid URL')

        headers = {'User-agent': default_user_agent('wger/{} + requests'.format(get_version()))}

        # Get all images
        page = 1
        all_images_processed = False
        result = requests.get(IMAGE_API.format(remote_url), headers=headers).json()
        self.stdout.write('*** Processing images ***')
        while not all_images_processed:
            self.stdout.write('')
            self.stdout.write(f'*** Page {page}')
            self.stdout.write('')
            page += 1

            if result['next']:
                result = requests.get(result['next'], headers=headers).json()
            else:
                all_images_processed = True

            for image_data in result['results']:
                image_uuid = image_data['uuid']

                self.stdout.write(f'Processing image {image_uuid}')

                try:
                    exercise_base = ExerciseBase.objects.get(id=image_data['exercise'])
                except ExerciseBase.DoesNotExist:
                    self.stdout.write('    Remote exercise base not found in local DB, skipping...')
                    continue

                try:
                    image = ExerciseImage.objects.get(uuid=image_uuid)
                    self.stdout.write('    Image already present locally, skipping...')
                    continue
                except ExerciseImage.DoesNotExist:
                    self.stdout.write('    Image not found in local DB, creating now...')
                    image = ExerciseImage()
                    image.uuid = image_uuid

                # Save the downloaded image
                # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
                retrieved_image = requests.get(image_data['image'], 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_image.content)
                img_temp.flush()

                image.exercise = exercise_base
                image.is_main = image_data['is_main']
                image.status = image_data['status']
                image.image.save(
                    os.path.basename(os.path.basename(image_data['image'])),
                    File(img_temp),
                )
                image.save()
                self.stdout.write(self.style.SUCCESS('    successfully saved'))
示例#10
0
    def handle(self, **options):

        if not settings.MEDIA_ROOT:
            raise ImproperlyConfigured('Please set MEDIA_ROOT in your settings file')

        remote_url = options['remote_url']
        try:
            val = URLValidator()
            val(remote_url)
        except ValidationError:
            raise CommandError('Please enter a valid URL')

        exercise_api = "{0}/api/v2/exercise/?limit=999&status=2"
        image_api = "{0}/api/v2/exerciseimage/?exercise={1}"
        thumbnail_api = "{0}/api/v2/exerciseimage/{1}/thumbnails/"

        headers = {'User-agent': default_user_agent('wger/{} + requests'.format(get_version()))}

        # Get all exercises
        result = requests.get(exercise_api.format(remote_url), headers=headers).json()
        for exercise_json in result['results']:
            exercise_name = exercise_json['name'].encode('utf-8')
            exercise_uuid = exercise_json['uuid']
            exercise_id = exercise_json['id']

            self.stdout.write('')
            self.stdout.write(u"*** Processing {0} (ID: {1}, UUID: {2})".format(exercise_name,
                                                                                exercise_id,
                                                                                exercise_uuid))

            try:
                exercise = Exercise.objects.get(uuid=exercise_uuid)

            except Exercise.DoesNotExist:
                self.stdout.write('    Remote exercise not found in local DB, skipping...')

                continue

            # Get all images
            images = requests.get(image_api.format(remote_url, exercise_id), headers=headers).json()

            if images['count']:

                for image_json in images['results']:
                    image_id = image_json['id']
                    result = requests.get(thumbnail_api.format(remote_url, image_id),
                                          headers=headers).json()

                    image_name = os.path.basename(result['original'])
                    self.stdout.write('    Fetching image {0} - {1}'.format(image_id, image_name))

                    try:
                        image = ExerciseImage.objects.get(pk=image_id)
                        self.stdout.write('    --> Image already present locally, skipping...')
                        continue
                    except ExerciseImage.DoesNotExist:
                        self.stdout.write('    --> Image not found in local DB, creating now...')
                        image = ExerciseImage()
                        image.pk = image_id

                    # Save the downloaded image, see link for details
                    # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
                    retrieved_image = requests.get(result['original'], headers=headers)
                    img_temp = NamedTemporaryFile(delete=True)
                    img_temp.write(retrieved_image.content)
                    img_temp.flush()

                    image.exercise = exercise
                    image.is_main = image_json['is_main']
                    image.status = image_json['status']
                    image.image.save(
                        os.path.basename(image_name),
                        File(img_temp),
                    )
                    image.save()

            else:
                self.stdout.write('    No images for this exercise, nothing to do')
示例#11
0
    def handle(self, *args, **options):

        if not settings.MEDIA_ROOT:
            raise ImproperlyConfigured(
                'Please set MEDIA_ROOT in your settings file')

        remote_url = options['remote_url']
        try:
            val = URLValidator()
            val(remote_url)
        except ValidationError:
            raise CommandError('Please enter a valid URL')

        exercise_api = "{0}/api/v2/exercise/?limit=999"
        image_api = "{0}/api/v2/exerciseimage/?exercise={1}"
        thumbnail_api = "{0}/api/v2/exerciseimage/{1}/thumbnails/"

        # Get all exercises
        result = json.load(urllib.urlopen(exercise_api.format(remote_url)))
        for exercise_json in result['results']:
            exercise_name = exercise_json['name']
            exercise_uuid = exercise_json['uuid']
            exercise_id = exercise_json['id']

            self.stdout.write('')
            self.stdout.write(u"*** Processing {0} (ID: {1})".format(
                exercise_name, exercise_id))

            try:
                exercise = Exercise.objects.get(uuid=exercise_uuid)
            except Exercise.DoesNotExist:
                self.stdout.write(
                    '    Remote exercise not found in local DB, skipping...')
                continue

            # Get all images
            images = json.load(
                urllib.urlopen(image_api.format(remote_url, exercise_id)))

            if images['count']:

                for image_json in images['results']:
                    image_id = image_json['id']
                    result = json.load(
                        urllib.urlopen(
                            thumbnail_api.format(remote_url, image_id)))

                    image_name = os.path.basename(result['original'])
                    self.stdout.write('    Fetching image {0} - {1}'.format(
                        image_id, image_name))

                    try:
                        image = ExerciseImage.objects.get(pk=image_id)
                        self.stdout.write(
                            '    --> Image already present locally, skipping...'
                        )
                        continue
                    except ExerciseImage.DoesNotExist:
                        self.stdout.write(
                            '    --> Image not found in local DB, creating now...'
                        )
                        image = ExerciseImage()
                        image.pk = image_id

                    # Save the downloaded image, see link for details
                    # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
                    retrieved_image = urllib.urlretrieve(result['original'])
                    image.exercise = exercise
                    image.is_main = image_json['is_main']
                    image.status = image_json['status']
                    image.image.save(os.path.basename(image_name),
                                     File(open(retrieved_image[0]), 'rb'))
                    image.save()

            else:
                self.stdout.write(
                    '    No images for this exercise, nothing to do')
示例#12
0
    def handle(self, *args, **options):

        if not settings.MEDIA_ROOT:
            raise ImproperlyConfigured('Please set MEDIA_ROOT in your settings file')

        remote_url = options['remote_url']
        val = URLValidator()
        try:
            val(remote_url)
        except ValidationError:
            raise CommandError('Please enter a valid URL')

        # Get all exercises
        result = json.load(urllib.urlopen("{0}/api/v1/exercise/?limit=0".format(remote_url)))
        for exercise_json in result['objects']:
            exercise_name = exercise_json['name']
            exercise_id = exercise_json['id']

            self.stdout.write(u"*** Processing {0} (ID: {1})".format(exercise_name, exercise_id))

            try:
                exercise = Exercise.objects.get(pk=exercise_id)
            except Exercise.DoesNotExist:
                self.stdout.write('Remote exercise not found in local DB, skipping...')
                self.stdout.write('')
                continue

            if exercise_json['images']:

                # Get all images
                for image_resource in exercise_json['images']:

                    result = json.load(urllib.urlopen("{0}{1}".format(remote_url, image_resource)))
                    image_name = os.path.basename(result['image'])
                    self.stdout.write('Fetching image {0} - {1}'.format(result['id'], image_name))

                    image_id = result['id']

                    try:
                        image = ExerciseImage.objects.get(pk=image_id)
                        self.stdout.write('--> Image already present locally, skipping...')
                        continue
                    except ExerciseImage.DoesNotExist:
                        self.stdout.write('--> Image not found in local DB, creating now...')
                        image = ExerciseImage()
                        image.pk = image_id

                    # Save the downloaded image, see link for details
                    # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
                    retrieved_image = urllib.urlretrieve(result['image'])
                    image.exercise = exercise
                    image.is_main = result['is_main']
                    image.image.save(
                        os.path.basename(image_name),
                        File(open(retrieved_image[0]), 'rb')
                    )
                    image.save()
            else:
                self.stdout.write('No images for this exercise, nothing to do')

            self.stdout.write('')
示例#13
0
    def handle(self, **options):

        if not settings.MEDIA_ROOT:
            raise ImproperlyConfigured(
                'Please set MEDIA_ROOT in your settings file')

        remote_url = options['remote_url']
        try:
            val = URLValidator()
            val(remote_url)
        except ValidationError:
            raise CommandError('Please enter a valid URL')

        headers = {
            'User-agent':
            default_user_agent('wger/{} + requests'.format(get_version()))
        }

        # Get all exercises
        result = requests.get(EXERCISE_API.format(remote_url),
                              headers=headers).json()
        for exercise_json in result['results']:
            exercise_name = exercise_json['name']
            exercise_uuid = exercise_json['uuid']
            exercise_id = exercise_json['id']

            self.stdout.write('')
            self.stdout.write(
                f"*** {exercise_name} (ID: {exercise_id}, UUID: {exercise_uuid})"
            )

            try:
                exercise = Exercise.objects.get(uuid=exercise_uuid)

            except Exercise.DoesNotExist:
                self.stdout.write(
                    '    Remote exercise not found in local DB, skipping...')
                continue

            # Get all images
            images = requests.get(IMAGE_API.format(remote_url, exercise_id),
                                  headers=headers).json()

            if images['count']:

                for image_json in images['results']:
                    image_id = image_json['id']
                    image_uuid = image_json['uuid']
                    result = requests.get(THUMBNAIL_API.format(
                        remote_url, image_id),
                                          headers=headers).json()

                    image_name = os.path.basename(result['original'])
                    self.stdout.write('    Fetching image {0} - {1}'.format(
                        image_id, image_name))

                    try:
                        image = ExerciseImage.objects.get(uuid=image_uuid)
                        self.stdout.write(
                            '    --> Image already present locally, skipping...'
                        )
                        continue
                    except ExerciseImage.DoesNotExist:
                        self.stdout.write(
                            '    --> Image not found in local DB, creating now...'
                        )
                        image = ExerciseImage()
                        image.uuid = image_uuid

                    # Save the downloaded image
                    # http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
                    retrieved_image = requests.get(remote_url +
                                                   result['original'],
                                                   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_image.content)
                    img_temp.flush()

                    image.exercise = exercise.exercise_base
                    image.is_main = image_json['is_main']
                    image.status = image_json['status']
                    image.image.save(
                        os.path.basename(image_name),
                        File(img_temp),
                    )
                    image.save()

            else:
                self.stdout.write(
                    '    No images for this exercise, nothing to do')
示例#14
0
def _parse_exercises(xml_data, current_user):
    """
    Importer les exos puis les images car il faut l'id de l'exercice
    pour correctement positionner l'image dans le
    systeme de fichiers
    cf: models.py:351
    """
    current_username = current_user.username
    users_list = User.objects.values_list("username", flat=True)

    for _exercise in xml_data:
        identity = _get_exercise_identity(_exercise)

        # Checking exercise existence based on the name
        # if exists skipping this iteration
        if _exercise_exists(identity["uuid"]):
            continue

        description = base64.b64decode(_exercise.text).decode("utf-8")
        muscles_list = _get_muscles(_exercise)
        equipment_list = _get_equipment(_exercise)

        author = identity["author"] if identity[
            "author"] in users_list else current_username

        exercise = Exercise()
        exercise.name = identity["name"]
        exercise.name_original = identity["name"]
        exercise.license_author = author
        exercise.creation_date = identity["creation_date"]
        exercise.category = identity["category"]
        exercise.language = identity["language"]
        exercise.license = identity["license"]
        exercise.status = identity["status"]
        exercise.uuid = uuid.UUID(identity["uuid"])
        exercise.description = description

        exercise.save()

        for _muscle in muscles_list["main"]:
            exercise.muscles.add(_muscle)

        for _muscle in muscles_list["secondary"]:
            exercise.muscles_secondary.add(_muscle)

        for _equipment in equipment_list:
            exercise.equipment.add(_equipment)

        images_xml = _get_images(_exercise)

        if images_xml:
            for _image in images_xml:
                exercise_image = ExerciseImage()
                exercise_image.exercise = exercise

                exercise_image.is_main = _image[2]

                # Decoding base64 image
                _byte_image = _image[0].text.encode("utf-8")
                raw_image_data = base64.b64decode(_byte_image)
                image_buffer = io.BytesIO(raw_image_data)

                exercise_image.image.save(_image[1], image_buffer)

                exercise_image.status = exercise_image.STATUS_ACCEPTED

                exercise_image.save()