Information Technology Grimoire

Version .0.0.1

IT Notes from various projects because I forget, and hopefully they help you too.

Python3 Flask Royalty Free Images

This allows you to search multiple royalty free image sites using their api. You should still accredit like normal, and I haven’t coded that portion in.

Installation

  1. make an account at each api key location
  2. check your profile/settings for api key
  3. Fill out the api key strings
  4. setup environment:
    python -m venv images
    cd images
    scripts\activate
    python -m pip install --upgrade pip
    python -m pip install -r requirements.txt
  1. Run the script
    python images.py

Access Flask Server

Flask should be running on your machine at this point:

http://localhost:5000

The Files for the Image Finder Script

requirements.txt

certifi==2022.12.7
charset-normalizer==3.1.0
click==7.1.2
Flask==1.1.4
Flask-Login==0.5.0
Flask-SQLAlchemy==2.5.1
Flask-WTF==0.15.1
idna==3.4
itsdangerous==1.1.0
Jinja2==2.11.3
MarkupSafe==1.1.1
requests==2.28.2
SQLAlchemy==1.4.28
urllib3==1.26.15
Werkzeug==1.0.1
WTForms==2.3.3

images_config.py

# https://help.unsplash.com/en/collections/1451694-api-guidelines
UNSPLASH_API_KEY = "blehblehyourkey"

PIXABAY_API_KEY = "blehblehyourkey"

# https://www.pexels.com/api/new/
PEXELS_API_KEY = "blehblehyourkey"

images.py

from flask import Flask, render_template, request, render_template_string
import requests
from images_config import UNSPLASH_API_KEY, PIXABAY_API_KEY, PEXELS_API_KEY

app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def image_search():
    images = []

    if request.method == "POST":
        search_query = request.form["search"]
        api_provider = request.form["api_provider"]

        if api_provider == "unsplash":
            response = requests.get(f"https://api.unsplash.com/search/photos?query={search_query}&client_id={UNSPLASH_API_KEY}")
            response_data = response.json()["results"]
            images = [{"urls": {"small": img["urls"]["small"], "full": img["urls"]["full"]}, "alt_description": img["alt_description"]} for img in response_data]

        elif api_provider == "pixabay":
            response = requests.get(f"https://pixabay.com/api/?key={PIXABAY_API_KEY}&q={search_query}&image_type=photo")
            response_data = response.json()["hits"]
            images = [{"urls": {"small": img["previewURL"], "full": img["largeImageURL"]}, "alt_description": img["tags"]} for img in response_data]

        elif api_provider == "openverse":
            response = requests.get(f"https://api.openverse.engineering/v1/images?q={search_query}")
            response_data = response.json()["results"]
            images = [{"urls": {"small": img["thumbnail"], "full": img["url"]}, "alt_description": img["title"]} for img in response_data]

        elif api_provider == "pexels":
            headers = {'Authorization': PEXELS_API_KEY}
            response = requests.get(f"https://api.pexels.com/v1/search?query={search_query}", headers=headers)
            response_data = response.json()["photos"]
            images = [{"urls": {"small": img["src"]["medium"], "full": img["src"]["large"]}, "alt_description": img["url"].split("/")[-2].replace("-", " ")} for img in response_data]

    #return render_template("index.html", images=images)

    return render_template_string("""
<!doctype html>
<html>
  <head>
    <title>Image Search</title>
  </head>
  <body>
    <form method="POST">
      <input type="text" name="search" placeholder="Search">
      <select name="api_provider">
        <option value="unsplash">Unsplash</option>
        <option value="pixabay">Pixabay</option>
        <option value="openverse">Openverse</option>
        <option value="pexels">Pexels</option>
      </select>
      <button type="submit">Search</button>
    </form>
    <div>
      {% for image in images %}
        <a href="{{ image.urls.full }}"><img src="{{ image.urls.small }}" alt="{{ image.alt_description }}"></a>
      {% endfor %}
    </div>
  </body>
</html>
""", images=images)

if __name__ == "__main__":
    app.run(debug=True)
Last updated on 13 Apr 2023
Published on 13 Apr 2023