Quick Start

Get up and running with Akron ORM in minutes. Build your first database application with this step-by-step guide.

Your First Akron Application

In this quick start guide, you'll build a simple blog application using Akron ORM. We'll cover database setup, table creation, and basic CRUD operations.

šŸŽÆ What You'll Build

  • • A simple blog application with users and posts
  • • Database tables with proper relationships
  • • CRUD operations for managing data
  • • Both Python API and CLI examples

Step 1: Project Setup

Create Project Directory

First, let's create a new directory for our blog application:

Project Setup
1# Create project directory
2mkdir blog_app
3cd blog_app
4
5# Create a virtual environment (recommended)
6python -m venv venv
7
8# Activate virtual environment
9# Windows:
10venv\Scripts\activate
11# macOS/Linux:
12source venv/bin/activate
13
14# Install Akron
15pip install akron
16
17# Create main application file
18touch blog_app.py
19
20# Verify installation
21python -c "import akron; print('Akron ready!')"
Expected Output
Akron ready!

Step 2: Define Your Models

Create Data Models

Create blog_app.py and define your data models using Pydantic:

blog_app.py - Data Models
1from akron import Akron
2from pydantic import BaseModel, EmailStr
3from akron.models import ModelMixin
4from datetime import datetime
5from typing import Optional
6
7# Define User model
8class User(BaseModel, ModelMixin):
9 id: int
10 username: str
11 email: str
12 full_name: Optional[str] = None
13 is_active: bool = True
14 created_at: datetime
15
16# Define Post model
17class Post(BaseModel, ModelMixin):
18 id: int
19 title: str
20 content: str
21 author_id: int # Foreign key to User.id
22 published: bool = False
23 created_at: datetime
24 updated_at: Optional[datetime] = None
25
26# Initialize database connection
27def create_database():
28 """Create database and tables"""
29 # Using SQLite for this example (no server required)
30 db = Akron("sqlite:///blog.db")
31
32 # Create tables
33 print("Creating database tables...")
34 User.create_table(db)
35 Post.create_table(db)
36
37 print("āœ“ Database tables created successfully!")
38 return db
39
40if __name__ == "__main__":
41 db = create_database()
42 print("Blog application initialized!")

Run the script to create your database:

1python blog_app.py
Expected Output
Creating database tables...
āœ“ Database tables created successfully!
Blog application initialized!

Step 3: Add Sample Data

Insert Users and Posts

Let's add some sample data to our blog application:

Add to blog_app.py - Sample Data
1def seed_data(db):
2 """Add sample users and posts"""
3 print("Adding sample data...")
4
5 # Create sample users
6 alice = User(
7 id=1,
8 username="alice",
9 email="alice@example.com",
10 full_name="Alice Johnson",
11 created_at=datetime.now()
12 )
13
14 bob = User(
15 id=2,
16 username="bob",
17 email="bob@example.com",
18 full_name="Bob Smith",
19 created_at=datetime.now()
20 )
21
22 # Insert users
23 User.insert(db, alice)
24 User.insert(db, bob)
25 print("āœ“ Users created")
26
27 # Create sample posts
28 post1 = Post(
29 id=1,
30 title="Welcome to My Blog",
31 content="This is my first post using Akron ORM! It's amazing how easy it is to work with databases.",
32 author_id=1, # Alice's post
33 published=True,
34 created_at=datetime.now()
35 )
36
37 post2 = Post(
38 id=2,
39 title="Database Magic with Akron",
40 content="Akron ORM makes database operations so simple. No more complex SQL queries!",
41 author_id=2, # Bob's post
42 published=True,
43 created_at=datetime.now()
44 )
45
46 post3 = Post(
47 id=3,
48 title="Draft Post",
49 content="This post is still being written...",
50 author_id=1, # Alice's draft
51 published=False,
52 created_at=datetime.now()
53 )
54
55 # Insert posts
56 Post.insert(db, post1)
57 Post.insert(db, post2)
58 Post.insert(db, post3)
59 print("āœ“ Posts created")
60
61 print("Sample data added successfully!")
62
63# Update the main section
64if __name__ == "__main__":
65 db = create_database()
66 seed_data(db)
67 print("\nBlog application ready!")

Run the updated script:

1python blog_app.py
Expected Output
Creating database tables...
āœ“ Database tables created successfully!
Adding sample data...
āœ“ Users created
āœ“ Posts created
Sample data added successfully!

Blog application ready!

Step 4: Query and Display Data

Read Operations

