<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Björn van Dijkman on Medium]]></title>
        <description><![CDATA[Stories by Björn van Dijkman on Medium]]></description>
        <link>https://medium.com/@bjornvandijkman?source=rss-ad6cec1eb34b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JVUoi-9N49KACWF1iqkrLA.jpeg</url>
            <title>Stories by Björn van Dijkman on Medium</title>
            <link>https://medium.com/@bjornvandijkman?source=rss-ad6cec1eb34b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:23:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bjornvandijkman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to make your Python Docker images secure, fast & small]]></title>
            <link>https://medium.com/vantageai/how-to-make-your-python-docker-images-secure-fast-small-b3a6870373a0?source=rss-ad6cec1eb34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3a6870373a0</guid>
            <category><![CDATA[multi-stage-builds]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-security]]></category>
            <category><![CDATA[image-size-reduce]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Björn van Dijkman]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 12:01:58 GMT</pubDate>
            <atom:updated>2023-02-20T13:42:59.998Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Image Layers and Implementing Multistage Builds</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YfnDW9Ww-tcuPFFU" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the world of <strong>microservices</strong>, having secure, efficient, and compact <a href="https://www.docker.com/"><strong>Docker</strong></a> images is crucial for successful deployments. This blog will explore the key factors that contribute to building such images, including the importance of not running images as the root user, updating and upgrading packages when building the image, considering Docker’s layer architecture while writing Dockerfile instructions, and utilizing multistage builds to decrease your image size. Parts of this blog were inspired by a great talk that I recently from Matthijs Brouns, which you can view <a href="https://www.youtube.com/watch?v=kx-SeGbkNPU">here</a>.</p><p>I will be using the CLI tool <a href="https://github.com/wagoodman/dive"><strong>Dive</strong></a> to analyze the image and its layers. The aim of the Docker image is to serve as a host for a <a href="https://fastapi.tiangolo.com/">FASTAPI</a> server for a machine learning application, with Poetry as its dependency manager. For more information on the motivation to use Poetry instead of pip/pipenv/pip-tools/conda, read <a href="https://andrewbrookins.com/python/why-poetry/"><strong>this</strong></a> and<strong> </strong><a href="https://betterprogramming.pub/5-reasons-why-poetry-beats-pip-python-setup-6f6bd3488a04"><strong>this</strong></a> blog. Please note that a basic understanding of Docker and <a href="https://docs.docker.com/engine/reference/builder/"><strong>Dockerfiles</strong></a> is a prerequisite for this article.</p><pre>FROM python:3.11-slim as build</pre><p>I am using the <a href="https://hub.docker.com/layers/library/python/3.11-slim/images/sha256-1591aa8c01b5b37ab31dbe5662c5bdcf40c2f1bce4ef1c1fd24802dae3d01052?context=explore"><strong>slim</strong></a> version of Python 3.11 to minimize the size of the container and make it as <strong>lightweight</strong> as possible. It has a size of <strong>121</strong> MB.</p><p>The full Python Image (<a href="https://hub.docker.com/layers/library/python/3.11/images/sha256-79f7c6a20b4c513556c949c356ee075c4eb31aff8f64d8b81eac0799adc0e223?context=explore">python:3.11</a>) includes extra development tools and documentation that are not necessary for running the application, making it much larger with a size of <strong>875</strong> MB, around <strong>7 times</strong> larger than the slim version 😱.</p><p>Another alternative is <strong>Alpine </strong>(<a href="https://hub.docker.com/layers/library/python/3.11-alpine/images/sha256-9f955672f82a7e7138bcb64bb8352fb0a3025533b8be90a789be5a32526497ca?context=explore">python:3.11-alpine</a>), which is smaller with a size of <strong>56.5 </strong>MB. However, it lacks the package installer pip and the support for installing wheel packages, which are both needed for installing applications like Pandas and Numpy. To install these applications, you would need to compile them from source files using compiler packages like <a href="https://www.geeksforgeeks.org/compiling-with-g-plus-plus/"><strong>G++</strong></a>, which are also not installed by default on the Alpine image. This results in a larger image size (and a lot more hassle) than the slim version, so lets continue with that one.</p><pre>ENV PIP_DEFAULT_TIMEOUT=100 \<br>    # Allow statements and log messages to immediately appear<br>    PYTHONUNBUFFERED=1 \<br>    # disable a pip version check to reduce run-time &amp; log-spam<br>    PIP_DISABLE_PIP_VERSION_CHECK=1 \<br>    # cache is useless in docker image, so disable to reduce image size<br>    PIP_NO_CACHE_DIR=1<br><br>ARG POETRY_VERSION=1.3.2</pre><p>The ENV variables in the Dockerfile are set to optimize the behavior of pip and poetry during the installation of packages in the Docker container. Furthermore, I explicitly define the <strong>Poetry</strong> version to install.</p><h3>Security</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LcfOJjNZqamA3_B_" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=medium&amp;utm_medium=referral">FLY:D</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s move on to security, because there are a few aspects that are important. Running Docker containers as the <strong>root</strong> user is not recommended because the root user has complete control over the host system, including the ability to <strong>modify</strong> or <strong>delete</strong> files, start and stop services, and <strong>access sensitive information</strong>. To follow the <strong>principle of least privilege</strong>, it’s better to run the containers with only the minimum necessary privileges. To enhance security, we therefore create a non-root user for the Docker container named appuser.</p><pre>RUN set -ex \<br>    # Create a non-root user<br>    &amp;&amp; addgroup --system --gid 1001 appgroup \<br>    &amp;&amp; adduser --system --uid 1001 --gid 1001 --no-create-home appuser \</pre><p>By assigning specific user and group IDs, such as 1001, it becomes easier to manage user permissions and access control across different systems, especially when running containers on platforms like Kubernetes.</p><p>🤔 So in what way do the permissions of appuser differ from the root user? The permissions assigned to appuser may include restrictions on read, write, or execute access to certain files and directories, depending on the default permissions set for those resources. For example, by default, appuser may not have write access to a specific subdirectory within the container. If the application running as appuser requires write access to that directory, you would need to change the ownership of that directory using the chown command, to grant appuser the required permissions:</p><pre>RUN chown -R appuser:appuser /your-subdirectory</pre><p>Otherwise the following error would be thrown:</p><pre>[Errno 13] Permission denied: &#39;your-subdirectory/filename&#39;</pre><p>Another security best-practice is updating and upgrading packages in a Docker container. The reason for this is that in a Docker environment, the base image used to create a container is typically a snapshot of a specific version of an operating system. Over time, security vulnerabilities or other issues may be discovered and patches released to address them using apt-get update and apt-get upgrade. The apt-get update command updates the package index, which is kind of like a database of available software packages and their metadata, and retrieves the latest package information from the package repository.</p><pre>RUN set -ex \<br>    &amp;&amp; apt-get update \<br>    &amp;&amp; apt-get upgrade -y</pre><p>Now that we have information on the available software packages, we can use the apt-get upgrade command to upgrade the packages currently installed in the container to their latest available versions. The -y flag is used to automatically answer yes to any prompts during the upgrade process.</p><p>⬆ The update process resulted in some automatically installed packages, package cache files, and package index files. These files are no longer required when running the application after they have served their purpose of helping to upgrade the packages. We can safely remove these files using the following commands, which should reduce the size of the Docker image.</p><pre># Clean up<br>RUN set -ex apt-get autoremove -y \\<br>    &amp;&amp; apt-get clean -y \\<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p>A final security best-practice is to make sure that no secrets are included in the docker image. To help prevent this, you can add common secrets files and folders to your <strong>.dockerignore</strong> file:</p><pre>**/.env<br>**/.aws<br>**/.ssh</pre><p>You can also use <a href="https://github.com/aquasecurity/trivy">Trivy</a>, which will warn you when you for example are using ‘root’ as your image user. Here is a screenshot from the VSCode extension:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMoFS3WR84XuiYdCtrycMg.png" /><figcaption>VSCode extension for Trivy</figcaption></figure><h3>Application files</h3><p>Alright, now that we have set some environment variables and improved the security of our docker container, lets continue to the copying of the actual application files and installing the dependencies. We want to set the working directory to ‘/app’. This directory does not exist yet in the base image, but WORKDIR creates it for us if it doesn’t exist. All subsequent instructions will be executed in this location, which makes our docker image more organized and portable.</p><pre>WORKDIR /app<br>COPY pyproject.toml poetry.lock ./</pre><p>The COPY command is used to copy files from the host system to the container file system. In this case, we are copying pyproject.toml and poetry.lock, which are the configuration files for the Poetry package manager.</p><h3>Dive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Li3H1zhl_RUGaNm-" /><figcaption>Photo by <a href="https://unsplash.com/@sebaspenalambarri?utm_source=medium&amp;utm_medium=referral">Sebastian Pena Lambarri</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now that we have completed some steps, lets build the docker image and dive into it to inspect 🕵️‍♀️ the different layers:</p><pre>docker build -t app:latest .<br>dive app:latest</pre><p>👇 We can see in each layer which changes were made compared to the previous layer. First we created an <strong>app</strong> directory using the WORKDIR command, followed by the copying of two files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JS1YOLmAHyxByHETLACKg.png" /></figure><p>The current image has a size of <strong>139 MB</strong>. It is looking pretty good, but a couple of improvements can be made to decrease its size. The first thing to remember is that files that are removed by subsequent layers in the system are actually still present in the images; they’re just inaccessible in the final layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*8M03e-cxUbCcjCvbQTvm5w.png" /></figure><p>👆Having the steps of installing the security updates and removing the now unnecessary files and packages separately therefore does not save any space. What does work is to combine these two steps into one.</p><pre>RUN set -ex \<br>    # Create a non-root user<br>    &amp;&amp; addgroup --system --gid 1001 appgroup \<br>    &amp;&amp; adduser --system --uid 1001 --gid 1001 --no-create-home appuser \<br>    # Upgrade the package index and install security upgrades<br>    &amp;&amp; apt-get update \<br>    &amp;&amp; apt-get upgrade -y \<br>    &amp;&amp; apt-get autoremove -y \<br>    &amp;&amp; apt-get clean -y \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p>This decreased the size of the image with 18 mb to a total size of 121 mb 🎉, which is exactly equal to the apt-get update &amp;&amp; update-get upgrade -y layer that we had before.</p><h3>Caching</h3><p>Okay, lets continue! After installing the dependencies, we will copy some subdirectories that my application needs to the container. Followed by the installation of the python packages using Poetry:</p><pre>COPY ./artifacts artifacts<br>COPY ./api api<br><br>RUN pip install &quot;poetry==$POETRY_VERSION&quot; \<br>    &amp;&amp; poetry install --no-root --no-ansi --no-interaction</pre><p>🤔 But does the order of these commands make sense? Remember that each layer is an <strong>independent delta</strong> from the layer below it. Every time you change a layer, it changes every layer that comes after it. If the previous layer is exactly the same as before, we can just use the cached value instead of rebuilding that step.</p><pre>Step 12/18 : COPY ./api api<br> ---&gt; Using cache<br> ---&gt; ea3ba41d1a13</pre><p>Therefore, you want to <strong>order your layers</strong> from least likely to change to most likely to change for fast building times💨. It makes sense to first install the dependencies before copying the rest of the program. You are generally much less likely to update and change your dependencies than your application code. 👇 This is therefore a better order of instructions:</p><pre>RUN pip install &quot;poetry==$POETRY_VERSION&quot; \<br>    &amp;&amp; poetry install --no-root --no-ansi --no-interaction<br><br>COPY ./artifacts artifacts<br>COPY ./api api</pre><p>The next step is to expose a port for our application to listen on. EXPOSE in a <strong>Dockerfile</strong> is more for <strong>documentation</strong> 📄 purposes, indicating which ports the application listens on within the container.</p><p>To actually expose our FASTAPI server, we run the following command:</p><pre>CMD [&quot;uvicorn&quot;, &quot;api.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Finally, we set the user that the application will run as using the USER command. This is set to the user we created earlier, appuser.</p><p>Let’s build the docker image again and check out the size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*WsSCcueCagpBEixHMntibg.png" /></figure><p>The image now has a total size of <strong>731</strong> mb. <strong>531</strong> mb comes from the dependencies that were installed by Poetry, but Poetry itself also takes up some space.</p><p>💡 Although Poetry is useful during the development phase for creating virtual environments and managing dependencies, these functionalities are not required when running the Docker image, as the image provides its own isolated environment and our dependencies have already been installed. Reducing the size of the Docker image can therefore also be achieved by ensuring that the Poetry package is not included in the final image.</p><h3>Multistage builds</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*8r7gLDZCIMC6TtU27Omuvg.png" /></figure><p>Multistage builds can be utilized to exclude Poetry from the final Docker image, because it enables the creation of multiple images from a single Dockerfile. Instead of installing the dependencies directly using Poetry, Poetry can also export the necessary dependencies to a <strong>requirements.txt </strong>file during the build stage. This file can be copied to the final stage, and be used by the <strong>pip</strong> to install the dependencies.</p><pre>FROM python:3.11-slim as build<br><br>. . . <br><br>RUN pip install &quot;poetry==$POETRY_VERSION&quot; \<br>    &amp;&amp; poetry install --no-root --no-ansi --no-interaction \<br>    &amp;&amp; poetry export -f requirements.txt -o requirements.txt<br><br><br>### Final stage<br>FROM python:3.11-slim as final<br><br>WORKDIR /app<br><br>COPY --from=build /app/requirements.txt .<br><br>RUN pip install -r requirements.txt</pre><p>By excluding Poetry in the final stage, the size of the Docker image is reduced, as demonstrated by the decrease from 732 MB to 538 MB 🎉🍾.</p><h3>👇 We end up with the following file:</h3><pre>FROM python:3.11-slim as build<br><br>ENV PIP_DEFAULT_TIMEOUT=100 \<br>    # Allow statements and log messages to immediately appear<br>    PYTHONUNBUFFERED=1 \<br>    # disable a pip version check to reduce run-time &amp; log-spam<br>    PIP_DISABLE_PIP_VERSION_CHECK=1 \<br>    # cache is useless in docker image, so disable to reduce image size<br>    PIP_NO_CACHE_DIR=1 \<br>    POETRY_VERSION=1.3.2<br><br>WORKDIR /app<br>COPY pyproject.toml poetry.lock ./<br><br>RUN pip install &quot;poetry==$POETRY_VERSION&quot; \<br>    &amp;&amp; poetry install --no-root --no-ansi --no-interaction \<br>    &amp;&amp; poetry export -f requirements.txt -o requirements.txt<br><br><br>### Final stage<br>FROM python:3.11-slim as final<br><br>WORKDIR /app<br><br>COPY --from=build /app/requirements.txt .<br><br>RUN set -ex \<br>    # Create a non-root user<br>    &amp;&amp; addgroup --system --gid 1001 appgroup \<br>    &amp;&amp; adduser --system --uid 1001 --gid 1001 --no-create-home appuser \<br>    # Upgrade the package index and install security upgrades<br>    &amp;&amp; apt-get update \<br>    &amp;&amp; apt-get upgrade -y \<br>    # Install dependencies<br>    &amp;&amp; pip install -r requirements.txt \<br>    # Clean up<br>    &amp;&amp; apt-get autoremove -y \<br>    &amp;&amp; apt-get clean -y \<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br>COPY ./artifacts artifacts<br>COPY ./api api<br><br>EXPOSE 8000<br><br>CMD [&quot;uvicorn&quot;, &quot;api.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]<br><br># Set the user to run the application<br>USER appuser</pre><h3>Summary</h3><p>In conclusion, by following these tips and best practices when creating your Dockerfile, you can ensure that your final image is optimized for security, size and performance.</p><p>Make sure to choose the right base image, understand the immutability of Docker layers, put instructions in the right order, and follow the security best-practices.</p><p>Thanks for reading! Feel free to reach out if you found this post interesting or if it helped you out in any way.</p><p><a href="https://www.linkedin.com/in/bj%C3%B6rn-van-dijkman-5103a671/">https://www.linkedin.com/in/bj%C3%B6rn-van-dijkman-5103a671/</a></p><h3>Resources</h3><ul><li><a href="https://andrewbrookins.com/python/why-poetry/">Why Is Poetry Essential to the Modern Python Stack? - Andrew Brookins</a></li><li><a href="https://betterprogramming.pub/5-reasons-why-poetry-beats-pip-python-setup-6f6bd3488a04">5 Reasons Why Poetry Beats Pip Python Setup</a></li><li><a href="https://www.oreilly.com/library/view/kubernetes-up-and/9781491935668/">Kubernetes: Up and Running</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fkx-SeGbkNPU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dkx-SeGbkNPU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fkx-SeGbkNPU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/43719a3ef480fec1ee3270ade979ad9e/href">https://medium.com/media/43719a3ef480fec1ee3270ade979ad9e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3a6870373a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vantageai/how-to-make-your-python-docker-images-secure-fast-small-b3a6870373a0">How to make your Python Docker images secure, fast &amp; small</a> was originally published in <a href="https://medium.com/vantageai">VantageAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use slim CI with dbt-core]]></title>
            <link>https://medium.com/vantageai/how-to-use-slim-ci-with-dbt-core-bc0594514308?source=rss-ad6cec1eb34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc0594514308</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[google-cloud-storage]]></category>
            <category><![CDATA[ci]]></category>
            <dc:creator><![CDATA[Björn van Dijkman]]></dc:creator>
            <pubDate>Wed, 11 May 2022 15:29:31 GMT</pubDate>
            <atom:updated>2022-05-30T12:13:46.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use Slim CI with dbt Core</h3><h4>Run modified and new dbt models using dbt Core, Github Actions and Google Cloud Storage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXnhnmvwmZ9tdzk5tSxfXg.jpeg" /><figcaption>Make yourself and your manager happy by implementing Slim CI</figcaption></figure><p>Dbt is a great tool for data transformations. The paid version, called dbt Cloud, offers <a href="https://docs.getdbt.com/docs/dbt-cloud/using-dbt-cloud/cloud-enabling-continuous-integration"><strong>Slim CI</strong></a>. Slim CI makes it easy to test new and modified dbt models before deploying them into production. You can configure jobs to run when opening a Pull Request in your repository. By surfacing the job’s most recent successful run artifacts, <strong>dbt Cloud</strong> determines the set of new and modified resources. You can choose to only run the dbt models for which any code has changed. This makes your CI process more efficient in terms of time and costs. In this article I will explain how to mimic this functionality when you are limited to using <strong>dbt Core</strong>.</p><p>Summarized, the process is as follows:</p><ul><li>Run dbt when deploying to production and save the manifest.json file to cloud storage. This file contains the <strong>state of the models</strong> of the last dbt run, and thus reflects the models deployed to production.</li><li>Retrieve the manifest.json file from cloud storage when opening a new <strong>pull request</strong> and run dbt using the state:modified+ parameter in that same pull request.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sN_hl-gENajwewA11naexA.png" /><figcaption>Slim CI workflow using dbt Core and Google Cloud Platform</figcaption></figure><h3>Storing the manifest.json file</h3><p>First, you need to create a cloud storage folder, which you can do through the UI, but preferably through Terraform. I am using Google Cloud Storage (GCS), but you can use any cloud storage. The manifest.json file will be copied to this folder, and overwritten each time a new deployment is made. I named my GCS bucket manifest-location-prod, and can access it at gs://manifest-location-prod when logging in to that Google Cloud project during the CI process. I was already generating the manifest.json file in a workflow where we publish our dbt documentation to Github Pages, so I incorporate the copying of the manifest.json file to the GCS bucket in that workflow. Find a full example of this Github workflow in <a href="https://github.com/bjornvandijkman1993/dbt-slim-ci">this</a> repository, or see the relevant snippet below.</p><blockquote>Note: you first need to run dbt before generating the documentation, because this ensures that you see documentation for all columns, and not just the columns described in your dbt yml files.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc49dedbec937dbb75594ee06aab0820/href">https://medium.com/media/fc49dedbec937dbb75594ee06aab0820/href</a></iframe><h3>Slim CI</h3><p>When opening a pull request we use that same manifest.json file to get the <strong>current state of the deployed models</strong>. After retrieving the file from GCS, the new or modified dbt models are run and tested. The parameter state:modified+ is used to run these models and its first order children, which are the models that are downstream of the modified models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3166a12a7b1620ba2792b33f1870dffa/href">https://medium.com/media/3166a12a7b1620ba2792b33f1870dffa/href</a></iframe><h3>Limit the data</h3><p>Testing these new models during Pull Requests against full production datasets would be expensive. Limit the amount of data against which the models are tested by using <strong>dbt macros</strong>. This allows you to test models on a subset of the production data. The macro in days_back.sql uses a date column as input. The objective is to limit the data, x number of days back from today.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a21912ce633b4ccd5ed90f76f5667f08/href">https://medium.com/media/a21912ce633b4ccd5ed90f76f5667f08/href</a></iframe><p>In our staging model stg_web.sql, we call the macro with the arguments that we want data from the last 3 days, and specify the column from which to extract the dates. Using 3 as an input for days, date_sub(current_date(&quot;Europe/Amsterdam&quot;), interval {{ days }} day) from days_back.sql will return the date from 3 days ago. The macro then filters on the dates that are greater or equal than the returned date. Do note that your source table has to be partitioned on the date column to optimize the query for cost.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3fded482161aafdb9f0479e098444a6/href">https://medium.com/media/b3fded482161aafdb9f0479e098444a6/href</a></iframe><p>This is all conditional on the name of the target, because we do not want to filter the data when targeting “prod”. In the Pull Request workflow “dev” is being targeted, which means that the days_back macro is only used when integrating new dbt models.</p><h3>Conclusion</h3><p>Testing and running new or modified dbt models is important, but the costs and time that it takes can get out of hand very quickly. By mimicking the Slim CI feature of dbt Cloud and filtering the data against which the dbt models are run, we can make our CI process more (cost) efficient.</p><p>Thanks for reading! Feel free to reach out if you found this post interesting or if it helped you out in any way.</p><p><a href="https://www.linkedin.com/in/bj%C3%B6rn-van-dijkman-5103a671/">Björn van Dijkman - Data Engineer (Vantage AI) - IKEA | LinkedIn</a></p><h3>Resources</h3><ul><li><a href="https://docs.getdbt.com/docs/building-a-dbt-project/documentation">Documentation | dbt Docs</a></li><li><a href="https://github.com/bjornvandijkman1993/dbt-slim-ci">GitHub - bjornvandijkman1993/dbt-slim-ci</a></li><li><a href="https://docs.getdbt.com/docs/dbt-cloud/using-dbt-cloud/cloud-enabling-continuous-integration">Enabling CI | dbt Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc0594514308" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vantageai/how-to-use-slim-ci-with-dbt-core-bc0594514308">How to use slim CI with dbt-core</a> was originally published in <a href="https://medium.com/vantageai">VantageAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to enforce good Pull Requests on Github]]></title>
            <link>https://medium.com/vantageai/how-to-enforce-good-pull-requests-on-github-727e9c118106?source=rss-ad6cec1eb34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/727e9c118106</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[pull-request]]></category>
            <dc:creator><![CDATA[Björn van Dijkman]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 13:57:23 GMT</pubDate>
            <atom:updated>2022-03-02T14:21:30.629Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using a pull request template, labeler and a semantics file</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h31uQMHpsT7_6ZOeEehAwQ.png" /><figcaption>Source: <a href="https://www.atlassian.com/blog/bitbucket/5-pull-request-must-haves">https://www.atlassian.com/blog/bitbucket/5-pull-request-must-haves</a></figcaption></figure><p>You have worked hard on a new feature or on a bug, and it is time to open a pull request to notify your team members that the feature or fix that you worked on, is ready. It&#39;s the reviewers job to review your code and thoroughly discuss the implementation of a feature before approving the merge to main. But what about a closer look at the pull request itself? Are there any standards or best practices that we should care about?</p><h4>Should you care?</h4><p>The answer to this is YES! And the reasons why are discussed in <a href="https://hugooodias.medium.com/the-anatomy-of-a-perfect-pull-request-567382bb6067">this</a> excellent blogpost by Hugo Dias. A pull request should be able to be reviewed easily and quickly. To facilitate this, the following actionable insights were shared:</p><ul><li>A pull request should give details on <strong>what</strong> was changed, <strong>why</strong> it was changed and <strong>how</strong> it was changed</li><li>A pull request should be <strong>small.</strong> A pull request with more than 250 lines of code tends to take more than 1 hour to be reviewed</li><li>The title should be <strong>self-explanatory</strong>, describing what the pull request does</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4O8lQaDQdNvxtL47gv6kQ.png" /><figcaption>A bad pull request can hit you like a 🚋</figcaption></figure><h4>Learning by enforcing</h4><p>We could rely on our team members to have read that article and comply with the best practices that you discussed during a team meeting, or you could help them out a little bit using the following features in Github:</p><ul><li>A pull request template</li><li>A labeler.yml file to automatically assign labels to your pull requests</li><li>A semantic.yml file that validates the title of the pull request</li><li>And as a bonus, a CODEOWNERS file that automatically assigns a reviewer to a pull request</li></ul><p>My repository with the code for this tutorial can be found <a href="https://github.com/bjornvandijkman1993/pull-request-automation">here</a>.</p><h4>Pull Request template</h4><p>You can put a pull_request_template.md file with your desired template in your .github folder to automatically include the template’s contents in the pull request body. If you want to have your team members explain <strong>what</strong> was changed in the code, <strong>why</strong> it was changed and <strong>how</strong> it changed you could do something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37c86e3ac51d946a2005e9cd0a99273b/href">https://medium.com/media/37c86e3ac51d946a2005e9cd0a99273b/href</a></iframe><p>The body shown above will automatically be included when a pull request is opened. Why the code was changed should ideally be explained in a Jira (or any other) ticket. Linking to the relevant issue is helpful in explaining why you wrote this code and opened this pull request.</p><h4>Labeler</h4><p>A labeler.yml file is used to automatically assign labels to pull requests. A label can be assigned based on:</p><ul><li>the number of lines of code changed in the pull request</li><li>the subdirectory in which the code was changed</li></ul><p>I included the following workflow in .github/workflows/pr-labeler.yml :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07841fce955e8742d6dcfe4a1a33f773/href">https://medium.com/media/07841fce955e8742d6dcfe4a1a33f773/href</a></iframe><p>Pull requests that contain more than 250 lines will be labeled as Too Large, because nobody got time for that. You can assign labels based on the subdirectory in which the code was changed in the following file .github/labeler.yml :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53c6606adf64c9ffef67740cf53139ea/href">https://medium.com/media/53c6606adf64c9ffef67740cf53139ea/href</a></iframe><p>Any changes that were made in .github/workflows will be labeled as ci/cd, and all markdown files will be labeled as documentation. Opening a pull request for some changes that I made in pr-labeler.yml now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*QlOifHFH7S7JJPPSUzBJNw.png" /><figcaption>The pull requests are starting to take shape 🆒</figcaption></figure><p>The pull request template is included, along with a label of the size (XS) and the label for the directory in which a change was made (ci/cd).</p><h4>A semantic title</h4><p>I started the title of the pull request with feat:, indicating that the contents of the pull request can best be characterized as a new feature. This follows the <a href="https://www.conventionalcommits.org/en/v1.0.0/">convention</a> used on top of commit messages:</p><ol><li>fix: a pull request of <em>type </em>fix patches a bug in your codebase</li><li>feat: a pull request of <em>type</em> feat introduces a new feature into the codebase</li><li>types other than fix: and feat: are allowed as well, including build:, chore:, ci:, docs:, style:, refactor:, perf:, test:, and others.</li></ol><p>To enforce these semantics, include a semantic.yml file in .github/. This file looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c560c130e7ed441bba7fc243c3bcf05/href">https://medium.com/media/2c560c130e7ed441bba7fc243c3bcf05/href</a></iframe><p>You also need to install the <a href="https://github.com/marketplace/semantic-pull-requests">semantic pull request application</a> from the GitHub Marketplace (it’s free!). After having merged the semantics file to your main branch and opening a new pull request without one of these prefixes, it will throw an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*XU16o2g8DMJ6CDLk4yHtLg.png" /><figcaption>Red Light 🔴</figcaption></figure><p>Changing the title of the pull request into a semantic one lets all checks pass, it is now ready to be merged!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*Axy0m0kQ2BPdE02YOxWG3Q.png" /><figcaption>Green light 💚</figcaption></figure><h4>Bonus trick</h4><p>Besides assigning labels to a pull request based on the contents, it is also possible to automatically assign reviewers using a CODEOWNERS file. You can use this file to define individuals or teams that are responsible for certain parts of the code in that repository. Just as the other files, the CODEOWNERS file can be put in the .github/ directory. A reviewer can be assigned based on the extension or the directory of a file. Lets add another Github account of mine as a codeowner for the .github directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f64528e8b70bfde37f5c693bf0aaf6a6/href">https://medium.com/media/f64528e8b70bfde37f5c693bf0aaf6a6/href</a></iframe><p>Opening a pull request that includes a change in the .github directory automatically assigns bjornvandijkman-ingka as a reviewer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*2Hm5v5LtG5B5JKea131T5w.png" /><figcaption>Automate everything 🤖</figcaption></figure><h4>Recap</h4><p>A good pull request should:</p><ul><li>give details on what was changed, why it changed and how it was changed → use a pull_request_template to give some guidance on this</li><li>be <strong>small → </strong>automatically assign size labels to the pull request using Github actions</li><li>The title should be <strong>self-explanatory</strong>, describing what the pull request does → use conventional commit semantics to describe the contents of the pull request</li><li>Lastly, you can use a CODEOWNERS file to automatically assign reviewers to a pull request.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*YJfUvAS1WTSHh3hI4MsaBA.png" /><figcaption>An overview of the closed PRs of my repository</figcaption></figure><p>Of course these tools only nudge the creator of the pull request into a certain direction. It is still the responsibility of the individual and the team to follow the best practices. You can temporarily put a link to the article of <a href="https://hugooodias.medium.com/?source=post_page-----567382bb6067-----------------------------------">Hugo Dias</a> in your pull request template to make sure that everyone reads it.</p><p>Thanks for reading! Feel free to follow me on <a href="https://www.linkedin.com/in/bj%C3%B6rn-van-dijkman-5103a671/">LinkedIn</a> if you are, like me, passionate about data science and the engineering side of it.</p><p>__________________________________________________________________</p><p>Links:</p><p><a href="https://hugooodias.medium.com/the-anatomy-of-a-perfect-pull-request-567382bb6067">https://hugooodias.medium.com/the-anatomy-of-a-perfect-pull-request-567382bb6067</a></p><p><a href="https://github.com/bjornvandijkman1993/pull-request-automation">https://github.com/bjornvandijkman1993/pull-request-automation</a></p><p><a href="https://www.conventionalcommits.org/en/v1.0.0/">https://www.conventionalcommits.org/en/v1.0.0/</a></p><p><a href="https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners">About code owners - GitHub Docs</a></p><p><a href="https://github.com/marketplace/semantic-pull-requests">https://github.com/marketplace/semantic-pull-requests</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=727e9c118106" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vantageai/how-to-enforce-good-pull-requests-on-github-727e9c118106">How to enforce good Pull Requests on Github</a> was originally published in <a href="https://medium.com/vantageai">VantageAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Data Scientists should write Unit Tests for their code]]></title>
            <link>https://medium.com/vantageai/why-data-scientists-should-write-unit-tests-for-their-code-e11532cd2042?source=rss-ad6cec1eb34b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e11532cd2042</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Björn van Dijkman]]></dc:creator>
            <pubDate>Mon, 18 Oct 2021 11:19:03 GMT</pubDate>
            <atom:updated>2021-10-19T12:22:56.207Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical example of testing your code using Pytest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFCNumMmk1-SnZezJHQbKw.jpeg" /></figure><p>Within the software engineering industry most developers will be familiar with <strong>unit testing</strong>. A unit test aims to check whether a part of your code operates in the intended way. Writing them has the following benefits:</p><ul><li>Reduces bugs when developing new features or when changing the existing functionality</li><li>Prevents unexpected output</li><li>Helps detecting edge cases</li><li>Tests can serve as documentation</li></ul><blockquote>All the benefits of unit testing for software engineering projects apply to data science projects as well</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5nakU2LHfIGkRGWKssQjMg.jpeg" /></figure><p>When should you start writing tests? The more certainty you want to have that your code works as intended, the more you want to invest in testing. When you are exploring a dataset for the first time, you will be less inclined to write them. But once you move beyond the exploratory phase, you should start adding some tests. Especially when code is used in production, writing tests can be very valuable and ultimately time-saving. I would like to showcase the need for it using a very practical example.</p><h3>Coding without testing</h3><p>Let’s say you have a dataframe with a text column that contains monetary values, e.g. “This product costs 5 euro”. Your goal is to write a function that extracts the value 5. This would look like something as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b1f3285b74741b4dba11e69fe016a8c/href">https://medium.com/media/2b1f3285b74741b4dba11e69fe016a8c/href</a></iframe><p>This works well for your current dataset, printing the following table:</p><pre>+--------+------------+--------+<br>| text   | row_number | money  |<br>+--------+------------+--------+<br>| 5 euro |          1 |    5.0 |<br>| 7 euro |          2 |    7.0 |<br>+--------+------------+--------+</pre><p>You are happy with this result and proud of yourself that you wrote some docstrings, so you incorporate the code into your pipeline and go on to your next task. The next week your manager comes back, furious. “Our application stopped working when new data came in, this is costing the business millions of $”, he exclaims. You anxiously go back to check out the new dataset and see what has gone wrong:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ee000b2bda2a4647a6002525bb15a4d/href">https://medium.com/media/1ee000b2bda2a4647a6002525bb15a4d/href</a></iframe><p>*An empty string has entered the chat*, resulting in the following error:</p><p><em>AttributeError: ‘NoneType’ object has no attribute ‘group’</em></p><p>You realize that you have to change the function to account for the scenario of the string being empty and make the relevant change to the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4384c35d15975ed21ed8ec7991b4cf7a/href">https://medium.com/media/4384c35d15975ed21ed8ec7991b4cf7a/href</a></iframe><p>However, you also come to the realization that you should have thought ahead, and that more unanticipated rows of data might appear in the future. You want to be fully confident that your code is working exactly as you intended.</p><h3>Unit Tests to the rescue</h3><p>This is the mindset that writing unit tests encourages. <strong>Pytest</strong> is a great tool for writing unit tests in Python. It makes writing tests short, easy to read, and provides great output. You can install pytest using pip install pytestand create a folder structure like the following:</p><pre>project/<br>├─ src/<br>│  ├─ regex.py<br>│  ├─ __init__.py<br>├─ test/<br>│  ├─ test_regex.py<br>│  ├─ __init__.py</pre><p>Within text_regex.py I import my extract_money function and write a first test. The test consists of the AAA (Arrange-Act-Assert) pattern. Some data is created (Arrange), in this case an empty string. We then invoke the method that we want to test (Act). Lastly, we check whether the outcome of the function matches the expected output (Assert).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6965e05cc4bf482e9c96df8bcd732480/href">https://medium.com/media/6965e05cc4bf482e9c96df8bcd732480/href</a></iframe><blockquote>Note: both the filename and the name of a test function itself should always start with <em>test_</em> , otherwise the function will not be detected by <em>pytest</em> .</blockquote><p>To check whether the function can now indeed handle an empty string I run the test from the root directory using pytest -v , which returns the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*4yleD4V4xOaY1H4eIvnSyQ.png" /></figure><p>Yeah, the test has passed! The change that we made before gives us the expected result. Alright, what other cases can we think of? Lets try and see what happens when there is a monetary value with decimals, like “5.49 euro”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95be04c01dc89db9ee0b8d5baf292194/href">https://medium.com/media/95be04c01dc89db9ee0b8d5baf292194/href</a></iframe><p>Again we run pytest -v , which gives us the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*wWfvSKSyQP3YpBRlTajCIQ.png" /></figure><p>As you can see, we got an AssertionError, stating that 9 is not equal to 5.49. It seems that our function only extracted the last digit of 5.49. Without this test, we would have been less likely to catch this error. The function would have returned the value 9, instead of throwing us an error. Good thing that we found this bug before the manager did.</p><blockquote>An important goal of testing within data science is to prevent unexpected output from happening</blockquote><p>The next step is to fix our code and make sure that it now passes the test that failed before, while still passing the first test that we wrote as well. A great thing about unit testing is that it gives you an overview of <strong>how your changes affect the project as a whole</strong>. The tests will make you aware if any of your code additions cause any unexpected consequences.</p><p>Furthermore, the fact that our initial function did not pass the decimal number test raises the question what other examples might come up that we did not anticipate. Maybe we will get a number separated by a comma, like 5,49 euro. Or the monetary value is formatted as € 5.49,-. Unit testing allows us to quickly check for these cases and some other less-common <strong>edge cases</strong>.</p><h3>Documentation</h3><p>You could argue that for this example you could use a site like <a href="https://regex101.com/">regex101</a> to test your regex. However, one of the advantages of unit tests that I highlighted in the introduction is that the tests can serve as <strong>documentation</strong>. Test functions illustrate which scenarios you thought of when developing a functionality and give concrete examples of these scenarios. When onboarding a new colleague to your project it becomes immediately clear to them what a given function is supposed to do, just by looking at the test functions. But also when coming back to the project yourself after a couple of months the tests will help you remember what you were trying to accomplish with your code.</p><h3>Thank you for reading!</h3><p>I hope that this article has given you a better understanding about why testing is a good idea for your data science projects.</p><p>I encourage you to use this code as a basis and try to write some more tests for this function. The <strong>code</strong> used in this article can be found <a href="https://github.com/bjornvandijkman-vantage/unit_testing_tutorial">here</a>. In a next article on testing I would like to focus on more advanced functionalities of Pytest like the <strong>fixture</strong> and <strong>parametrize</strong> <strong>decorators</strong>.<strong> </strong>Feel free to add me on <a href="https://www.linkedin.com/in/bj%C3%B6rn-van-dijkman-5103a671/">LinkedIn</a> if you are, like me, passionate about data science and the engineering side of it.</p><p><em>Thank you to my colleagues Ruurtjan Pul, Max Ortega del Vecchyo, Menno Liefstingh and Karlijn Schipper for reviewing this blog</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e11532cd2042" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vantageai/why-data-scientists-should-write-unit-tests-for-their-code-e11532cd2042">Why Data Scientists should write Unit Tests for their code</a> was originally published in <a href="https://medium.com/vantageai">VantageAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>