In cloud computing and web development, Python developers have two powerful tools: Kubernetes and Django.
Kubernetes is an open-source platform trusted by developers worldwide to automate the deployment and scaling of containerized applications. It uses containers, which are lightweight alternatives to virtual machines, allowing applications to run and scale efficiently. Key features of Kubernetes include self-monitoring, auto-scaling, health checks, and smooth rollouts, thanks to its use of immutable infrastructure.
Django is a powerful Python framework that follows the model-view-template (MVT) architectural pattern. Its main goal is to make web development easier by handling much of the complexity for developers. Django is considered "batteries-included," meaning it provides everything needed to build a project from prototyping to production.
The MVT pattern in Django is similar to the popular Model-View-Controller (MVC) pattern. However, Django manages the "controller" internally. The "Model" represents the data access layer, dealing with database interactions. The "View" is where data from the model is shown, and the "Template" stores HTML files to render web pages.
Django automates many tedious tasks for developers. It comes with a built-in user authentication system that manages accounts, permissions, and sessions. It also automates form creation by reading data from models to generate input forms. One standout feature is Django's admin interface, which is automatically generated from models and allows for easy content management.
Django automates many tedious tasks for developers. It comes with a built-in user authentication system that manages accounts, permissions, and sessions. It also automates form creation by reading data from models to generate input forms. One standout feature is Django's admin interface, which is automatically generated from models and allows for easy content management.
Django’s components are loosely coupled, allowing them to work together through well-defined interfaces. This flexibility means you can use Django for small projects and easily scale it as your project grows.
This guide walks you through building a Django app that fetches stock market data. We’ll start by creating the Django environment and gradually build the app step by step.
1. Ensure Python3 is installed. You can check using the following command:
python3 --version
If Python is not installed, you can install it using the following commands:
sudo apt update
sudo apt install python3
sudo apt install python3-venv python3-pip
2. Check Pip (Python package manager) is installed. It is required for installation of Django and other Python packages
pip3 --version
If pip3 is not installed, you can install it using the following command:
sudo apt install python3-pip
3. Install Django Framework: Use the following pip3 command to install Django framework. For the purpose of this tutorial, we will use the default SQLite database.
pip3 install django
4. We will use the development server for Django. We will not install Nginx / Apache / etc. for this tutorial
1. Now change folder to /usr/local/ folder. Use the following command:
cd /usr/local/
2. Create the django project using the following command:
django-admin startproject stock_market_api
As shown in the above screenshot, Django will create a folder called stock_market_api inside the /usr/local/stock_market. In order see the contents of stock_market_api folder, use the following command:
cd stock_market_api
ls -la
1. manage.py
This file serves as a command-line utility that helps you to interact with your project. It provides a variety of commands to perform tasks related to database management, testing, running servers, and more.
Run the Development Server:
You can start the built-in Django development server using:
python3 manage.py runserver
You can also specify IP address and the port
python3 manage.py runserver 0.0.0.0:8080
Make migrations
manage.py helps manage your database schema changes using Django’s migrations system.
python3 manage.py makemigrations
Apply migrations
Applies the pending migrations to the database.
python3 manage.py migrate
Create a Superuser
This command creates a superuser account (admin) that can log into the Django admin interface.
python3 manage.py createsuperuser
Open a Django Shell
The shell command opens an interactive Python shell with your Django environment preloaded, so you can interact with your models and database directly.
python3 manage.py shell
Run Unit Tests
You can run your project’s unit tests using the test command. Django will automatically discover tests within your project’s tests.py or tests directory and execute them.
python3 manage.py test
Start a new app
Creates the boilerplate code for a new Django application within your project.
python3 manage.py startapp <app_name>
Check for project issues
The check command looks for potential problems in your project without running migrations or launching the server.
python3 manage.py check
2. models.py
In Django, the models.py file is where you define the structure of your application's data. It contains models, which are Python classes that map to database tables. Each class defines a database table, and the class attributes define the table’s columns. Django's ORM (Object-Relational Mapping) system then handles translating these models into SQL statements to interact with the database.
Each model class represents a table in the database:
- Attributes of the model represent fields (columns) in the table.
- The class itself represents the table (rows of data).
- In the class, fields are defined using Django's field types (e.g., CharField, IntegerField, DateField)
The following class snippet shows how we can define a models.py file for Product table:
3. views.py
In Django, views.py is a core component of the application where the logic for handling user requests and returning responses is implemented. It defines views—functions or classes that receive HTTP requests, process data (e.g., by interacting with the database or performing calculations), and return HTTP responses, often in the form of HTML, JSON, or other formats.
Key functions of views.py include:
- Handling HTTP requests: Views handle various HTTP methods like GET, POST, PUT, DELETE, etc.
- Returning HTTP Responses: Views typically return HTTP responses, often rendered as HTML pages using templates, but can also return other data types like JSON or plain text. A common pattern is to use HttpResponse or JsonResponse to send data back to the client.
- Interacting with Models: Views often retrieve data from the database using models and pass that data to templates to be rendered as part of an HTML response.
- Rendering Templates: A view can use the render() function to combine a template with context data (e.g., variables to be displayed in the template), producing an HTML response.
- The following code show a simple view that renders an HTML template with data retrieved using a data model:
4. urls.py
In Django, urls.py is responsible for defining the URL patterns (routes) that map to views in your application. When a user accesses a URL in a Django application, the urls.py file determines which view should handle the request and return the appropriate response, such as an HTML page, a JSON object, etc.
- URL Routing: It contains URL patterns that map specific URLs to view functions or class-based views. This is done using the path() or re_path() functions.
- Views Assignment: Each pattern in urls.py is associated with a view (a Python function or class) that processes the HTTP request and returns a response.
- Namespace Definition: If you have multiple applications within a Django project, urls.py can help differentiate them using namespaces to avoid URL conflicts.
- Include Other URLs: In a larger project, urls.py can include URL configurations from other apps using the include() function, allowing for modular and reusable URL patterns.
- The following code show a simple urls.py file:
In the next part:
We will code the Django API App that will retrieve stock prices based on the provided stock symbol in the query string.
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 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.