|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). |
| 4 | +# You may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +Django ORM Failover Example with AWS Advanced Python Driver |
| 17 | +
|
| 18 | +This example demonstrates how to handle failover events when using Django ORM |
| 19 | +with the AWS Advanced Python Driver. |
| 20 | +
|
| 21 | +""" |
| 22 | + |
| 23 | +import django |
| 24 | +from django.conf import settings |
| 25 | +from django.db import models, connection |
| 26 | + |
| 27 | +from aws_advanced_python_wrapper import release_resources |
| 28 | +from aws_advanced_python_wrapper.errors import ( |
| 29 | + FailoverFailedError, |
| 30 | + FailoverSuccessError, |
| 31 | + TransactionResolutionUnknownError |
| 32 | +) |
| 33 | + |
| 34 | + |
| 35 | +# Django settings configuration |
| 36 | +DJANGO_SETTINGS = { |
| 37 | + 'DATABASES': { |
| 38 | + 'default': { |
| 39 | + 'ENGINE': 'aws_advanced_python_wrapper.django.backends.mysql_connector', |
| 40 | + 'NAME': 'test_db', |
| 41 | + 'USER': 'admin', |
| 42 | + 'PASSWORD': 'password', |
| 43 | + 'HOST': 'database.cluster-xyz.us-east-1.rds.amazonaws.com', |
| 44 | + 'PORT': 3306, |
| 45 | + 'OPTIONS': { |
| 46 | + 'plugins': 'failover,host_monitoring_v2', |
| 47 | + 'connect_timeout': 10, |
| 48 | + 'autocommit': True, |
| 49 | + 'failover_timeout': 60, |
| 50 | + }, |
| 51 | + }, |
| 52 | + }, |
| 53 | +} |
| 54 | + |
| 55 | +# Configure Django settings |
| 56 | +if not settings.configured: |
| 57 | + settings.configure(**DJANGO_SETTINGS) |
| 58 | +django.setup() |
| 59 | + |
| 60 | + |
| 61 | +class BankAccount(models.Model): |
| 62 | + """Example model for demonstrating failover handling.""" |
| 63 | + name = models.CharField(max_length=100) |
| 64 | + account_balance = models.IntegerField() |
| 65 | + |
| 66 | + class Meta: |
| 67 | + app_label = 'myapp' |
| 68 | + db_table = 'bank_test' |
| 69 | + |
| 70 | + def __str__(self): |
| 71 | + return f"{self.name}: ${self.account_balance}" |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | +def execute_query_with_failover_handling(query_func): |
| 76 | + """ |
| 77 | + Execute a Django ORM query with failover error handling. |
| 78 | +
|
| 79 | + Args: |
| 80 | + query_func: A callable that executes the desired query |
| 81 | +
|
| 82 | + Returns: |
| 83 | + The result of the query function |
| 84 | + """ |
| 85 | + try: |
| 86 | + return query_func() |
| 87 | + |
| 88 | + except FailoverSuccessError: |
| 89 | + # Query execution failed and AWS Advanced Python Driver successfully failed over to an available instance. |
| 90 | + # https://github.com/aws/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#failoversuccesserror |
| 91 | + |
| 92 | + # The connection has been re-established. Retry the query. |
| 93 | + print("Failover successful! Retrying query...") |
| 94 | + |
| 95 | + # Retry the query |
| 96 | + return query_func() |
| 97 | + |
| 98 | + except FailoverFailedError as e: |
| 99 | + # Failover failed. The application should open a new connection, |
| 100 | + # check the results of the failed transaction and re-run it if needed. |
| 101 | + # https://github.com/aws/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#failoverfailederror |
| 102 | + print(f"Failover failed: {e}") |
| 103 | + print("Application should open a new connection and retry the transaction.") |
| 104 | + raise e |
| 105 | + |
| 106 | + except TransactionResolutionUnknownError as e: |
| 107 | + # The transaction state is unknown. The application should check the status |
| 108 | + # of the failed transaction and restart it if needed. |
| 109 | + # https://github.com/aws/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#transactionresolutionunknownerror |
| 110 | + print(f"Transaction resolution unknown: {e}") |
| 111 | + print("Application should check transaction status and retry if needed.") |
| 112 | + raise e |
| 113 | + |
| 114 | + |
| 115 | +def create_table(): |
| 116 | + """Create the database table with failover handling.""" |
| 117 | + def _create(): |
| 118 | + with connection.cursor() as cursor: |
| 119 | + cursor.execute(""" |
| 120 | + CREATE TABLE IF NOT EXISTS bank_test ( |
| 121 | + id INT AUTO_INCREMENT PRIMARY KEY, |
| 122 | + name VARCHAR(100), |
| 123 | + account_balance INT |
| 124 | + ) |
| 125 | + """) |
| 126 | + print("Table created successfully") |
| 127 | + |
| 128 | + execute_query_with_failover_handling(_create) |
| 129 | + |
| 130 | + |
| 131 | +def drop_table(): |
| 132 | + """Drop the database table with failover handling.""" |
| 133 | + def _drop(): |
| 134 | + with connection.cursor() as cursor: |
| 135 | + cursor.execute("DROP TABLE IF EXISTS bank_test") |
| 136 | + print("Table dropped successfully") |
| 137 | + |
| 138 | + execute_query_with_failover_handling(_drop) |
| 139 | + |
| 140 | + |
| 141 | +def insert_records(): |
| 142 | + """Insert records with failover handling.""" |
| 143 | + print("\n--- Inserting Records ---") |
| 144 | + |
| 145 | + def _insert1(): |
| 146 | + account = BankAccount.objects.create(name="Jane Doe", account_balance=200) |
| 147 | + print(f"Inserted: {account}") |
| 148 | + return account |
| 149 | + |
| 150 | + def _insert2(): |
| 151 | + account = BankAccount.objects.create(name="John Smith", account_balance=200) |
| 152 | + print(f"Inserted: {account}") |
| 153 | + return account |
| 154 | + |
| 155 | + execute_query_with_failover_handling(_insert1) |
| 156 | + execute_query_with_failover_handling(_insert2) |
| 157 | + |
| 158 | + |
| 159 | +def query_records(): |
| 160 | + """Query records with failover handling.""" |
| 161 | + print("\n--- Querying Records ---") |
| 162 | + |
| 163 | + def _query(): |
| 164 | + accounts = list(BankAccount.objects.all()) |
| 165 | + for account in accounts: |
| 166 | + print(f" {account}") |
| 167 | + return accounts |
| 168 | + |
| 169 | + return execute_query_with_failover_handling(_query) |
| 170 | + |
| 171 | + |
| 172 | +def update_record(): |
| 173 | + """Update a record with failover handling.""" |
| 174 | + print("\n--- Updating Record ---") |
| 175 | + |
| 176 | + def _update(): |
| 177 | + account = BankAccount.objects.filter(name="Jane Doe").first() |
| 178 | + if account: |
| 179 | + account.account_balance = 300 |
| 180 | + account.save() |
| 181 | + print(f"Updated: {account}") |
| 182 | + return account |
| 183 | + |
| 184 | + return execute_query_with_failover_handling(_update) |
| 185 | + |
| 186 | + |
| 187 | +def filter_records(): |
| 188 | + """Filter records with failover handling.""" |
| 189 | + print("\n--- Filtering Records ---") |
| 190 | + |
| 191 | + def _filter(): |
| 192 | + accounts = list(BankAccount.objects.filter(account_balance__gte=250)) |
| 193 | + print(f"Found {len(accounts)} accounts with balance >= $250:") |
| 194 | + for account in accounts: |
| 195 | + print(f" {account}") |
| 196 | + return accounts |
| 197 | + |
| 198 | + return execute_query_with_failover_handling(_filter) |
| 199 | + |
| 200 | + |
| 201 | +if __name__ == "__main__": |
| 202 | + try: |
| 203 | + print("Django ORM Failover Example with AWS Advanced Python Driver") |
| 204 | + print("=" * 60) |
| 205 | + |
| 206 | + # Create table |
| 207 | + create_table() |
| 208 | + |
| 209 | + # Insert records |
| 210 | + insert_records() |
| 211 | + |
| 212 | + # Query records |
| 213 | + query_records() |
| 214 | + |
| 215 | + # Update a record |
| 216 | + update_record() |
| 217 | + |
| 218 | + # Query again to see the update |
| 219 | + query_records() |
| 220 | + |
| 221 | + # Filter records |
| 222 | + filter_records() |
| 223 | + |
| 224 | + # Cleanup |
| 225 | + print("\n--- Cleanup ---") |
| 226 | + drop_table() |
| 227 | + |
| 228 | + print("\n" + "=" * 60) |
| 229 | + print("Example completed successfully!") |
| 230 | + |
| 231 | + except Exception as e: |
| 232 | + print(f"Error: {e}") |
| 233 | + import traceback |
| 234 | + traceback.print_exc() |
| 235 | + |
| 236 | + finally: |
| 237 | + # Clean up AWS Advanced Python Driver resources |
| 238 | + release_resources() |
0 commit comments