惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MongoDB | Blog
MongoDB | Blog
宝玉的分享
宝玉的分享
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
罗磊的独立博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
博客园 - 聂微东
博客园 - 司徒正美
博客园 - 叶小钗
T
Tailwind CSS Blog
博客园 - Franky
V
V2EX
有赞技术团队
有赞技术团队
美团技术团队
雷峰网
雷峰网
爱范儿
爱范儿
Jina AI
Jina AI
D
DataBreaches.Net
H
Help Net Security
酷 壳 – CoolShell
酷 壳 – CoolShell

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Python E-Commerce Automation: Process Orders, Update Inve...
Brad · 2026-05-14 · via DEV Community

Brad

Running an online store manually means spending hours on order processing, inventory checks, and customer emails. Here's how to automate the entire backend with Python.

The E-Commerce Automation Stack

These four scripts handle 80% of repetitive e-commerce work:

  1. Order processing pipeline
  2. Inventory level monitoring
  3. Automated customer emails
  4. Daily sales reporting

1. Order Processing Pipeline

Connect to your store's API (Shopify, WooCommerce, or direct DB):

import httpx
from datetime import datetime

SHOPIFY_STORE = "your-store.myshopify.com"
SHOPIFY_TOKEN = "your-access-token"

def get_new_orders(since_hours=2):
    """Fetch orders from the last N hours."""
    resp = httpx.get(
        f"https://{SHOPIFY_STORE}/admin/api/2024-01/orders.json",
        headers={"X-Shopify-Access-Token": SHOPIFY_TOKEN},
        params={
            "status": "open",
            "financial_status": "paid",
            "limit": 50
        }
    )
    return resp.json().get('orders', [])

def process_order(order):
    """Extract key info and route to fulfillment."""
    return {
        'id': order['id'],
        'email': order['email'],
        'name': order['shipping_address']['name'],
        'items': [
            {'sku': item['sku'], 'qty': item['quantity'], 'title': item['title']}
            for item in order['line_items']
        ],
        'total': float(order['total_price']),
        'address': order['shipping_address']
    }

Enter fullscreen mode Exit fullscreen mode

2. Inventory Monitoring

Never run out of stock again:

def check_inventory_levels():
    """Check all SKUs against reorder thresholds."""
    resp = httpx.get(
        f"https://{SHOPIFY_STORE}/admin/api/2024-01/inventory_levels.json",
        headers={"X-Shopify-Access-Token": SHOPIFY_TOKEN},
        params={"limit": 250}
    )

    inventory = resp.json().get('inventory_levels', [])
    low_stock = []
    REORDER_THRESHOLD = 10

    for item in inventory:
        available = item.get('available', 0)
        if available < REORDER_THRESHOLD and available >= 0:
            low_stock.append({
                'inventory_item_id': item.get('inventory_item_id'),
                'available': available,
                'threshold': REORDER_THRESHOLD
            })

    return low_stock

Enter fullscreen mode Exit fullscreen mode

3. Automated Customer Emails

The sequence that increases repeat purchases:

import smtplib
from email.mime.text import MIMEText

EMAIL_TEMPLATES = {
    'order_confirmed': """Hi {name},

Your order #{order_id} has been confirmed!

Items ordered:
{items_list}

Total: ${total:.2f}

We'll send tracking info once your order ships (usually 1-2 business days).

Thanks for your business!""",

    'shipped': """Hi {name},

Great news - your order #{order_id} has shipped!

Tracking number: {tracking_number}
Carrier: {carrier}
Expected delivery: {delivery_estimate}""",

    'review_request': """Hi {name},

Hope you love your recent purchase!

Could you take 30 seconds to leave a review? It helps other customers make decisions.

Leave a review: {review_url}

Thanks in advance!"""
}

def send_order_email(template_name, order_data, smtp_config):
    """Send a templated email for an order event."""
    template = EMAIL_TEMPLATES[template_name]

    items_text = '\n'.join([
        f"  - {item['title']} x{item['qty']}"
        for item in order_data.get('items', [])
    ])

    body = template.format(
        name=order_data['name'].split()[0],
        order_id=order_data['id'],
        items_list=items_text,
        total=order_data.get('total', 0),
        **order_data.get('extra', {})
    )

    msg = MIMEText(body)
    msg['Subject'] = f"Your order #{order_data['id']}"
    msg['From'] = smtp_config['from']
    msg['To'] = order_data['email']

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
        server.login(smtp_config['from'], smtp_config['password'])
        server.send_message(msg)

Enter fullscreen mode Exit fullscreen mode

4. Daily Sales Report

Get your business metrics every morning:

from datetime import datetime, timedelta

def generate_daily_report():
    """Pull yesterday's data and build a summary."""
    yesterday = (datetime.utcnow() - timedelta(days=1)).date().isoformat()

    resp = httpx.get(
        f"https://{SHOPIFY_STORE}/admin/api/2024-01/orders.json",
        headers={"X-Shopify-Access-Token": SHOPIFY_TOKEN},
        params={
            "created_at_min": f"{yesterday}T00:00:00Z",
            "created_at_max": f"{yesterday}T23:59:59Z",
            "financial_status": "paid",
            "limit": 250
        }
    )

    orders = resp.json().get('orders', [])
    total_revenue = sum(float(o['total_price']) for o in orders)
    total_orders = len(orders)
    avg_order = total_revenue / total_orders if total_orders > 0 else 0

    report = f"""Daily Sales - {yesterday}

Orders: {total_orders}
Revenue: ${total_revenue:,.2f}
Avg Order Value: ${avg_order:,.2f}
"""
    print(report)
    return report

Enter fullscreen mode Exit fullscreen mode

The Full Automation Loop

def run_ecommerce_automation():
    """Main loop - run every 30 minutes via cron."""
    print(f"[{datetime.now().strftime('%H:%M')}] Running e-commerce automation...")

    # Process new orders
    new_orders = get_new_orders(since_hours=1)
    for order in new_orders:
        processed = process_order(order)
        send_order_email('order_confirmed', processed, smtp_config)
        print(f"  Processed order #{processed['id']} for {processed['name']}")

    # Check inventory
    low_stock = check_inventory_levels()
    if low_stock:
        print(f"  WARNING: {len(low_stock)} items low on stock")

    print(f"  Done: {len(new_orders)} orders processed")

if __name__ == '__main__':
    run_ecommerce_automation()

Enter fullscreen mode Exit fullscreen mode

Cron Schedule

# Run every 30 minutes
*/30 * * * * /usr/bin/python3 /path/to/ecommerce_automation.py

# Daily report at 7am
0 7 * * * /usr/bin/python3 /path/to/daily_report.py

Enter fullscreen mode Exit fullscreen mode

This entire automation system — plus 20 more business scripts — is available as a ready-to-run toolkit: https://lukassbrad.gumroad.com/l/ugeka


What's the biggest time drain in your e-commerce operations? Share in the comments.