
Apache Cassandra is a fault-tolerant high-availability NoSQL database. The database server uses a distributed system model to handle large amounts of data across different nodes, and implements a modern peer-to-peer architecture. This architecture is different from the traditional primary-secondary architecture which is prone to a single point of failure.
Among the key advantages of the Cassandra database server is scalability. Depending on your application needs, you can scale your database up by adding new nodes or down by deleting nodes. These high-performance features make Cassandra one of the best database systems for deploying Python applications.
This guide explains how to implement the Apache Cassandra database with Python.
Before you start:
In this section, set up the Cassandra database, that's used by the sample application with a single products table to store product information as described in the steps below.
Log in to the Apache Cassandra database server.
Create a sample online_shop keyspace.
In Cassandra, a keyspace is a data container similar to a database in traditional relation database management systems. The above command creates a new keyspace named online_shop.
Switch to the new online_shop keyspace.
Create a sample products table with three columns.
In the above table, the product_id column is a PRIMARY KEY that uniquely identifies the products. The product_name column stores the product names and the retail_price column stores the final price that customers pay for the products.
Populate the products table with sample data.
View the products table data.
Output:
Exit the database server.
To keep your application organized, Python source code files must be in a separate directory. For the Python application to connect to the Apache Cassandra database you created earlier, install the cassandra-driver module as described in the following steps.
Create a new project directory.
Switch to the directory.
Install the pip Python package manager.
Using pip, install the Cassandra database driver.
The above command installs cassandra-driver, a feature-rich and highly-customizable Python module for the Apache Cassandra database.
To promote code reusability in your Python application, develop a central module that connects to the Apache Cassandra database to execute queries. The module works as a gateway to the Apache Cassandra database server. Later, you can import and reuse the module in other Python source code files. To create the module, follow the steps described below.
Using a text editor such as Nano, create a new cassandra_gateway.py file.
Add the following contents to the file.
Save and close the file.
Below is what the file declarations represent:
The declaration below imports the Apache Cassandra database driver for Python.
The dict_factory function returns data from the products table in a dictionary format that lists the column names. The dictionary format displays meaningful data for JSON responses.
The CassandraGateway class hosts three methods as below:
db_session(self): Executes the clstr = Cluster() and session = clstr.connect('online_shop') functions to connect to the Apache Cassandra keyspace you created earlier.execute(self, json_data): Reuses the db_session() method to run db_session.prepare(query_string), stmt.bind([product_id, product_name, retail_price]) and db_session.execute(prepared_query) functions to insert data into the products table using a parameterized query (insert into products (product_id, product_name, retail_price) values (?, ?, ?);).query(self, product_id = 0): Runs a SELECT statement against the products table and returns the output as a list using the return list(rows) declaration. if product_id == 0: ... else ... returns either the full list of products or a specific product depending on whether the HTTP client request that specifies a product_id value when making a GET request.Every Python application requires a main file that executes when the application starts. In this section, create a new index.py file that reuses the custom cassandra_gateway module you created in the previous step as described in the steps below.
Create a new index.py file.
Add the following contents to the file.
Save and close the file.
Below is what the file declarations represent:
The code below imports HTTP functionalities.
The following lines enable JSON formatting and Cassandra database functions.
The HttpHandler(http.server.SimpleHTTPRequestHandler) class responds to HTTP POST and GET requests to insert and retrieve data using the custom cassandra_gateway.py module.
The following lines run an HTTP server that listens for incoming connections on port 8080.
When all Python source code files are created, run and test your application's logic as described in the following steps.
Run the application.
Your output should look like the one below:
In a new terminal session, establish another SSH connection to the server.
Run the following HTTP GET request to list products from the database.
Output:
Specify a product_id at the end of the URL to retrieve a specific product.
Output:
Insert a new product into the Cassandra database by running the following HTTP POST request.
Output:
When all commands are successful, Your application is working correctly as expected.
In this guide, you implemented the Apache Cassandra Python module to perform basic database operations on a custom keyspace. You created a test database using the Cassandra CLI (cqlsh), set up a custom Python database gateway module, and reused it in a new source code file to execute queries on the Cassandra database.
To implement more Python database modules, visit the following resources.
0 Comments
Be the first to comment and share your perspective with the community.