Now let's add functions to query and display our blog data:

Add to blog_app.py - Query Functions
1def display_blog_stats(db):
2 """Display blog statistics"""
3 print("\n" + "="*50)
4 print("BLOG STATISTICS")
5 print("="*50)
6
7 # Count total users
8 all_users = User.select(db)
9 print(f"Total Users: {len(all_users)}")
10
11 # Count total posts
12 all_posts = Post.select(db)
13 print(f"Total Posts: {len(all_posts)}")
14
15 # Count published posts
16 published_posts = Post.select(db, where={"published": True})
17 print(f"Published Posts: {len(published_posts)}")
18
19 # Count draft posts
20 draft_posts = Post.select(db, where={"published": False})
21 print(f"Draft Posts: {len(draft_posts)}")
22
23def display_users(db):
24 """Display all users"""
25 print("\n" + "="*50)
26 print("USERS")
27 print("="*50)
28
29 users = User.select(db)
30 for user in users:
31 status = "Active" if user.is_active else "Inactive"
32 print(f"[{user.id}] {user.username} ({user.full_name})")
33 print(f" Email: {user.email}")
34 print(f" Status: {status}")
35 print(f" Joined: {user.created_at.strftime('%Y-%m-%d')}")
36 print()
37
38def display_posts(db, published_only=False):
39 """Display posts"""
40 title = "PUBLISHED POSTS" if published_only else "ALL POSTS"
41 print("\n" + "="*50)
42 print(title)
43 print("="*50)
44
45 if published_only:
46 posts = Post.select(db, where={"published": True})
47 else:
48 posts = Post.select(db)
49
50 for post in posts:
51 # Get author information
52 author = User.find(db, {"id": post.author_id})
53 author_name = author.username if author else "Unknown"
54
55 status = "āœ“ Published" if post.published else "āœ Draft"
56 print(f"[{post.id}] {post.title}")
57 print(f" Author: {author_name}")
58 print(f" Status: {status}")
59 print(f" Created: {post.created_at.strftime('%Y-%m-%d %H:%M')}")
60 print(f" Content: {post.content[:100]}{'...' if len(post.content) > 100 else ''}")
61 print()
62
63def search_posts(db, keyword):
64 """Search posts by keyword in title or content"""
65 print(f"\n" + "="*50)
66 print(f"SEARCH RESULTS FOR: '{keyword}'")
67 print("="*50)
68
69 all_posts = Post.select(db)
70 matching_posts = [
71 post for post in all_posts
72 if keyword.lower() in post.title.lower() or keyword.lower() in post.content.lower()
73 ]
74
75 if matching_posts:
76 for post in matching_posts:
77 author = User.find(db, {"id": post.author_id})
78 author_name = author.username if author else "Unknown"
79 print(f"[{post.id}] {post.title} by {author_name}")
80 print(f" {post.content[:150]}{'...' if len(post.content) > 150 else ''}")
81 print()
82 else:
83 print("No posts found matching your search.")
84
85# Update the main section
86if __name__ == "__main__":
87 db = create_database()
88 seed_data(db)
89
90 # Display blog data
91 display_blog_stats(db)
92 display_users(db)
93 display_posts(db, published_only=True)
94 search_posts(db, "Akron")
95
96 print("\nBlog application demo complete!")

Run the complete application:

1python blog_app.py
Expected Output
Creating database tables...
āœ“ Database tables created successfully!
Adding sample data...
āœ“ Users created
āœ“ Posts created
Sample data added successfully!

==================================================
BLOG STATISTICS
==================================================
Total Users: 2
Total Posts: 3
Published Posts: 2
Draft Posts: 1

==================================================
USERS
==================================================
[1] alice (Alice Johnson)
    Email: alice@example.com
    Status: Active
    Joined: 2024-01-15

[2] bob (Bob Smith)
    Email: bob@example.com
    Status: Active
    Joined: 2024-01-15

==================================================
PUBLISHED POSTS
==================================================
[1] Welcome to My Blog
    Author: alice
    Status: āœ“ Published
    Created: 2024-01-15 10:30
    Content: This is my first post using Akron ORM! It's amazing how easy it is to work with databases.

[2] Database Magic with Akron
    Author: bob
    Status: āœ“ Published
    Created: 2024-01-15 10:30
    Content: Akron ORM makes database operations so simple. No more complex SQL queries!

==================================================
SEARCH RESULTS FOR: 'Akron'
==================================================
[1] Welcome to My Blog by alice
    This is my first post using Akron ORM! It's amazing how easy it is to work with databases.

