LORDCHANNEL2.0/utils/download_image.py

31 lines
1.3 KiB
Python
Raw Normal View History

2021-03-13 18:36:50 +00:00
import requests
from os import path
from pathlib import Path
import string
import random
def get_image(image_url):
"""
Get image based on url.
:return: Image name if everything OK, False otherwise
"""
random_image_name = string.ascii_lowercase + string.ascii_uppercase + string.digits
base_upload_path = Path(path.dirname(path.realpath(__file__)))
upload_path = base_upload_path.parent / 'upload'
image_name = path.split(image_url)[1]
try:
image = requests.get(image_url)
except OSError: # Little too wide, but work OK, no additional imports needed. Catch all conection problems
return False
if image.status_code == 200: # we could have retrieved error page
base_dir = path.join(path.dirname(path.realpath(__file__)), upload_path)
print(base_dir) # Use your own path or "" to use current working directory. Folder must exist.
if path.isfile(path.join(base_dir, image_name)):
image_name = "".join(random.choice(random_image_name) for _ in range(11)) + path.split(image_url)[1]
with open(path.join(base_dir, image_name), "wb") as f:
f.write(image.content)
else:
with open(path.join(base_dir, image_name), "wb") as f:
f.write(image.content)
return image_name