This is Day 2 of the #100DaysOfPython challenge.
In today’s morning post, I am opting to begin to shift how I generate my blog post images. To do so, I will making use of an unofficial Python Unsplash API by salvoventura.
This post won’t cover the entire shift, but it will look into how I will grab the source image from Unsplash.
- A registered app with the Unsplash developers site.
- Familiarity with Pipenv — see my post for the minimum you will need.
- An environment setup with JupyterLab.
Let’s create the
pyunsplash directory and install the Unsplash API along with other required packages to install and download the image.
The server will now be up and running.
You will need to also grab your access key from your Unsplash app from the developer portal. Once you have it, update your
.env file like so:
It will be used to power the
Creating the notebook
Once on http://localhost:8888/lab, select to create a new Python 3 notebook from the launcher.
We will create four cells to handle four parts of this mini project:
- Load the environment variables.
- Use the Unsplash API to grab the source image.
- Save the image to the parent directory.
- Display the downloaded image in the notebook using Pillow.
Load the environment variables
Assuming that our notebook is in
docs/unsplash_api.ipynb file, we will create a new cell and paste the following code:
Running this cell will read the
.env file in the parent directory and load the
Fetching the link for a random photo
We can create a new cell that will load the
pyunsplash package and grab a random photo from Unsplash.
This will print out the photo ID along with the value of the link for download.
Download the image to the parent folder
We can make use of the
requests package to download the image and write it to file.
Finally, we can display what that image looks like:
This photo is the photo that I am using for this blog post.
Today’s post demonstrated how to use the
pyunsplash package to fetch a random image based on a keyword and save it to disk.
I will be writing further posts in the coming days on how we can compose multiple images together to create a more complex effect along with text.
Resources and further reading
- Unsplash developers site.
- The ABCs of Pipenv for the minimum you will need.
- Hello, JupyterLab.
Originally posted on my blog. To see new posts without delay, read the posts there and subscribe to my newsletter.