[2] Database Magic with Akron by bob
    Akron ORM makes database operations so simple. No more complex SQL queries!

Blog application demo complete!

Step 5: Update and Delete Operations

Modify Your Data

Let's add functions to update and delete blog data:

Add to blog_app.py - Update/Delete Functions
1def update_post(db, post_id, title=None, content=None, published=None):
2 """Update a blog post"""
3 print(f"\nUpdating post {post_id}...")
4
5 # Prepare update data
6 update_data = {"updated_at": datetime.now()}
7 if title:
8 update_data["title"] = title
9 if content:
10 update_data["content"] = content
11 if published is not None:
12 update_data["published"] = published
13
14 # Update the post
15 result = Post.update(db, {"id": post_id}, update_data)
16
17 if result:
18 print(f"āœ“ Post {post_id} updated successfully!")
19
20 # Show updated post
21 updated_post = Post.find(db, {"id": post_id})
22 if updated_post:
23 print(f" Title: {updated_post.title}")
24 print(f" Published: {updated_post.published}")
25 print(f" Updated: {updated_post.updated_at}")
26 else:
27 print(f"āœ— Failed to update post {post_id}")
28
29def publish_draft(db, post_id):
30 """Publish a draft post"""
31 print(f"\nPublishing post {post_id}...")
32
33 post = Post.find(db, {"id": post_id})
34 if not post:
35 print(f"āœ— Post {post_id} not found")
36 return
37
38 if post.published:
39 print(f"Post '{post.title}' is already published")
40 return
41
42 # Publish the post
43 Post.update(db, {"id": post_id}, {
44 "published": True,
45 "updated_at": datetime.now()
46 })
47
48 print(f"āœ“ Post '{post.title}' published successfully!")
49
50def delete_post(db, post_id):
51 """Delete a blog post"""
52 print(f"\nDeleting post {post_id}...")
53
54 # Get post details before deletion
55 post = Post.find(db, {"id": post_id})
56 if not post:
57 print(f"āœ— Post {post_id} not found")
58 return
59
60 # Delete the post
61 result = Post.delete(db, {"id": post_id})
62
63 if result:
64 print(f"āœ“ Post '{post.title}' deleted successfully!")
65 else:
66 print(f"āœ— Failed to delete post {post_id}")
67
68def create_new_post(db, title, content, author_id, published=False):
69 """Create a new blog post"""
70 print(f"\nCreating new post: '{title}'...")
71
72 # Get next available ID
73 all_posts = Post.select(db)
74 next_id = max([post.id for post in all_posts], default=0) + 1
75
76 # Create new post
77 new_post = Post(
78 id=next_id,
79 title=title,
80 content=content,
81 author_id=author_id,
82 published=published,
83 created_at=datetime.now()
84 )
85
86 # Insert the post
87 result = Post.insert(db, new_post)
88
89 if result:
90 print(f"āœ“ Post '{title}' created successfully!")
91 return next_id
92 else:
93 print(f"āœ— Failed to create post '{title}'")
94 return None
95
96# Interactive demo function
97def run_interactive_demo(db):
98 """Run an interactive demo of CRUD operations"""
99 print("\n" + "="*60)
100 print("INTERACTIVE CRUD OPERATIONS DEMO")
101 print("="*60)
102
103 # 1. Create a new post
104 new_post_id = create_new_post(
105 db,
106 title="My Python Journey",
107 content="Learning Python has been an incredible experience. From basic syntax to advanced frameworks like Akron ORM, every step has been exciting!",
108 author_id=1, # Alice
109 published=False # Start as draft
110 )
111
112 # 2. Update the post content
113 if new_post_id:
114 update_post(
115 db,
116 new_post_id,
117 content="Learning Python has been an incredible experience. From basic syntax to advanced frameworks like Akron ORM, every step has been exciting! I particularly love how Akron makes database operations so intuitive.",
118 published=False
119 )
120
121 # 3. Publish the draft
122 if new_post_id:
123 publish_draft(db, new_post_id)
124
125 # 4. Show current stats
126 display_blog_stats(db)
127
128 # 5. Delete the demo post
129 if new_post_id:
130 delete_post(db, new_post_id)
131
132 # 6. Final stats
133 print("\nFinal statistics after cleanup:")
134 display_blog_stats(db)
135
136# Update the main section
137if __name__ == "__main__":
138 db = create_database()
139 seed_data(db)
140
141 # Run basic demo
142 display_blog_stats(db)
143 display_posts(db, published_only=True)
144
145 # Run interactive CRUD demo
146 run_interactive_demo(db)
147
148 print("\n" + "="*60)
149 print("āœ“ Quick Start Demo Complete!")
150 print("="*60)
151 print("Next steps:")
152 print("• Try different database types (MySQL, PostgreSQL, MongoDB)")
153 print("• Explore the CLI commands")
154 print("• Check out the full API documentation")
155 print("• Build your own application!")

