Skip to main content

Flask Integration

dkmio is framework-agnostic and easy to integrate into existing Flask applications. There are two main patterns depending on whether you are starting a new project or integrating into one that already uses boto3.

Let dkmio manage the connection entirely. This is the cleanest approach for new applications.

from flask import Flask
from dkmio import DynamoDB, PK

app = Flask(__name__)

# Initialize DynamoDB
db = DynamoDB(region_name="us-east-1")

# Define your Table
class Users(db.Table):
__table_name__ = "Users"
pk = PK("id")

# Create an instance
users = Users()

@app.route('/user/<user_id>')
def get_user(user_id):
# Returns the item as a dict or {} if not found
return users.get(id=user_id) or {}

Pattern 2: Existing Projects with Boto3

If your Flask app already initializes a boto3.resource, you can wrap it with dkmio without changing your existing setup.

Option A: DynamoDB(resource=) Wrapper

import boto3
from flask import Flask
from dkmio import DynamoDB, PK

app = Flask(__name__)

# Your existing boto3 resource
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')

# Wrap it with dkmio
db = DynamoDB(resource=dynamodb)

class Users(db.Table):
__table_name__ = "Users"
pk = PK("id")

Option B: Direct Table(resource=) Binding

If you only want to use dkmio for specific tables, you can bind the resource directly to the table instance.

import boto3
from dkmio import PK
from dkmio.table import Table

# Your existing boto3 resource
dynamodb = boto3.resource('dynamodb')

class Users(Table):
__table_name__ = "Users"
pk = PK("id")

# Bind resource at instantiation
users = Users(resource=dynamodb)

Tips for Production

  • Singletons: It's best practice to initialize your DynamoDB and Table instances outside of the request context (at the module level) so they can be reused across requests.
  • Error Handling: Use dkmio's structured exceptions to return appropriate HTTP status codes (e.g., 404 for TableNotFoundError, 409 for ConditionError).