Skip to content

Commit

Permalink
Add method to download a MediaEntry image
Browse files Browse the repository at this point in the history
  • Loading branch information
TDKorn committed Apr 7, 2024
1 parent 1afb8d0 commit 4cfce3e
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions magento/models/product.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations
import requests
from . import Model
from pathlib import Path
from functools import cached_property
from magento.exceptions import MagentoError
from typing import Union, TYPE_CHECKING, Optional, List, Dict
Expand Down Expand Up @@ -596,6 +598,30 @@ def enable(self, scope: Optional[str] = None) -> bool:
self.data['disabled'] = False
return self.update(scope)

def download(self, filename: Optional[str] = None) -> Optional[str]:
"""Downloads the MediaEntry image
:param filename: the name of the file to save the image to; uses the filename on Magento if not provided.
:return: the absolute path of the downloaded image file, or ``None`` if the download failed
"""
if filename is None:
filename = Path(self.file).name

try:
response = requests.get(self.link)
response.raise_for_status()

except requests.RequestException as e:
self.logger.error(f"Failed to download {self}: {e}")
return None

fpath = Path(filename).resolve()
with open(fpath, 'wb') as f:
f.write(response.content)

self.logger.info(f"Downloaded {self} to {fpath}")
return str(fpath)

def add_media_type(self, media_type: str, scope: Optional[str] = None) -> bool:
"""Add a media type to the MediaEntry on the given scope
Expand Down

0 comments on commit 4cfce3e

Please sign in to comment.