Run the complete demo:

1python blog_app.py
Expected Output
Creating database tables...
āœ“ Database tables created successfully!
Adding sample data...
āœ“ Users created
āœ“ Posts created
Sample data added successfully!

==================================================
BLOG STATISTICS
==================================================
Total Users: 2
Total Posts: 3
Published Posts: 2
Draft Posts: 1

============================================================
INTERACTIVE CRUD OPERATIONS DEMO
============================================================

Creating new post: 'My Python Journey'...
āœ“ Post 'My Python Journey' created successfully!

Updating post 4...
āœ“ Post 4 updated successfully!
  Title: My Python Journey
  Published: False
  Updated: 2024-01-15 10:30:45.123456

Publishing post 4...
āœ“ Post 'My Python Journey' published successfully!

==================================================
BLOG STATISTICS
==================================================
Total Users: 2
Total Posts: 4
Published Posts: 3
Draft Posts: 1

Deleting post 4...
āœ“ Post 'My Python Journey' deleted successfully!

Final statistics after cleanup:
==================================================
BLOG STATISTICS
==================================================
Total Users: 2
Total Posts: 3
Published Posts: 2
Draft Posts: 1

============================================================
āœ“ Quick Start Demo Complete!
============================================================
Next steps:
• Try different database types (MySQL, PostgreSQL, MongoDB)
• Explore the CLI commands
• Check out the full API documentation
• Build your own application!

Step 6: Using the CLI

Command-Line Interface

Akron also provides a powerful CLI for database operations. Let's explore some commands:

CLI Examples
1# Inspect your database schema
2akron inspect-schema --db "sqlite:///blog.db"
3
4# Query data using raw SQL
5akron raw-sql --db "sqlite:///blog.db" --query "SELECT * FROM users"
6
7# Add more users via CLI
8akron seed users --db "sqlite:///blog.db" --data '[
9 {
10 "id": 3,
11 "username": "charlie",
12 "email": "charlie@example.com",
13 "full_name": "Charlie Brown",
14 "is_active": true,
15 "created_at": "2024-01-15T10:30:00"
16 }
17]'
18
19# Create a new table via CLI
20akron create-table comments --db "sqlite:///blog.db" --schema '{
21 "id": "int",
22 "post_id": "int",
23 "author_name": "str",
24 "content": "str",
25 "created_at": "str"
26}'
27
28# Verify the new table
29akron inspect-schema --db "sqlite:///blog.db"
Expected Output
Database Schema (SQLite):
=====================================
ā”œā”€ā”€ users
│   ā”œā”€ā”€ id (INTEGER)
│   ā”œā”€ā”€ username (TEXT)
│   ā”œā”€ā”€ email (TEXT)
│   ā”œā”€ā”€ full_name (TEXT)
│   ā”œā”€ā”€ is_active (INTEGER)
│   └── created_at (TEXT)
ā”œā”€ā”€ posts
│   ā”œā”€ā”€ id (INTEGER)
│   ā”œā”€ā”€ title (TEXT)
│   ā”œā”€ā”€ content (TEXT)
│   ā”œā”€ā”€ author_id (INTEGER)
│   ā”œā”€ā”€ published (INTEGER)
│   ā”œā”€ā”€ created_at (TEXT)
│   └── updated_at (TEXT)
└── comments
    ā”œā”€ā”€ id (INTEGER)
    ā”œā”€ā”€ post_id (INTEGER)
    ā”œā”€ā”€ author_name (TEXT)
    ā”œā”€ā”€ content (TEXT)
    └── created_at (TEXT)

āœ“ User added successfully
āœ“ Table 'comments' created successfully

Try Different Databases

Same Code, Different Databases

The beauty of Akron is that you can use the same code with different databases. Just change the connection string:

