How do you set up a CI/CD pipeline using CircleCI for a Python Flask project?

Setting up a CI/CD pipeline is crucial for modern software development. It ensures that code changes are automatically tested and deployed, maintaining the integrity of your application. In this article, we will guide you on how to set up a CI/CD pipeline using CircleCI for a Python Flask project. We will cover everything from creating a Flask application to integrating CircleCI and Docker for continuous integration and deployment.

Getting Started with Your Python Flask Project

To set up a CI/CD pipeline, you first need a Python Flask project. Flask is a lightweight web framework that makes it easy to build web applications.

Additional reading : What are the techniques for optimizing Elasticsearch queries for large datasets?

Create Your Flask App

Begin by creating a new directory for your project. Open your terminal and run the following commands:

mkdir flask_ci_cd
cd flask_ci_cd
python3 -m venv venv
source venv/bin/activate
pip install Flask

Next, create a file named app.py in your project directory:

Have you seen this : How can you use AWS Elastic Beanstalk for deploying scalable web applications?

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, CircleCI!"

if __name__ == "__main__":
    app.run(debug=True)

This basic Flask application returns "Hello, CircleCI!" when accessed.

Setting Up Requirements

Create a requirements.txt file to manage your app’s dependencies. Add the following line to requirements.txt:

Flask==2.0.2

Run the command:

pip install -r requirements.txt

Your basic Flask application is now ready. Next, we will focus on testing.

Writing Tests for Your Flask Application

Testing ensures that your Flask application functions correctly. We’ll use the unittest framework to write tests for our Flask app.

Create a Test File

Create a new directory named tests and add a file named test_app.py inside it:

import unittest
from app import app

class FlaskTestCase(unittest.TestCase):

    def test_home(self):
        tester = app.test_client(self)
        response = tester.get('/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, b"Hello, CircleCI!")

if __name__ == "__main__":
    unittest.main()

Running Your Tests

You can run the tests using the following command:

python -m unittest discover tests

If everything is set up correctly, the tests will pass. Now, let’s integrate CircleCI for continuous integration.

Setting Up CircleCI for Continuous Integration

CircleCI is a popular CI/CD tool that automates the testing and deployment process. Setting it up involves creating a configuration file and integrating it with your GitHub repository.

Integrating Your Project with GitHub

Push your project to a GitHub repository. If you don’t have a repository yet, create one and follow these steps:

git init
git add .
git commit -m "Initial commit"
git remote add origin <your github repo URL>
git push -u origin main

Adding CircleCI Configuration

Create a directory named .circleci in your project root and add a file named config.yml:

version: 2.1

executors:
  python-executor:
    docker:
      - image: circleci/python:3.8

jobs:
  build:
    executor: python-executor
    steps:
      - checkout
      - run:
          name: Install dependencies
          command: |
            python -m venv venv
            . venv/bin/activate
            pip install -r requirements.txt
      - run:
          name: Run tests
          command: |
            . venv/bin/activate
            python -m unittest discover tests

workflows:
  version: 2
  test:
    jobs:
      - build

This configuration file defines a job named build that installs dependencies and runs tests.

Enabling CircleCI

  1. Go to CircleCI.
  2. Sign in with your GitHub account.
  3. Navigate to "Projects" and set up the project you just committed.
  4. Click on "Set Up Project" and then "Start Building".

CircleCI will now automatically run tests every time you push changes to your repository.

Integrating Docker for Containerization

Using Docker for containerization ensures that your application runs consistently in different environments. This is especially useful for deployment.

Creating a Dockerfile

Create a file named Dockerfile in your project root:

# Use the official Python image from Docker Hub
FROM python:3.8

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt

# Make port 5000 available to the world outside this container
EXPOSE 5000

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]

Building and Running the Docker Image

Build and run the Docker image using the following commands:

docker build -t flask-app .
docker run -p 5000:5000 flask-app

Your Flask app should now be running in a Docker container.

Pushing the Docker Image to Docker Hub

To simplify deployment, push your Docker image to Docker Hub. First, log in to Docker Hub:

docker login

Then, tag and push your image:

docker tag flask-app <your-dockerhub-username>/flask-app
docker push <your-dockerhub-username>/flask-app

Congratulations! You’ve successfully set up a CI/CD pipeline for a Python Flask project using CircleCI. By integrating CircleCI, Docker, and GitHub, you can automate testing and deployment, ensuring that your application remains robust and up-to-date. This process not only facilitates continuous integration and continuous deployment but also streamlines the development workflow, making it more efficient and reliable.

By following the steps outlined in this article, you’ve built a strong foundation for maintaining the integrity and quality of your Flask application. Whether you’re working on a solo project or collaborating with a team, this setup will enhance your productivity and ensure that your application is always in a deployable state.

Keep exploring and improving your CI/CD pipeline by incorporating advanced features and best practices. Happy coding!

CATEGORIES:

Internet