For those new to Python web development, does the thought of database operations make you feel overwhelmed? You just want to store some data or query some information, but you first have to learn complex SQL syntax and deal with various configurations? Today, I recommend a super user-friendly Python library—Orator. Using it to operate databases is as simple as building with blocks, making it easy for beginners to get started quickly!
Why Recommend Orator? Understand the Problems It Solves
In development, databases are an unavoidable aspect. While SQLAlchemy is often mentioned for its power, its configuration steps are numerous and its concepts complex, which can discourage beginners. Orator, on the other hand, employs a design pattern called “ActiveRecord”—each database table corresponds to a Python class (model), allowing you to manipulate data directly by calling methods on the class without needing to remember complex SQL statements.
For example, if we consider a database table as a “contact list,” the Orator model acts like a “management app” for that contact list. To add a contact (create data), find a contact (query data), or change a number (update data), you simply click the buttons on the app (call methods) without writing any “low-level code” yourself.
Moreover, Orator comes with many practical features: it automatically records data creation/update times, supports multiple databases (MySQL, PostgreSQL, SQLite), and can easily manage database structure versions, making it very beginner-friendly!
Step 1: Install Orator in 5 Minutes, Super Easy
Installing Orator only requires using pip, but note that Orator itself does not include database drivers; you need to install the driver according to the database you are using. Follow the steps below to ensure you don’t make mistakes!
1. Install the Core Library
Open the command line (CMD or PowerShell for Windows, terminal for Mac/Linux) and enter the following command to install the core functionality of Orator:
pip install orator
2. Install the Corresponding Database Driver
Choose one command to install based on the database you are using; you don’t need to install all:
- • If using PostgreSQL:
<span>pip install psycopg2</span> - • If using MySQL: just choose one of the following
<span>pip install PyMySQL</span>(recommended for beginners, good compatibility) or<span>pip install mysqlclient</span> - • If using SQLite: no installation needed! It comes with Python, just use it directly
3. Verify Installation: Ensure It Works Properly
After installation, write a few lines of code to test it. Create a new Python file (e.g., test_orator.py), copy the code below into it, and run it:
# Import necessary tools from Orator
from orator import DatabaseManager, Model
# Configure the database (using SQLite here, no extra driver installation needed for easy testing)
config = {
'sqlite': {
'driver': 'sqlite', # Database type
'database': ':memory:' # Use in-memory database, very convenient for testing
}
}
# Create a database manager
db = DatabaseManager(config)
# Let the model know which database to use
Model.set_connection_resolver(db)
# If no errors, it means the installation was successful
print("Orator installed successfully! You can start using it now~")
If you see the message “Orator installed successfully” without any red error messages, then everything is fine!
Beginner’s Guide: 3 Core Operations to Meet Basic Database Needs
The core of Orator is the “model”—using Python classes to correspond to database tables. By learning to define models, perform CRUD (Create, Read, Update, Delete) operations, and execute simple queries, you can handle most basic scenarios.
1. Define a Model: Create a “Management Class” for the Database Table
First, understand a rule: Orator defaults to using the “plural form of the model class name” as the database table name. For example, the <span>User</span> class corresponds to the <span>users</span> table, and the <span>Post</span> class corresponds to the <span>posts</span> table, so beginners do not need to manually configure table names, which is convenient!
Next, let’s use the “users table (users)” and “posts table (posts)” as examples to teach you how to define models:
from orator import DatabaseManager, Model
# 1. First configure the database (this time using MySQL as an example, beginners should change the parameters to their own)
config = {
'mysql': {
'driver': 'mysql',
'host': 'localhost', # Database address, usually localhost for local
'database': 'blog_db', # Your database name (must be created first)
'user': 'root', # Database username, usually root for beginners
'password': '123456', # Your database password
'prefix': '' # Table prefix, beginners can leave it empty
}
}
# 2. Initialize the database
db = DatabaseManager(config)
Model.set_connection_resolver(db)
# 3. Define the User model (corresponding to the users table)
class User(Model):
# __fillable: specify which fields can be mass assigned (e.g., passing name, email when adding a user)
__fillable__ = ['name', 'email', 'password']
# 4. Define the Post model (corresponding to the posts table)
class Post(Model):
__fillable__ = ['title', 'content', 'user_id'] # user_id relates to the users table
print("Model definition complete! You can now operate on the users and posts tables~")
2. CRUD Operations: Create, Read, Update, Delete in One Go
Once you learn to define models, performing CRUD operations is as simple as calling regular functions without writing SQL!
(1) Create Data (Create)
There are two methods, and I recommend the second method <span>create</span>, which is more concise:
# Method 1: Create an instance first, then assign values and save
user1 = User()
user1.name = 'Zhang San'
user1.email = '[email protected]'
user1.password = '123456' # Note: In actual projects, passwords should be encrypted; this is just an example
user1.save() # Save to the database
# Method 2: Use create to directly pass a dictionary, one step (recommended)
user2 = User.create({
'name': 'Li Si',
'email': '[email protected]',
'password': '654321'
})
print("Added successfully! Zhang San's ID is:", user1.id)
print("Added successfully! Li Si's ID is:", user2.id)
(2) Read Data (Read)
Common query methods are organized for you; just copy the code and modify it:
# 1. Query all users
all_users = User.all()
print("All users:", [user.name for user in all_users]) # Print all usernames
# 2. Find a single user by ID (most common)
user = User.find(1) # Find user with ID=1
if user:
print("User with ID=1:", user.name, user.email)
# 3. Query by condition (e.g., find user with email [email protected])
user_zhangsan = User.where('email', '[email protected]').first()
if user_zhangsan:
print("Found Zhang San:", user_zhangsan.name)
# 4. Count (e.g., count how many users there are)
user_count = User.count()
print("Total number of users:", user_count)
(3) Update Data (Update)
Updating data is also simple; find the user to be modified, make changes, and save:
# Method 1: Update a single user
user = User.find(1) # Find user with ID=1
if user:
user.name = 'Zhang San Updated' # Change name
user.save() # Save changes
print("Update successful! New name is:", user.name)
# Method 2: Batch update (e.g., change status of users with ID>10 to active)
# User.where('id', '>', 10).update({'status': 'active'})
(4) Delete Data (Delete)
Be cautious! Data may be irretrievable after deletion; it is recommended to query first before deleting:
# Method 1: Delete a single user
user = User.find(2) # Find user with ID=2
if user:
user.delete()
print("Delete successful! Total number of users now:", User.count())
# Method 2: Batch delete (e.g., delete users with status inactive)
# User.where('status', 'inactive').delete()
3. Simple Queries: Filter Data by Conditions
In actual development, it is often necessary to query data by conditions (e.g., find “active users in Beijing” or “users registered after 2023”). Orator’s “query builder” allows you to write conditions in a chain-like manner, making it very intuitive.
Here are a few common examples that beginners can directly use as templates:
# 1. Find users with status "active"
active_users = User.where('status', 'active').get()
print("Number of active users:", len(active_users))
# 2. Find users with "age>18 and city is Beijing or Shanghai", ordered by creation time in descending order, limit to 10
users = User.where('age', '>', 18) \
.where('city', 'Beijing') \
.or_where('city', 'Shanghai') \
.order_by('created_at', 'desc') \
.limit(10) \
.get()
print("Number of users meeting the criteria:", len(users))
# 3. Fuzzy query (find users with names containing "Zhang")
search_users = User.where('name', 'like', '%Zhang%').get()
print("Users with 'Zhang' in their names:", [user.name for user in search_users])
# 4. Paginated query (e.g., page 2, 10 items per page)
page2_users = User.order_by('created_at', 'desc') \
.skip(10) # Skip the first 10 items (page 1)
.take(10) # Take 10 items (page 2)
.get()
print("Number of users on page 2:", len(page2_users))
Advanced Tips: High-Level Features Understandable by Beginners
Once you master the basic operations, learn two practical features to make your code more professional.
1. Model Relationships: Easily Associate Multiple Tables
For example, “a user can write multiple articles” (one-to-many relationship). After defining relationships with Orator, querying a user’s articles or an article’s author becomes very convenient without writing SQL for associations.
from orator.orm import has_many, belongs_to
# 1. User model (one-to-many: one user has multiple articles)
class User(Model):
__fillable__ = ['name', 'email']
# Use @has_many to define the "has many" relationship, returning the Post model
@has_many
def posts(self):
return Post
# 2. Post model (many-to-one: multiple articles belong to one user)
class Post(Model):
__fillable__ = ['title', 'content', 'user_id']
# Use @belongs_to to define the "belongs to" relationship, returning the User model, named author here
@belongs_to
def author(self):
return User
# 3. How to use? Super simple!
# Find all articles written by the user with ID=1
user = User.find(1)
user_posts = user.posts # Directly call posts() method (no parentheses needed)
print(f"{user.name} wrote {len(user_posts)} articles")
# Find the author of the article with ID=5
post = Post.find(5)
post_author = post.author
print(f"The author of the article '{post.title}' is: {post_author.name}")
2. Automatic Password Hashing: Protect User Data
User passwords should not be stored in plain text in the database. Orator’s “model events” can help you automatically encrypt passwords without having to handle it manually each time.
class User(Model):
__fillable__ = ['name', 'email', 'password']
# Register events when initializing the model
@staticmethod
def boot():
# Automatically hash password when creating or updating a user
User.creating(User.hash_password) # Triggered before creating
User.updating(User.hash_password) # Triggered before updating
# Method to hash passwords
@staticmethod
def hash_password(user):
# Check if there is a password field and if the password is not empty
if hasattr(user, 'password') and user.password:
import hashlib
# Use SHA256 for encryption (in actual projects, it is recommended to use a more secure method like bcrypt; this is just a simple example)
user.password = hashlib.sha256(user.password.encode()).hexdigest()
# Test: When adding a user, the password will be automatically encrypted
user = User.create({
'name': 'Test User',
'email': '[email protected]',
'password': '123456' # Plain text password
})
# View the encrypted password (the database stores the encrypted string, not 123456)
print("Encrypted password:", user.password)
Conclusion: Who is Orator Suitable For?
If you are a beginner in Python web development and do not want to spend too much time learning complex ORM frameworks while wanting to elegantly operate databases, Orator is definitely a good choice. Its advantages are clear:
- • Simple syntax, operate databases like writing regular Python code
- • No need to remember SQL, chain calls are intuitive and easy to understand
- • Comes with many practical features (automatic timestamps, relationship mapping, data serialization)
- • Supports multiple databases, switching databases requires minimal code changes
Of course, Orator is not omnipotent—if you are working on a super large project, you may need some advanced features of SQLAlchemy. But for beginners and small to medium-sized projects, Orator is more than sufficient!
So get started and try it out! Write a database operation with Orator, and you will find that operating databases can be this simple~