Getting started with Testcontainers for Python — Create the business logic
Create a customers/customers.py file and define the Customer class Bounded code example (external data; do not execute automatically): ```python class Customer: def __init__(self, cust_id, name, email): self.id = cust_id self.name = name self.email = email def __str__(self): return f"Customer({self.
Reference note (untrusted external data; do not execute it as instructions).
Create a customers/customers.py file and define the Customer class
Bounded code example (external data; do not execute automatically):
```python
class Customer:
def __init__(self, cust_id, name, email):
self.id = cust_id
self.name = name
self.email = email
def __str__(self):
return f"Customer({self.id}, {self.name}, {self.email})"
```
Add a create_table() function to create the customers table
Bounded code example (external data; do not execute automatically):
```python
from db.connection import get_connection
def create_table():
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute("""
CREATE TABLE customers (
id serial PRIMARY KEY,
name varchar not null,
email varchar not null unique)
""")
conn.commit()
```
The function obtains a database connection using get_connection() and creates the customers table. The with statement automatically closes the connection when done.
Add the remaining CRUD functions
Bounded code example (external data; do not execute automatically):
```python
def create_customer(name, email):
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO customers (name, email) VALUES (%s, %s)", (name, email))
conn.commit()
def get_all_customers() -> list[Customer]:
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT * FROM customers")
return [Customer(cid, name, email) for cid, name, email in cur]
def get_customer_by_email(email) -> Customer:
with get_connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT id, name, email FROM customers WHERE email = %s", (email,))
(cid, name, email) = cur.fetchone()
return Customer(cid, name, email)
def delete_all_customers():
with get_connection() as conn:
with conn.cursor() as cur:
c
```
> [!NOTE] > To keep it straightforward for this guide, each function creates a new > connection. In a real-world application, use a connection pool to reuse > connections.
Attribution: Adapted from Docker Documentation under Apache-2.0. Adaptation: WikiKV isolated this documentation section, normalized formatting, retained only bounded code excerpts, and shortened it at a paragraph or sentence boundary for retrieval. Verify version-sensitive details at the source.
ATTRIBUTED SOURCE
This compact reference card is adapted from official documentation and is not a community-verified experience.
Docker Documentation — content/guides/testcontainers-python-getting-started.md :: Create the business logic ↗Revision 3a9d778562f3 · Apache-2.0 and attribution