Our Blog

Django Meets Kubernetes: Unleash The Power Of Python
AI LLM Models

Django Meets Kubernetes: Unleash The Power Of Python - Part 2

Part 1 of the blog "Django Meets Kubernetes" explores the power of combining Django, a popular Python web framework, with Kubernetes for deploying scalable applications. It covers an introduction to both technologies, highlighting Django's MVT architecture and Kubernetes' container orchestration capabilities. The blog provides a step-by-step guide to setting up a Django project for fetching stock market data, including environment setup, key Django files like models.py, views.py, and urls.py, and using Django's built-in development server.

In this blog, we will show step-by-step instructions on how to setup Django API application. This API will query Postgres Database to retrieve information about the stock prices from the database.

Section 1 : Configuring Django’s Database access

To configure Django for connecting to a PostgreSQL database, you'll need to adjust the DATABASES setting in the settings.py file. Here's how to do it:

1. Access your Django installation folder. Note: We have installed it in. We have installed it in the following folder:
/usr/local/stock_market_api

2. Our app is called ‘stock_market_api’ as well, hence settings.py will be stored in:
/usr/local/stock_market_api/stock_market_api

3. Open settings.py in your Django project.

4. Locate the DATABASES setting.

5. Replace the default ENGINE and NAME with PostgreSQL settings.

6. Set the USER, PASSWORD, HOST, and PORT to match your PostgreSQL credentials.
Django Database settings

Section 2 : Creating Django Model for database interaction

Django models are a crucial component of Django's Object-Relational Mapping (ORM) system, allowing developers to define the structure of their database tables as Python classes. Each model class represents a table in the database, and its attributes define the columns. Django automatically handles creating, updating, and querying the database through these model classes, eliminating the need for manual SQL. This ORM simplifies interactions with the database and improves code maintainability, making Django a powerful framework for web development.

Here is the code for the StockPrice model:

from django.db import models

