Connect to TiDB with peewee

TiDB is a MySQL-compatible database, and peewee is a popular Object Relational Mapper (ORM) for Python.

In this tutorial, you can learn how to use TiDB and peewee to accomplish the following tasks:

  • Set up your environment.
  • Connect to your TiDB cluster using peewee.
  • Build and run your application. Optionally, you can find sample code snippets for basic CRUD operations.

peewee - 图1

Note

This tutorial works with TiDB Serverless, TiDB Dedicated, and TiDB Self-Hosted clusters.

Prerequisites

To complete this tutorial, you need:

If you don’t have a TiDB cluster, you can create one as follows:

If you don’t have a TiDB cluster, you can create one as follows:

Run the sample app to connect to TiDB

This section demonstrates how to run the sample application code and connect to TiDB.

Step 1: Clone the sample app repository

Run the following commands in your terminal window to clone the sample code repository:

  1. git clone https://github.com/tidb-samples/tidb-python-peewee-quickstart.git
  2. cd tidb-python-peewee-quickstart

Step 2: Install dependencies

Run the following command to install the required packages (including peewee and PyMySQL) for the sample app:

  1. pip install -r requirements.txt

Why use PyMySQL?

Peewee is an ORM library that works with multiple databases. It provides a high-level abstraction of the database, which helps developers write SQL statements in a more object-oriented way. However, peewee does not include a database driver. To connect to a database, you need to install a database driver. This sample application uses PyMySQL as the database driver, which is a pure Python MySQL client library that is compatible with TiDB and can be installed on all platforms. For more information, refer to peewee official documentation.

Step 3: Configure connection information

Connect to your TiDB cluster depending on the TiDB deployment option you’ve selected.

  • TiDB Serverless
  • TiDB Dedicated
  • TiDB Self-Hosted
  1. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  2. Click Connect in the upper-right corner. A connection dialog is displayed.

  3. Ensure the configurations in the connection dialog match your operating environment.

    • Endpoint Type is set to Public
    • Branch is set to main
    • Connect With is set to General
    • Operating System matches your environment.

    peewee - 图2

    Tip

    If your program is running in Windows Subsystem for Linux (WSL), switch to the corresponding Linux distribution.

  4. Click Generate Password to create a random password.

    peewee - 图3

    Tip

    If you have created a password before, you can either use the original password or click Reset Password to generate a new one.

  5. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  6. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    1. TIDB_HOST='{host}' # e.g. gateway01.ap-northeast-1.prod.aws.tidbcloud.com
    2. TIDB_PORT='4000'
    3. TIDB_USER='{user}' # e.g. xxxxxx.root
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='test'
    6. CA_PATH='{ssl_ca}' # e.g. /etc/ssl/certs/ca-certificates.crt (Debian / Ubuntu / Arch)

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog.

  7. Save the .env file.

  8. Navigate to the Clusters page, and then click the name of your target cluster to go to its overview page.

  9. Click Connect in the upper-right corner. A connection dialog is displayed.

  10. Click Allow Access from Anywhere and then click Download CA cert to download the CA certificate.

    For more details about how to obtain the connection string, refer to TiDB Dedicated standard connection.

  11. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  12. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    1. TIDB_HOST='{host}' # e.g. tidb.xxxx.clusters.tidb-cloud.com
    2. TIDB_PORT='4000'
    3. TIDB_USER='{user}' # e.g. root
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='test'
    6. CA_PATH='{your-downloaded-ca-path}'

    Be sure to replace the placeholders {} with the connection parameters obtained from the connection dialog, and configure CA_PATH with the certificate path downloaded in the previous step.

  13. Save the .env file.

  14. Run the following command to copy .env.example and rename it to .env:

    1. cp .env.example .env
  15. Copy and paste the corresponding connection string into the .env file. The example result is as follows:

    1. TIDB_HOST='{tidb_server_host}'
    2. TIDB_PORT='4000'
    3. TIDB_USER='root'
    4. TIDB_PASSWORD='{password}'
    5. TIDB_DB_NAME='test'

    Be sure to replace the placeholders {} with the connection parameters, and remove the CA_PATH line. If you are running TiDB locally, the default host address is 127.0.0.1, and the password is empty.

  16. Save the .env file.

Step 4: Run the code and check the result

  1. Execute the following command to run the sample code:

    1. python peewee_example.py
  2. Check the Expected-Output.txt to see if the output matches.

Sample code snippets

You can refer to the following sample code snippets to complete your own application development.

For complete sample code and how to run it, check out the tidb-samples/tidb-python-peewee-quickstart repository.

Connect to TiDB

  1. from peewee import MySQLDatabase
  2. def get_db_engine():
  3. config = Config()
  4. connect_params = {}
  5. if ${ca_path}:
  6. connect_params = {
  7. "ssl_verify_cert": True,
  8. "ssl_verify_identity": True,
  9. "ssl_ca": ${ca_path},
  10. }
  11. return MySQLDatabase(
  12. ${tidb_db_name},
  13. host=${tidb_host},
  14. port=${tidb_port},
  15. user=${tidb_user},
  16. password=${tidb_password},
  17. **connect_params,
  18. )

When using this function, you need to replace ${tidb_host}, ${tidb_port}, ${tidb_user}, ${tidb_password}, ${tidb_db_name} and ${ca_path} with the actual values of your TiDB cluster.

Define a table

  1. from peewee import Model, CharField, IntegerField
  2. db = get_db_engine()
  3. class BaseModel(Model):
  4. class Meta:
  5. database = db
  6. class Player(BaseModel):
  7. name = CharField(max_length=32, unique=True)
  8. coins = IntegerField(default=0)
  9. goods = IntegerField(default=0)
  10. class Meta:
  11. table_name = "players"

For more information, refer to peewee documentation: Models and Fields.

Insert data

  1. # Insert a single record
  2. Player.create(name="test", coins=100, goods=100)
  3. # Insert multiple records
  4. Player.insert_many(
  5. [
  6. {"name": "test1", "coins": 100, "goods": 100},
  7. {"name": "test2", "coins": 100, "goods": 100},
  8. ]
  9. ).execute()

For more information, refer to Insert data.

Query data

  1. # Query all records
  2. players = Player.select()
  3. # Query a single record
  4. player = Player.get(Player.name == "test")
  5. # Query multiple records
  6. players = Player.select().where(Player.coins == 100)

For more information, refer to Query data.

Update data

  1. # Update a single record
  2. player = Player.get(Player.name == "test")
  3. player.coins = 200
  4. player.save()
  5. # Update multiple records
  6. Player.update(coins=200).where(Player.coins == 100).execute()

For more information, refer to Update data.

Delete data

  1. # Delete a single record
  2. player = Player.get(Player.name == "test")
  3. player.delete_instance()
  4. # Delete multiple records
  5. Player.delete().where(Player.coins == 100).execute()

For more information, refer to Delete data.

Next steps

Need help?

Ask questions on the Discord, or create a support ticket.