Esempio n. 1
0
 def save_image(self, exercise, filename, db_filename=None):
     """
     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 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('')

            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_base'])
                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_base = 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'))

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