AWS Builder Center

Development and deployment

This code is a lightweight dual-database read and write service, showing how to connect to two databases at the same time.

from flask import Flask, request, jsonify
import json
import boto3
import pymysql

app = Flask(__name__)

# Loading settings
with open('config.json', 'r') as f:
config = json.load(f)

# DynamoDB Client
dynamodb = boto3.resource('dynamodb', region_name=config['dynamodb']['region'])
ddb_table = dynamodb.Table(config['dynamodb']['table_name'])

# RDS connect function
def get_rds_connection():
rds = config['rds']
return pymysql.connect(
host=rds['host'],
user=rds['user'],
password=rds['password'],
database=rds['database'],
port=rds['port'],
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)

@app.route('/')
def index():
return jsonify({"status": "ok"}), 200

@app.route('/post_data1', methods=['POST'])
def post_data1():
try:
data = request.get_json(force=True)
item_id = data.get('id')
item_value = data.get('value')

if not item_id or item_value is None:
return jsonify({"error": "Missing id or value"}), 400

ddb_table.put_item(Item={'id': item_id, 'value': item_value})
return jsonify({"message": "success", "id": item_id}), 200

except Exception as e:
return jsonify({"error": str(e)}), 500

@app.route('/post_data2', methods=['POST'])
def post_data2():
try:
data = request.get_json(force=True)
item_id = data.get('id')
item_value = data.get('value')

if not item_id or item_value is None:
return jsonify({"error": "Missing id or value"}), 400

conn = get_rds_connection()
try:
with conn.cursor() as cursor:
cursor.execute(
"INSERT INTO data (id, value) VALUES (%s, %s) ON DUPLICATE KEY UPDATE value=%s",
(item_id, item_value, item_value)
)
conn.commit()
return jsonify({"message": "success", "id": item_id}), 200
finally:
conn.close()

except Exception as e:
return jsonify({"error": str(e)}), 500

@app.route('/get_value', methods=['GET'])
def get_value():
try:
item_id = request.args.get('id')
if not item_id:
return jsonify({"error": "Missing id parameter"}), 400

#DynamoDB
ddb_response = ddb_table.get_item(Key={'id': item_id})
ddb_item = ddb_response.get('Item', {})
val1 = int(ddb_item.get('value', 0))

#RDS
conn = get_rds_connection()
try:
with conn.cursor() as cursor:
cursor.execute("SELECT value FROM data WHERE id = %s", (item_id,))
result = cursor.fetchone()
val2 = int(result['value']) if result else 0
finally:
conn.close()

total = val1 + val2
return jsonify({"message": str(total)}), 200

except Exception as e:
return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=False)
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article