{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# A random item from the Museums Victoria's collections!\n", "\n", "The Museums Victoria collections API includes a couple of very useful parameters:\n", "\n", "* `sort` – as well as the usual options 'relevance' and 'date', `sort` can be set to 'random'\n", "* `hasimages` – set to 'yes' to only get records with images attached\n", "\n", "Putting these two things together, we can very easily create a random collection image viewer. Just run the cells below, then click on the 'Randomise!' button for serendipitous fun." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import requests\n", "import random\n", "from IPython.display import Image, display, HTML\n", "import ipywidgets as widgets" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "SEARCH_URL = 'https://collections.museumsvictoria.com.au/api/search'" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "6a437d8067444588b5f24390df097889", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Button(description='Randomise!', style=ButtonStyle())" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "92b6baa3da734f44a2079b23beec7208", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Output()" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "def display_random(b):\n", " out.clear_output()\n", " params = {\n", " 'sort': 'random',\n", " 'hasimages': 'yes'\n", " }\n", " # Get the data\n", " response = requests.get(SEARCH_URL, params=params, headers={'User-Agent': 'Mozilla/5.0'})\n", " # Randomly select a record from the randomly sorted data\n", " record = random.choice(response.json())\n", " # Display the record\n", " with out:\n", " display(HTML(f'

{record[\"displayTitle\"]}

'))\n", " display(Image(url=record['media'][0]['small']['uri']))\n", " display(HTML(f'More info...'))\n", "\n", "# Create a button to launch the randomness\n", "go = widgets.Button(description='Randomise!')\n", "out = widgets.Output()\n", "go.on_click(display_random)\n", "display(go)\n", "display(out)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "----\n", "\n", "Created by [Tim Sherratt](https://timsherratt.org/) for the [GLAM Workbench](https://glam-workbench.github.io/). Support me by becoming a [GitHub sponsor](https://github.com/sponsors/wragge)!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5" } }, "nbformat": 4, "nbformat_minor": 4 }