# Gallery in Python

> Render a VisualCI screenshots gallery in Django, Flask or a Jinja build script with the visualci-gallery package, and fail the deploy when the manifest can't be read.

Source: https://visualci.com/docs/gallery/python/
All of VisualCI's documentation: https://visualci.com/llms.txt

The `visualci-gallery` package renders a [public gallery](https://visualci.com/docs/gallery.md) on your server, in Python. Its HTML is byte for byte what the JS library renders, and the package carries the library's script and stylesheet, so the page works before any script runs and the script then adds the tabs, the switches and the full-size view.

It needs Python 3.10 or later and nothing beyond the standard library:

```sh
pip install visualci-gallery==0.7.0
```

It has two functions. `fetch(url)` reads a manifest and returns it parsed. `render(manifest, **options)` returns the gallery's HTML. Both raise `visualci_gallery.GalleryError` when something is wrong, and there's no fallback: fetch the manifest when you deploy or build, so a VisualCI outage fails the deploy instead of a page, then render from the copy you saved. Image URLs always serve the approved version, so a changed screenshot shows on your site without a deploy. A new screenshot, or one whose size changed, shows after the next one.

Every snippet below is a file, or part of one, from the [example apps](https://github.com/DocSpring/visualci/tree/main/clients/gallery/python/examples), which run in VisualCI's tests.

## Django

In `settings.py`, add the package to `INSTALLED_APPS`, so `django.contrib.staticfiles` finds its script and stylesheet:

<!-- example: clients/gallery/python/examples/django/mysite/settings.py#installed-apps -->
```python
INSTALLED_APPS = [
    "django.contrib.staticfiles",
    "visualci_gallery",  # its static/ folder holds the gallery's script and stylesheet
    "screenshots",
]
```

Then say where the manifest is, and where to keep a copy:

<!-- example: clients/gallery/python/examples/django/mysite/settings.py#gallery-settings -->
```python
# The project's gallery manifest, and where `manage.py fetch_gallery` saves a copy of it.
VISUALCI_GALLERY_URL = "https://app.visualci.com/g/acme/web.json"
VISUALCI_GALLERY_FILE = BASE_DIR / "gallery.json"
```

A management command, `screenshots/management/commands/fetch_gallery.py`, saves the copy. It renders it once with the view's options (below), so a manifest with nothing to show fails the deploy too:

<!-- example: clients/gallery/python/examples/django/screenshots/management/commands/fetch_gallery.py -->
```python
import json
from pathlib import Path

import visualci_gallery
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

from screenshots.views import GALLERY_OPTIONS


class Command(BaseCommand):
    help = "Saves the VisualCI gallery manifest for the screenshots page. Run it on every deploy."

    def handle(self, *args, **options):
        try:
            manifest = visualci_gallery.fetch(settings.VISUALCI_GALLERY_URL)
            # Fails the deploy now, not a request later, when the manifest has nothing to show.
            visualci_gallery.render(manifest, **GALLERY_OPTIONS)
        except visualci_gallery.GalleryError as e:
            raise CommandError(str(e)) from e
        Path(settings.VISUALCI_GALLERY_FILE).write_text(json.dumps(manifest), encoding="utf-8")
```

Run it where you run `collectstatic`, in the step whose files ship (a Dockerfile, or your platform's build step):

```sh
python manage.py fetch_gallery
python manage.py collectstatic --noinput
```

Run `python manage.py fetch_gallery` once in development too, and in CI before the tests. Without `gallery.json`, the screenshots view raises `FileNotFoundError` and the page answers 500. The copy belongs to each deploy, so keep it out of git, in the project's `.gitignore`:

<!-- example: clients/gallery/python/examples/django/.gitignore -->
```text
# Written by `python manage.py fetch_gallery` when the site is deployed.
/gallery.json
```

The view, in `screenshots/views.py`, renders from the saved copy. The package has no template tag: the view marks the HTML safe. Import the package by name, since Django's `render` shortcut has the same name as the package's:

<!-- example: clients/gallery/python/examples/django/screenshots/views.py -->
```python
import json
from pathlib import Path

import visualci_gallery
from django.conf import settings
from django.shortcuts import render
from django.utils.safestring import mark_safe

GALLERY_OPTIONS = {
    "title": None,  # the page has its own <h1>
    "screens": {
        "overview": {"title": "Overview", "caption": "What needs you, every machine with its sessions, and the newest events."},
        "access": {"title": "Access", "caption": "Requests waiting for your approval."},
        "pages-edit-preview": {"title": "The preview"},
        "ios/sessions": {"title": "Sessions", "caption": "Every session on every machine."},
    },
    "order": ["overview", "access", "ios/sessions", "ios/approval"],
    "groups": {"Mac approver": {"size": "desktop", "fit": "contain"}},
}


def screenshots(request):
    manifest = json.loads(Path(settings.VISUALCI_GALLERY_FILE).read_text(encoding="utf-8"))
    gallery = visualci_gallery.render(manifest, **GALLERY_OPTIONS)
    return render(request, "screenshots/index.html", {"gallery": mark_safe(gallery)})
```

It's routed in `mysite/urls.py`:

<!-- example: clients/gallery/python/examples/django/mysite/urls.py -->
```python
from django.urls import path

from screenshots import views

urlpatterns = [
    path("screenshots/", views.screenshots, name="screenshots"),
]
```

The template, `screenshots/templates/screenshots/index.html`, loads the stylesheet, puts the gallery in the page, then loads the script and hydrates every gallery on the page:

<!-- example: clients/gallery/python/examples/django/screenshots/templates/screenshots/index.html -->
```django
{% load static %}<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Screenshots</title>
  <link rel="stylesheet" href="{% static 'visualci_gallery/visualci_gallery.css' %}">
</head>
<body>
  <h1>Screenshots</h1>
  {{ gallery }}
  <script src="{% static 'visualci_gallery/visualci_gallery.js' %}"></script>
  <script>document.querySelectorAll("[data-vg]").forEach(function (el) { VisualCIGallery.hydrate(el); });</script>
</body>
</html>
```

The script is ES5 and sets `window.VisualCIGallery`, so it needs no bundler.

## Flask

The whole app is one file, `app.py`, with its settings in `app.config`:

<!-- example: clients/gallery/python/examples/flask/app.py#setup -->
```python
import json
from pathlib import Path

import click
import visualci_gallery
from flask import Blueprint, Flask, render_template
from markupsafe import Markup

app = Flask(__name__)

# The project's gallery manifest, and where `flask fetch-gallery` saves a copy of it.
app.config["VISUALCI_GALLERY_URL"] = "https://app.visualci.com/g/acme/web.json"
app.config["VISUALCI_GALLERY_FILE"] = Path(app.root_path) / "gallery.json"
```

A blueprint serves the script and stylesheet straight from the package. `visualci_gallery.static_dir()` is the package's static folder:

<!-- example: clients/gallery/python/examples/flask/app.py#static -->
```python
# The package's script and stylesheet, at /gallery/visualci_gallery/visualci_gallery.js and .css.
gallery_static = Blueprint(
    "visualci_gallery", __name__, static_folder=visualci_gallery.static_dir(), static_url_path="/gallery"
)
app.register_blueprint(gallery_static)
```

A CLI command saves the manifest, checking it against every set of options the site uses:

<!-- example: clients/gallery/python/examples/flask/app.py#fetch -->
```python
@app.cli.command("fetch-gallery")
def fetch_gallery():
    """Saves the VisualCI gallery manifest. Run it on every deploy."""
    try:
        manifest = visualci_gallery.fetch(app.config["VISUALCI_GALLERY_URL"])
        # Fails the deploy now, not a request later, when the manifest has nothing to show.
        for options in (SCREENSHOTS, BAND):
            visualci_gallery.render(manifest, **options)
    except visualci_gallery.GalleryError as e:
        raise click.ClickException(str(e)) from e
    Path(app.config["VISUALCI_GALLERY_FILE"]).write_text(json.dumps(manifest), encoding="utf-8")
```

```sh
flask --app app fetch-gallery
```

Run it on every deploy, once in development, and in CI before the tests. Without `gallery.json`, the routes raise `FileNotFoundError` and the pages answer 500. Keep the copy out of git:

<!-- example: clients/gallery/python/examples/flask/.gitignore -->
```text
# Written by `flask fetch-gallery` when the site is deployed.
/gallery.json
```

The routes render from the copy, and `Markup` keeps Jinja from escaping the HTML:

<!-- example: clients/gallery/python/examples/flask/app.py#routes -->
```python
def gallery(options):
    manifest = json.loads(Path(app.config["VISUALCI_GALLERY_FILE"]).read_text(encoding="utf-8"))
    return Markup(visualci_gallery.render(manifest, **options))


@app.route("/")
def home():
    return render_template("home.html", gallery=gallery(BAND))


@app.route("/screenshots/")
def screenshots():
    return render_template("screenshots.html", gallery=gallery(SCREENSHOTS))
```

`SCREENSHOTS` holds the same options as the Django view, and `BAND` is the homepage's strip ([below](#a-band-on-the-homepage)). The layout, `templates/layout.html`, links both stylesheets and the script:

<!-- example: clients/gallery/python/examples/flask/templates/layout.html -->
```jinja
<!doctype html>
<html lang="en" data-theme="light">
<head>
  <meta charset="utf-8">
  <title>{% block title %}Acme{% endblock %}</title>
  <link rel="stylesheet" href="{{ url_for('visualci_gallery.static', filename='visualci_gallery/visualci_gallery.css') }}">
  <link rel="stylesheet" href="{{ url_for('static', filename='site.css') }}">
</head>
<body>
  {% block content %}{% endblock %}
  <script src="{{ url_for('visualci_gallery.static', filename='visualci_gallery/visualci_gallery.js') }}"></script>
  <script>document.querySelectorAll("[data-vg]").forEach(function (el) { VisualCIGallery.hydrate(el); });</script>
</body>
</html>
```

The page, `templates/screenshots.html`, puts the gallery in it:

<!-- example: clients/gallery/python/examples/flask/templates/screenshots.html -->
```jinja
{% extends "layout.html" %}
{% block title %}Screenshots{% endblock %}
{% block content %}
  <h1>Screenshots</h1>
  {{ gallery }}
{% endblock %}
```

## A static site with Jinja

A build script, `build.py`, fetches and renders in one go, and exits non-zero when it can't, so the build fails and the last good site stays up:

<!-- example: clients/gallery/python/examples/jinja/build.py -->
```python
"""Builds the static site into site/: python build.py. Exits non-zero, writing nothing, when the gallery's manifest
can't be read or has nothing to show."""

import argparse
import shutil
import sys
from pathlib import Path

import visualci_gallery
from jinja2 import Environment, FileSystemLoader, select_autoescape
from markupsafe import Markup

HERE = Path(__file__).resolve().parent
MANIFEST = "https://app.visualci.com/g/acme/web.json"

# No heading (the page has one), and no Light and Dark buttons: the gallery follows <html data-theme>.
GALLERY_OPTIONS = {"title": None, "theme_switch": False}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--manifest", default=MANIFEST)
    parser.add_argument("--out", type=Path, default=HERE / "site")
    args = parser.parse_args()

    try:
        gallery = visualci_gallery.render(visualci_gallery.fetch(args.manifest), **GALLERY_OPTIONS)
    except visualci_gallery.GalleryError as e:
        sys.exit(f"build failed: {e}")

    env = Environment(loader=FileSystemLoader(HERE / "templates"), autoescape=select_autoescape())
    page = env.get_template("index.html").render(gallery=Markup(gallery))

    args.out.mkdir(parents=True, exist_ok=True)
    (args.out / "index.html").write_text(page, encoding="utf-8")
    # The package's script and stylesheet, next to the page.
    shutil.copytree(visualci_gallery.static_dir(), args.out, dirs_exist_ok=True)


if __name__ == "__main__":
    main()
```

Its template, `templates/index.html`, links the copied files by relative path:

<!-- example: clients/gallery/python/examples/jinja/templates/index.html -->
```jinja
<!doctype html>
<html lang="en" data-theme="light">
<head>
  <meta charset="utf-8">
  <title>Screenshots</title>
  <link rel="stylesheet" href="visualci_gallery/visualci_gallery.css">
</head>
<body>
  <h1>Screenshots</h1>
  <button type="button" id="theme">Dark mode</button>
  {{ gallery }}
  <script src="visualci_gallery/visualci_gallery.js"></script>
  <script>
    document.querySelectorAll("[data-vg]").forEach(function (el) { VisualCIGallery.hydrate(el); });
    // The site's own switch: the gallery follows <html data-theme> as it changes.
    document.getElementById("theme").addEventListener("click", function () {
      var html = document.documentElement;
      html.setAttribute("data-theme", html.getAttribute("data-theme") === "dark" ? "light" : "dark");
    });
  </script>
</body>
</html>
```

## Options

`render` takes the gallery's options as keyword arguments, in snake case: `title`, `heading_level`, `id`, `screens`, `order`, `groups`, `group_order`, `credit`, `layout`, `theme_switch`, `see_all`, `preload`, `deep_links`, `text`, `search`, `zoom` and `new_badges`. `None` is the same as leaving an option out, except for `title`, where it means no heading. The Django view's options give two screens a title and a caption, put four screens first, and show the Mac app's windows whole:

<!-- example: clients/gallery/python/examples/django/screenshots/views.py#options -->
```python
GALLERY_OPTIONS = {
    "title": None,  # the page has its own <h1>
    "screens": {
        "overview": {"title": "Overview", "caption": "What needs you, every machine with its sessions, and the newest events."},
        "access": {"title": "Access", "caption": "Requests waiting for your approval."},
        "pages-edit-preview": {"title": "The preview"},
        "ios/sessions": {"title": "Sessions", "caption": "Every session on every machine."},
    },
    "order": ["overview", "access", "ios/sessions", "ios/approval"],
    "groups": {"Mac approver": {"size": "desktop", "fit": "contain"}},
}
```

An option that's wrong (an unknown `layout`, an `id` that isn't a valid id) raises `GalleryError` naming it, so it fails the deploy along with the fetch. [Gallery options](https://visualci.com/docs/gallery/options.md) describes each one, and how screenshot names pair into screens.

After the page has loaded, the gallery preloads the images a reader is likely to look at next. `preload=False` turns that off, and `preload={"count": 200, "bytes": 20_000_000}` sets your own limits. It's on by default, and [Preloading](https://visualci.com/docs/gallery/options.md#preloading) says what it fetches and when.

`deep_links=True` puts what the reader is looking at in the page's URL (the tab, the open screen, the values), so a copied link opens the same view; [Deep links](https://visualci.com/docs/gallery/options.md#deep-links) has the details. `text` changes the gallery's own words, for a site in another language: `text={"close": "Fermer", "open": "Agrandir « {title} »"}`. [Your own words](https://visualci.com/docs/gallery/options.md#your-own-words) lists every key and its default. `search=False` takes away the search box a gallery of 40 screens or more gets, `zoom=False` turns off zooming in the full-size view, and `new_badges=14` badges the screens that changed in the last 14 days ([Search](https://visualci.com/docs/gallery/options.md#search), [Zoom](https://visualci.com/docs/gallery/options.md#zoom), [New badges](https://visualci.com/docs/gallery/options.md#new-badges)).

## A band on the homepage

The strip layout shows every screen at one size in a single row that scrolls sideways. With `see_all` it links to the full page:

<!-- example: clients/gallery/python/examples/flask/app.py#band -->
```python
# One row of screenshots on the homepage, linking to the full page.
BAND = {
    "layout": "strip",
    "title": None,
    "order": ["overview", "access"],
    "credit": False,
    "see_all": {"href": "/screenshots/"},
}
```

The homepage, `templates/home.html`:

<!-- example: clients/gallery/python/examples/flask/templates/home.html -->
```jinja
{% extends "layout.html" %}
{% block content %}
  <h1>Acme</h1>
  <p>Everything your team needs, in one place.</p>
  {{ gallery }}
{% endblock %}
```

A strip has no Light and Dark buttons: it follows the page.

## Theming

The stylesheet styles the gallery through `--vg-*` CSS variables. Set them to your site's own tokens on `.vg` or any element around it, in any stylesheet (here the Flask example's `static/site.css`). When the tokens change with your site's theme, the gallery's colours change with them:

<!-- example: clients/gallery/python/examples/flask/static/site.css#gallery -->
```css
/* The gallery in the site's colours, radii and type. */
.vg {
  --vg-ink: var(--text);
  --vg-ink-2: var(--text);
  --vg-muted: var(--text-muted);
  --vg-paper: var(--surface);
  --vg-paper-2: var(--surface-raised);
  --vg-rule: var(--border);
  --vg-accent: var(--link);
  --vg-radius-md: var(--radius);
  --vg-radius-lg: calc(var(--radius) * 1.5);
  font-family: var(--font);
}
```

[Gallery options](https://visualci.com/docs/gallery/options.md#theming) lists every variable.

## Light and dark

By default each gallery has Light and Dark buttons. It starts in the reader's theme (`<html data-theme>` when it's set, otherwise their system setting), and the buttons switch the screenshots.

If your site has its own theme switch on `<html data-theme>`, turn the buttons off with `theme_switch=False`. The gallery then follows `data-theme` as it changes, as the Jinja example does:

<!-- example: clients/gallery/python/examples/jinja/build.py#options -->
```python
# No heading (the page has one), and no Light and Dark buttons: the gallery follows <html data-theme>.
GALLERY_OPTIONS = {"title": None, "theme_switch": False}
```

## When the manifest can't be read

`fetch` tries three times, 20 seconds each, then raises `GalleryError` naming the URL: a network error, a timeout, a status other than 200, or JSON that doesn't parse. `render` raises it when the manifest has nothing to show or an option is invalid. `timeout` and `attempts` are keyword arguments of `fetch`.

Don't call `fetch` in a view: a slow or unreachable VisualCI would hold the request for a minute or more and then fail it. Fetch when you deploy or build, as the examples do, and let the error stop it. `manage.py fetch_gallery` and `flask fetch-gallery` exit 1 with the error, and the build script exits 1 before it writes anything. The site you have keeps serving its last copy.

## Pinning the version

Pin the package in your requirements:

```text
visualci-gallery==0.7.0
```

The script and stylesheet ship inside the package, so they're pinned with it: the script that hydrates the page is always the one made for the HTML the package rendered. Serve them from the package, as above, rather than from a CDN at another version. To upgrade, change the pin and redeploy.
