У меня есть простая модель с переопределенным методом save (), я хочу сохранить изображение с заданного URL, каждый раз, когда вызывается метод сохранения.
Вот мой код:
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
# Creating URL to request
URL = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&key=" + settings.KEY
URL += "&photoreference=" + self.reference
result = urllib.request.urlretrieve(URL)
self.image_file.save(
os.path.basename(self.reference),
File(open(result[0]))
)
self.save()
И это выдает эту ошибку:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "/home/dolidod/.local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/dolidod/coding/fest-apka/fest_strona/urls.py", line 21, in <module>
path('', include('app.urls')),
File "/home/dolidod/.local/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/dolidod/coding/fest-apka/app/urls.py", line 2, in <module>
from app.views import *
File "/home/dolidod/coding/fest-apka/app/views.py", line 5, in <module>
import app.scripts_for_api_control.main as SFAC
File "/home/dolidod/coding/fest-apka/app/scripts_for_api_control/main.py", line 15, in <module>
places_info.get_place_photo_by_reference("CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU")
File "/home/dolidod/coding/fest-apka/app/scripts_for_api_control/high_level_code.py", line 110, in get_place_photo_by_reference
image = low_level_code.get_image_from_URL_and_save_to_DB(photo_reference)
File "/home/dolidod/coding/fest-apka/app/scripts_for_api_control/low_level_code.py", line 55, in get_image_from_URL_and_save_to_DB
to_save_image_instance.save()
File "/home/dolidod/coding/fest-apka/app/models.py", line 26, in save
File(open(result[0]))
File "/home/dolidod/.local/lib/python3.7/site-packages/django/db/models/fields/files.py", line 87, in save
self.name = self.storage.save(name, content, max_length=self.field.max_length)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/files/storage.py", line 52, in save
return self._save(name, content)
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/files/storage.py", line 270, in _save
for chunk in content.chunks():
File "/home/dolidod/.local/lib/python3.7/site-packages/django/core/files/base.py", line 60, in chunks
data = self.read(chunk_size)
File "/usr/lib/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Я нашел возможное решение с добавлением:
with open(path, 'rb') as f:
contents = f.read()
Но теперь мой вопрос: как я могу использовать этот фрагмент кода для обработки сохранения изображения в моей функции save ()?