Database Variations
1# Try with PostgreSQL (if you have it running)
2# db = Akron("postgres://user:password@localhost:5432/blog")
3
4# Try with MySQL (if you have it running)
5# db = Akron("mysql://user:password@localhost:3306/blog")
6
7# Try with MongoDB (if you have it running)
8# db = Akron("mongodb://localhost:27017/blog")
9
10# For production, use environment variables
11import os
12db_url = os.getenv("DATABASE_URL", "sqlite:///blog.db")
13db = Akron(db_url)

šŸ”„ Database Portability

Your models and operations work identically across all databases:

  • • Same Python code for all database types
  • • Automatic type conversion and mapping
  • • Consistent API across SQL and NoSQL databases
  • • Easy migration between database systems

Complete Application Code

Final blog_app.py

Here's the complete code for your blog application:

Complete blog_app.py
1"""
2Simple Blog Application using Akron ORM
3A complete example demonstrating CRUD operations and best practices.
4"""
5
6from akron import Akron
7from pydantic import BaseModel
8from akron.models import ModelMixin
9from datetime import datetime
10from typing import Optional
11import os
12
13# Data Models
14class User(BaseModel, ModelMixin):
15 id: int
16 username: str
17 email: str
18 full_name: Optional[str] = None
19 is_active: bool = True
20 created_at: datetime
21
22class Post(BaseModel, ModelMixin):
23 id: int
24 title: str
25 content: str
26 author_id: int
27 published: bool = False
28 created_at: datetime
29 updated_at: Optional[datetime] = None
30
31def get_database():
32 """Get database connection"""
33 db_url = os.getenv("DATABASE_URL", "sqlite:///blog.db")
34 return Akron(db_url)
35
36def setup_database():
37 """Initialize database and tables"""
38 db = get_database()
39 User.create_table(db)
40 Post.create_table(db)
41 return db
42
43def create_sample_data(db):
44 """Create sample users and posts"""
45 # Add users
46 users = [
47 User(id=1, username="alice", email="alice@example.com",
48 full_name="Alice Johnson", created_at=datetime.now()),
49 User(id=2, username="bob", email="bob@example.com",
50 full_name="Bob Smith", created_at=datetime.now())
51 ]
52
53 for user in users:
54 User.insert(db, user)
55
56 # Add posts
57 posts = [
58 Post(id=1, title="Welcome to Akron",
59 content="Getting started with Akron ORM is super easy!",
60 author_id=1, published=True, created_at=datetime.now()),
61 Post(id=2, title="Database Magic",
62 content="Akron works with SQLite, MySQL, PostgreSQL, and MongoDB!",
63 author_id=2, published=True, created_at=datetime.now()),
64 Post(id=3, title="Work in Progress",
65 content="This post is still being written...",
66 author_id=1, published=False, created_at=datetime.now())
67 ]
68
69 for post in posts:
70 Post.insert(db, post)
71
72def show_blog_summary(db):
73 """Display blog summary"""
74 users = User.select(db)
75 all_posts = Post.select(db)
76 published_posts = Post.select(db, where={"published": True})
77
78 print("\nšŸ  BLOG SUMMARY")
79 print("=" * 40)
80 print(f"Users: {len(users)}")
81 print(f"Total Posts: {len(all_posts)}")
82 print(f"Published: {len(published_posts)}")
83 print(f"Drafts: {len(all_posts) - len(published_posts)}")
84
85 print("\nšŸ“ RECENT POSTS")
86 print("-" * 40)
87 for post in published_posts:
88 author = User.find(db, {"id": post.author_id})
89 print(f"• {post.title} by {author.username if author else 'Unknown'}")
90
91if __name__ == "__main__":
92 print("šŸš€ Akron Blog Application")
93 print("=" * 50)
94
95 # Setup
96 db = setup_database()
97 create_sample_data(db)
98
99 # Demo
100 show_blog_summary(db)
101
102 print("\nāœ… Application ready!")
103 print("\nNext steps:")
104 print("• Modify the code to add your own features")
105 print("• Try different database connections")
106 print("• Explore the Akron CLI commands")
107 print("• Check out the full documentation")

šŸŽ‰ Congratulations!

You've successfully built your first Akron application! You now know how to:

āœ… What You've Learned

  • • Install and configure Akron ORM
  • • Define data models with Pydantic
  • • Create database tables
  • • Perform CRUD operations
  • • Use both Python API and CLI
  • • Handle relationships between tables

šŸŽÆ Key Concepts

  • • Universal database connectivity
  • • Type-safe model definitions
  • • Consistent API across databases
  • • Automatic schema management
  • • Easy data validation
  • • Simple migration handling

Next Steps