def get_pil_image_for_term(term, minimum_side=settings.IMAGE_SIDE): boss = OAuth1Session(settings.BOSS_KEY, client_secret=settings.BOSS_SECRET) params = {'q': escaped_term(term), 'dimensions': 'large'} with timing('boss.get'): response = boss.get(settings.BOSS_IMAGE_URL, params=params).json() results = response['bossresponse']['images'].get('results') if not results: return None results = [r for r in results if _is_valid_boss_result(r, minimum_side)] if not results: return None with timing('_pick_readable_images'): images = _pick_readable_images(results) if not images: return None return random.choice(images)
def get_trumpified_image_url_for_term(term): term = term.lower() with timing('get_pil_image_for_term'): image = get_pil_image_for_term(term) if not image: abort(404) with timing('trumpify_image_from_url'): image = trumpify_image_from_url(image, term) with timing('upload_image_from_pil_image'): return upload_image_from_pil_image(image)
def _pick_readable_images(results): images, index, batch_size = [], 0, 3 urls = [r['url'] for r in results] while index < len(urls): batch = urls[index:index + batch_size] index += batch_size reqs = (grequests.get(url, timeout=1, allow_redirects=False) for url in batch) with timing('grequests.map'): responses = grequests.map(reqs) for resp in responses: if resp is None or resp.status_code != 200: continue try: image = Image.open(StringIO(resp.content)) images.append(image) except IOError: continue if images: break return images