
Python is a high-level programming language that allows you to create highly available applications with support for popular relational database systems such as MySQL. To permanently store data records and interact with databases, you can use a Vultr Managed Database for MySQL with Python to improve your application structure and availability.
This guide explains how to use a Vultr Managed Database for MySQL with Python. You are to create a sample application that uses the Python MySQL connector to query user data and interact with the database tables.
Before you begin:
Deploy a Vultr Managed Database for MySQL
Install the MySQL client tool on your development machine
Depending on your computer operating system, use a package manager such as
brewon macOS,apton Ubuntu/Debian systems,dnfon RHEL systems, among others to install the MySQL client tool. For example, on Ubuntu, run the following command:
Update the Python Pip package manager
To interact with your Vultr Managed Database for MySQL, install the Python mysql-connector-python driver and set up the database as described in the steps below.
Using pip, install the Python MySQL driver
Using the MySQL client tool, connect to your Vultr Managed Database for MySQL
Replace the above values with your actual Vultr Managed Database for MySQL details:
prod-db.vultrdb.comvultradmin16751When prompted, enter your Database password and press Enter to access the console.
Create a sample company_portal database
Create a new database user app_user with a strong password
Grant the user full privileges to the company_portal database
Refresh the MySQL privileges
Switch to the company_portal database
Create a sample products table with three columns
In the above table, the AUTO_INCREMENT value on the product_id column assigns unique product_ids for new records.
Add sample data to the products table
View the products table data
Output:
Exit the MySQL console
You have set up a MySQL database, a products table, and added sample table data to use in your Python application. You can add multiple columns and records to match your application structure.
Data-driven applications use Create, Read, Update, and Delete (CRUD) operations to handle user interactions. Set up a Python application that performs these CRUD operations with the following parts:
A User Interface (UI)
An Application Programming Interface (API). The user interface communicates to the API that uses the following HTTP methods to translate requests to CRUD operations
POST: Creates a new resource in the applicationGET: Retrieves the application resourcesPUT: Updates the details of an existing resourceDELETE: Removes a resource from the application.Based on the above structure, create a Python API application that accepts HTTP requests to interact with the MySQL database.
Create a new project directory
Switch to the directory
Using a text editor such as nano, create a new mysql_gateway.py file
Add the following contents to the file. Replace the host, password, and port values with your actual Vultr Managed Database for MySQL details
Save and close the file.
In the above application:
import mysql.connector imports the MySQL connector for Python to your application
The MysqlGateway class defines the following methods:
__init__(self) executes every time you create a new instance of the MysqlGateway class and initializes the last_row_id variable to 0db_conn(self) connects to the managed database and returns a reusable connection using the return mysql_con statementquery(self, query_string, resource_id = "") runs the SELECT SQL command and returns results from the database table as a dictionary with the column names and valuesexecute(self, query_string, data) runs the INSERT, UPDATE, and DELETE operations and returns the lastrowid when you insert a new recordIn the sample application database, you have a single products table. A mission critical-application can have hundreds of tables such as payment_methods, banks, customers, sales, and inventories. To organize your application data, create a resource module for every table. In this section, create the products resource module as described below.
Create a new products.py file
Add the following contents to the file
Save and close the file
In the above module, the Products class has the following methods:
__init__(self, mysql_gateway) runs when you call the module for the first time. The method takes the mysql_gateway class instance as an argument to connect to the database for each CRUD operationcreate(self, json_data) accepts data in JSON format and uses the insert into products (product_name, retail_price) values (%s, %s) SQL statement to insert the data to the products table by executing the self.dg.execute(...) from the mysql_gateway moduleread(self, resource_id = "") runs the select * from products or select * from products where product_id = %s SQL statements to either return all products or a single product.update(self, json_data, resource_id) runs the update products set product_name = %s, retail_price = %s where product_id = %s SQL command to update a product that matches the product_iddelete(self, resource_id) deletes a product that matches the given resource_id using the delete from products where product_id = %s SQL commandTo use the database structure that includes a MySQL gateway class and products module, create the application's main function that executes when you run the application as described below.
Create a new index.py file
Add the following contents to the file
Save and close the file
In the above application code:
import section declares the necessary modules to offer HTTP functionalities and imports the custom mysql_gateway and products modules you created earlierWebServerHandler() is a handler class for the HTTP server. Within the class, init_db() invokes your custom mysql_gateway module. Then, the write_http_output(self, resp) method sets the correct HTTP response headers for the web application.do_POST(self), do_GET(self), do_PUT(self), and do_DELETE(self) methods match each HTTP client request to the correct resource methodhttpd declaration starts an HTTP server that listens for incoming requests on port 8080 and directs the requests to the WebServerHandler() classList files in your working directory
Output:
Verify that the mysql_gateway.py, products.py, and index.py files are available
Run the Python application as a background process
Output
Establish a new SSH connection in a new terminal window and execute the following curl commands to test all CRUD operations:
Using the curl utility, test the following application CRUD operations
Create a new product
Output:
Retrieve all products in the database
Output:
Get a single product
Output:
Update product details. For example, the product ID 4
Output:
Delete a product
Output:
You have used a Vultr Managed Database for MySQL for Python by creating a sample CRUD operation application that allows you to create, update, and delete database records. By integrating a managed database, you can concentrate development efforts on the Python application to offer more features and handle user interactions.
0 Comments
Be the first to comment and share your perspective with the community.