# Blog Routes Quick Fix Guide

## Issues to Fix in blog_routes.py

### 1. Fix get_categories function (around line 621-652)

**Problem**: The function has the error return before the success return, and has duplicate finally blocks.

**Replace lines 621-652 with:**

```python
@blog_bp.route('/api/blogs/categories', methods=['GET'])
@require_api_key
@encrypt_response
def get_categories():
    """Get all blog categories from database"""
    try:
        # Log the request
        logger.info(f"GET /api/blogs/categories - IP: {request.remote_addr}")
        
        # Create database connection directly
        from database import get_cached_connection
        conn = get_cached_connection()
        cursor = None
        try:
            cursor = conn.cursor(dictionary=True)
            
            # Query to fetch all categories
            query = "SELECT id, name FROM blog_categories ORDER BY name"
            cursor.execute(query)
            categories = cursor.fetchall()
        finally:
            # Always clean up resources
            if cursor and hasattr(cursor, 'close'):
                cursor.close()
            if conn and hasattr(conn, 'close'):
                conn.close()
        
        # Log successful response
        logger.info(f"GET /api/blogs/categories - Success: {len(categories)} categories returned")
        
        # Return raw data - let the @encrypt_response decorator handle Response creation
        return format_api_response(
            data={'categories': categories},
            message="Categories retrieved successfully",
            include_legacy_fields=True  # FIXED: was `categories`, should be True
        )
    except Exception as e:
        logger.error("Error fetching blog categories: {}".format(str(e)))
        logger.error(f"GET /api/blogs/categories - Error: {str(e)}, IP: {request.remote_addr}")
        return create_error_response(str(e), status_code=500, encrypt=True)
```

### 2. Look for get_popular_tags function (should be around line 663)

Change the return statement to use `include_legacy_fields=True` instead of `include_legacy_fields=popular_tags`

### 3. Look for get_trending_posts function (should be around line 710+)

Change the return statement to use `include_legacy_fields=True` instead of `include_legacy_fields=trending_posts`

## Quick Search & Replace

If your editor supports it:

1. Find: `include_legacy_fields=categories`
   Replace with: `include_legacy_fields=True`

2. Find: `include_legacy_fields=popular_tags`
   Replace with: `include_legacy_fields=True`

3. Find: `include_legacy_fields=trending_posts`
   Replace with: `include_legacy_fields=True`

## Why This Fix?

The `include_legacy_fields` parameter expects a **boolean** (True/False), not the actual data array.

When you pass an array, it tries to use dict() on it which causes:
- "dictionary update sequence element #0 has length 19; 2 is required" error
- "Cannot encrypt non-Response object" warning

Setting it to `True` makes `format_api_response` copy the data to legacy_data automatically.
