Skip to content

Instantly share code, notes, and snippets.

@akarsh1995
Last active July 24, 2020 18:55
Show Gist options
  • Select an option

  • Save akarsh1995/233f97d0fd9d53566b3b5039d1874717 to your computer and use it in GitHub Desktop.

Select an option

Save akarsh1995/233f97d0fd9d53566b3b5039d1874717 to your computer and use it in GitHub Desktop.
A Flask web app to obtain random premium images of the desired size.Very useful to web developers.
from pathlib import Path
import subprocess
from flask import Flask, request
import sys
current_dir = Path(__file__).parent
image_fetch_script_path = current_dir.joinpath('random_image_fetch.py')
save_dir = current_dir.joinpath('random_images')
def run_fetching_in_background(width, height, n_images):
return subprocess.Popen(
[sys.executable, image_fetch_script_path.absolute(),
width, height, n_images,
f'{save_dir.absolute()}'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
app = Flask(__name__)
app.debug = True
display_html = '''
<h1>Enter width height and number of premium images you want to fetch.</h1>
<form id="random-image-form" method="POST" action="/fetch-images">
<label for="widthW">Width</label>
<input name="width" type="number" value=1024 /><br />
<label for="height">height</label>
<input name="height" type="number" value=576 /><br />
<label for="n_images">n_images</label>
<input name="n_images" type="number" value=1 max=50 min=1 /><br />
</form>
<button type="submit" form="random-image-form">
Submit
</button>'''
@app.route("/", methods=['GET'])
def index():
return display_html
@app.route("/fetch-images", methods=['POST'])
def fetch_images():
width = request.form['width']
height = request.form['height']
n_images = request.form['n_images']
process = run_fetching_in_background(width, height, n_images)
return f'Fetching Process at pid: {process.pid} <br/>' \
f'Your files will be fetched soon... dir -> {save_dir}'
if __name__ == "__main__":
app.run()
import os
import uuid
import warnings
import requests
endpoint = 'https://source.unsplash.com/random'
def generate_url(size):
size = map(str, size)
return f'{endpoint}/{"x".join(size)}'
def save_image(content, path):
with open(path, 'wb') as f:
f.write(content)
def get_image_content(url):
response = requests.get(url)
if response.status_code == 200:
return response.content
def get_random_file_name(size):
return f'{"x".join(map(str, size))}-{uuid.uuid4()}.jpg'
def get_and_save_image(size, dir_path):
if not os.path.exists(dir_path):
os.mkdir(dir_path)
url = generate_url(size)
image_content = get_image_content(url)
if image_content:
save_image(image_content,
os.path.join(dir_path, get_random_file_name(size)))
return
warnings.warn(f'Cannot fetch the given url.')
if __name__ == '__main__':
import sys
(width, height, n_images), output_dir = map(int, sys.argv[1:-1]), sys.argv[-1]
for _ in range(n_images):
get_and_save_image((width, height), output_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment