Build a simple API using Django Rest Framework, and use Redis for caching.
.sql
file, and an
additional data in the form of a csv
file. To convert from SQLite to a PostgreSQL database,
follow these steps.
.sql
File
The SQLite .sql file typically contains SQL commands to recreate the database schema and insert data.
However, SQLite and PostgreSQL have some differences in SQL syntax, so the file might need adjustments.
Common differences to look for:
INTEGER
, TEXT
, BLOB
, REAL
, and NUMERIC
. PostgreSQL has more specific types like SERIAL
, BOOLEAN
, and VARCHAR
.
Replace SQLite types with the corresponding PostgreSQL types where necessary.AUTOINCREMENT
with INTEGER PRIMARY KEY
. In PostgreSQL, use SERIAL
or BIGSERIAL
.TIMESTAMP
or DATE
.1
/0
. PostgreSQL uses TRUE
/FALSE
or t
/f
.AUTOINCREMENT
:
SERIAL
columns are correctly configured.
To view your database, you can also use TablePlus or DBeaver.
docker-compose.yml
file. Paste the following content:
6379
for your own local machine. I just happen to have the port used for another Redis server, thus the reason on why I had to use port 16379.
After saving the file, we are now to ready to start the container! Run it in detached mode using -d
flag to let it run in background of your terminal.
redis-cli
on its terminal. Let’s send a PING
!
requirements.txt
with the following:
project
and apps
.
settings.py
, add the following configurations to set up our Django application.
managed
option to False
in the model’s Meta
class. This tells Django that the table is already managed outside of Django’s ORM,
and Django should only use this model for querying, inserting, updating, or deleting data in the table, without trying to apply any schema changes.
One of the shortcut to infer the schema of tables from your connected database is by running the following command:
primary_key=True
api/models.py
.
following smart money
.
Based on this, let’s create a view which returns a list of companies and the associated institutional trading data. Since we are not allowing the users to post, update, or delete our data, we can use
the class ListAPIView
which only allows GET
method.
ListAPIView
is a class-based view provided by Django Rest Framework that is specifically designed to handle GET requests for listing a queryset of objects.
It is a powerful tool for building API endpoints because it simplifies the process of creating read-only endpoints that return a collection of model instances, typically in JSON format.
Institutions
objects that should be retrieved from the database.Institutions
objects into JSON.InstitutionsView
will automatically handle GET requests to list all instances of Institutions
, serialized with InstitutionsSerializer
.
That was easy, right? It took us just 3 lines of codes and we’re basically done. However, it would be nice if we can improve this by adding the capabilities to filter our query by a specific
institution name. This will be helpful if we want to follow a certain institution, i.e: Eastspring Investments. We can do this by overriding our queryset.
name
. If it’s provided, we return only the companies which have the given institution as one of its top sellers.
Notice that since top_sellers
is a JSONField
(originally a list of JSONB in our database schema), Django ORM supports querying the field based on a specific key-value, just like you learned in the previous chapter.
urls.py
file, serves as a roadmap that directs users’ requests to the corresponding views in your application.
Each Django project contains a urls.py
file in its main project directory. This file defines the URL patterns that route requests to the correct views. Additionally, each app within the project can have its own urls.py
file to handle app-specific URLs.
urls.py
:
urls.py
(api/urls.py):
caching
is the final touch of this lab.
cache_page
decorator, which caches entire views for a specified period, I’m going to demonstrate how to use Django’s low-level cache API.
The low-level cache function gives you granular control over which parts of your data should be cached.
This approach offers greater flexibility, allowing you to cache specific parts of your application as needed, rather than entire views or pages.
Let’s overwrite the list
function.
None
is returned.
self.get_queryset()
. This method fetches the required data directly from the database.
top_buyers
.Q
method to implement OR
filtering.permission
and throttling
policies which take in
the provided credentials to determine whether the request should be permitted or not.
Django REST framework provides several authentication schemes out of the box, and also allows you to implement custom schemes.
Show full code