def set_image(instance, field, width=1920, height=1440):
""" FileField / ImageField """
manager = getattr(instance, field.name)
try:
image_type = random.choice(['people', 'places', 'things'])
response = requests.get(
'https://placem.at/%s?w=%d&h=%d&random=1&txt=' % (image_type, width, height),
timeout=5,
stream=True
)
except (ConnectionError, Timeout):
response = requests.get('http://baconmockup.com/%d/%d/' % (width, height), stream=True)
tfp = tempfile.NamedTemporaryFile(delete=False)
with tfp:
for chunk in response.iter_content(1024 * 1024):
tfp.write(chunk)
tfp.seek(0)
manager.save('image.jpg', File(tfp), save=False)
评论列表
文章目录