class StockPrice(models.Model):
    status = models.CharField(max_length=10)
    date = models.DateField()
    symbol = models.CharField(max_length=10)
    open_price = models.DecimalField(max_digits=10, decimal_places=2)
    high = models.DecimalField(max_digits=10, decimal_places=2)
    low = models.DecimalField(max_digits=10, decimal_places=2)
    close_price = models.DecimalField(max_digits=10, decimal_places=2)
    volume = models.BigIntegerField()
    after_hours = models.DecimalField(max_digits=10, decimal_places=2)
    pre_market = models.DecimalField(max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'stock_prices'  # Explicitly define the table name in the database

    def __str__(self):
        return f"{self.symbol} - {self.date}"

What are Migrations and How to Run them

Django Migrations are a way to manage changes to your database schema over time. They allow you to create, modify, and delete database tables and fields automatically, based on changes in your Django models. Migrations track these changes using versioned files, enabling easy database updates and version control.

1. Creating Migrations
python3 manage.py makemigrations stock_price_api
Django Create Migration

2. Running the migrations
python3 manage.py migrate
Apply Migration

Load Sample Data

Let’s add some test data in the database:

INSERT INTO stock_price (status, date, symbol, open_price, high, low, close_price, volume, after_hours, pre_market, created_at, updated_at)
VALUES ('active', '2024-11-01', 'AAPL', 180.50, 182.75, 179.80, 181.00, 12000000, 181.25, 180.00, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

INSERT INTO stock_price (status, date, symbol, open_price, high, low, close_price, volume, after_hours, pre_market, created_at, updated_at)
VALUES ('inactive', '2024-11-02', 'GOOGL', 2650.30, 2680.40, 2620.00, 2675.50, 8000000, 2660.00, 2640.00, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

INSERT INTO stock_price (status, date, symbol, open_price, high, low, close_price, volume, after_hours, pre_market, created_at, updated_at)
VALUES ('active', '2024-11-03', 'MSFT', 330.75, 335.50, 329.20, 333.30, 9000000, 332.80, 331.50, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

INSERT INTO stock_price (status, date, symbol, open_price, high, low, close_price, volume, after_hours, pre_market, created_at, updated_at)
VALUES ('active', '2024-11-04', 'TSLA', 800.20, 820.00, 790.50, 810.00, 15000000, 815.50, 805.00, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

INSERT INTO stock_price (status, date, symbol, open_price, high, low, close_price, volume, after_hours, pre_market, created_at, updated_at)
VALUES ('active', '2024-11-05', 'AMZN', 3500.75, 3550.00, 3480.50, 3525.00, 7000000, 3530.00, 3495.00, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);

Section 3 : Creating API for Fetching All Quotes or Specified Quote

In this section, we will create the REST API using the Django Reset Framework:

1. Install Django RestAPI Framework

Install the Django RESTAPI framework using the following command:
pip3 install djangorestframework Install Django RestAPI Framework

2. Update the Settings

Update settings.py and add rest framework in the installed apps:

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'stock_market_api', 'rest_framework', ]

3. Create the Serializer for StockPrice Object

Django models store data in Python objects, but when you want to expose this data via a REST API, it needs to be converted to a format like JSON or XML. Serializers handle this conversion. # stock_market_api/serializers.py from rest_framework import serializers from .models import StockPrice class StockPriceSerializer(serializers.ModelSerializer): class Meta: model = StockPrice fields = '__all__'

4. Update methods in views.py

In Django, views.py is where you define your application's logic. Views are essentially Python functions or classes that handle incoming HTTP requests and return HTTP responses. They serve as the bridge between your models (i.e., your data) and the templates or API responses (i.e., what the user sees or interacts with).

We want to add two endpoints:
1. Get all updated stock quotes This endpoint will return a list of all stock quotes in the database.
2. Get a specific stock quote by symbol This endpoint will return data for a single stock, based on its symbol (e.g., "AAPL").

# stock_market_api/views.py from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import StockPrice from .serializers import StockPriceSerializer # Get all updated stock quotes @api_view(['GET']) def get_updated_quotes(request): quotes = StockPrice.objects.all().order_by('-updated_at') # Order by latest update serializer = StockPriceSerializer(quotes, many=True) return Response(serializer.data) # Get stock quotes by symbol @api_view(['GET']) def get_quote_by_symbol(request, symbol): # Use filter to get all stock prices for the given symbol stocks = StockPrice.objects.filter(symbol=symbol.upper()) # If no stock prices found, return a 404 response if not stocks.exists(): return Response({"detail": "Stock symbol not found"}, status=404) # Serialize the queryset and return the response serializer = StockPriceSerializer(stocks, many=True) return Response(serializer.data)

5 . Define URL Patterns

In Django, the urls.py file is responsible for defining the URL patterns (routes) that your application can respond to. It acts as a "map" between the URLs that users (or clients) enter into their browsers and the views that handle those requests. Each route in urls.py is linked to a specific view function or class that processes the request and returns a response.

urls.py helps us in:
1. URL Routing: It directs incoming HTTP requests to the correct view functions or classes.
2. Endpoints: Makes it easy to manage and organize your application's various API endpoints or web pages.
3. Scalability: As your application grows, you can keep URL patterns organized by splitting them into multiple files.

6. Update Project's urls.py

#Location: /usr/local/stock_market_api/stock_market_api/urls.py from django.urls import path from . import views urlpatterns = [ path('api/quotes/', views.get_updated_quotes, name='get_updated_quotes'), path('api/quotes//', views.get_quote_by_symbol, name='get_quote_by_symbol'), ]

7. Update Main urls.py

#Location: /usr/local/stock_market_api/urls.py # /usr/local/stock_market_api/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('stock_market_api.urls')), # Correctly include your app's urls ]

8. Start Django Application

First ensure the Django API code is correct by running the following command: python3 manage.py check Start Django Application - first do the dry run

Now run the server, using the following command: python3 manage.py runserver Start Django Application

9. Testing the API

We will use the Linux CURL command to test the APIs. To Get all of the quotes, use the following command: curl http://localhost:8000/api/quotes/ Test quotes end point

We will use the Linux CURL command to test the APIs. To Get all of the quotes for given symbol, use the following command: curl http://localhost:8000/api/quotes/AAPL/ Test quotes end point for Apple Quotes

Section 4 : Upcoming in the next blog

In the next blog, we will deep dive into Django Application deployment using Kubernetes. We will review the basics of Kubernetes and then we will deployment our Stock Market API on Kubernetes.

Looking for a reliable tech partner? FAMRO-LLC can help you!

Our development rockstars excels in creating robust and scalable solutions using Django, a powerful Python framework known for its rapid development capabilities and clean, pragmatic design. FAMRO’s team ensures that complex web applications are built quickly and with precision. Their expertise allows businesses to focus on enhancing their digital presence while leaving the intricacies of backend development in skilled hands.

On the deployment side, FAMRO's Infrastructure team takes charge with Kubernetes, a leading platform for container orchestration. Their deep knowledge of Kubernetes ensures that applications are seamlessly deployed, scaled, and managed in cloud environments. By automating key processes like service discovery, load balancing, and resource scaling, FAMRO’s Infrastructure team guarantees that applications not only perform well under high traffic but also remain resilient and easy to maintain. This combination of development and DevOps expertise enables FAMRO to deliver end-to-end, highly scalable solutions.

Please don't hesitate to Contact us for free initial consultation.

Our solutions for your business growth

Our services enable clients to grow their business by providing customized technical solutions that improve infrastructure, streamline software development, and enhance project management.

Our technical consultancy and project management services ensure successful project outcomes by reviewing project requirements, gathering business requirements, designing solutions, and managing project plans with resource augmentation for business analyst and project management roles.

Read More
2
Infrastructure / DevOps
3
Project Management
4
Technical Consulting