|
| 1 | +import re |
| 2 | +from flask import Flask, request, jsonify |
| 3 | +import pandas as pd |
| 4 | +import pymysql |
| 5 | + |
| 6 | +app = Flask(__name__) |
| 7 | + |
| 8 | +@app.route("/run_query", methods=["POST"]) |
| 9 | +def run_query(): |
| 10 | + # Get parameters from JSON POST body or query string |
| 11 | + data = request.get_json() or request.values |
| 12 | + target_db = data.get('target_db', 'curated') |
| 13 | + target_table = data.get('target_table', 'client_communication_preferences_journal') |
| 14 | + as_of = data.get('as_of') |
| 15 | + |
| 16 | + # Validate as_of parameter |
| 17 | + if not as_of or not re.match(r'^\d{8}$', as_of): |
| 18 | + return jsonify({"error": "Invalid or missing as_of. Expected format: YYYYMMDD."}), 400 |
| 19 | + |
| 20 | + # Dummy DB connection details (replace as needed) |
| 21 | + user = 'myuser' |
| 22 | + password = 'mypassword' |
| 23 | + host = 'mysql1.mycorp.io' |
| 24 | + port = 3306 |
| 25 | + source_db = 'blueshift' |
| 26 | + |
| 27 | + try: |
| 28 | + # Connect to source DB |
| 29 | + source_conn = pymysql.connect( |
| 30 | + host=host, |
| 31 | + user=user, |
| 32 | + password=password, |
| 33 | + database=source_db, |
| 34 | + port=port, |
| 35 | + cursorclass=pymysql.cursors.DictCursor |
| 36 | + ) |
| 37 | + |
| 38 | + qry = f""" |
| 39 | + WITH blueshift_active_email_client_agg AS ( |
| 40 | + SELECT client_id, |
| 41 | + MAX(last_opened_at) AS last_opened_at, |
| 42 | + MIN(first_opened_at) AS first_opened_at |
| 43 | + FROM campaign_activity_kpis |
| 44 | + WHERE (DATE(last_opened_at) <= STR_TO_DATE(%s, '%%Y%%m%%d') |
| 45 | + OR last_opened_at IS NULL |
| 46 | + OR DATE(first_opened_at) <= STR_TO_DATE(%s, '%%Y%%m%%d')) |
| 47 | + GROUP BY client_id |
| 48 | + ) |
| 49 | + SELECT * FROM blueshift_active_email_client_agg |
| 50 | + """ |
| 51 | + |
| 52 | + # Use parameterized queries! |
| 53 | + df = pd.read_sql(qry, source_conn, params=[as_of, as_of]) |
| 54 | + |
| 55 | + source_conn.close() |
| 56 | + except Exception as e: |
| 57 | + return jsonify({"error": f"Failed to query source: {str(e)}"}), 500 |
| 58 | + |
| 59 | + # Now insert into target |
| 60 | + try: |
| 61 | + target_conn = pymysql.connect( |
| 62 | + host=host, |
| 63 | + user=user, |
| 64 | + password=password, |
| 65 | + database=target_db, |
| 66 | + port=port, |
| 67 | + cursorclass=pymysql.cursors.DictCursor |
| 68 | + ) |
| 69 | + |
| 70 | + # Only allow specific table names (simple whitelist for demo) |
| 71 | + allowed_tables = ["client_communication_preferences_journal"] |
| 72 | + if target_table not in allowed_tables: |
| 73 | + return jsonify({"error": "Target table is not allowed."}), 400 |
| 74 | + |
| 75 | + if not df.empty: |
| 76 | + cols = list(df.columns) |
| 77 | + values = [tuple(row) for row in df.values] |
| 78 | + |
| 79 | + insert_stmt = f"INSERT INTO {target_table} ({', '.join(cols)}) VALUES ({', '.join(['%s']*len(cols))})" |
| 80 | + |
| 81 | + with target_conn.cursor() as cursor: |
| 82 | + cursor.executemany(insert_stmt, values) |
| 83 | + target_conn.commit() |
| 84 | + target_conn.close() |
| 85 | + return jsonify({"status": f"Inserted {len(df)} rows into {target_db}.{target_table}"}), 200 |
| 86 | + else: |
| 87 | + return jsonify({"status": "No data to insert."}), 200 |
| 88 | + |
| 89 | + except Exception as e: |
| 90 | + return jsonify({"error": f"Insert failed: {str(e)}"}), 500 |
| 91 | + |
| 92 | + |
| 93 | +if __name__ == "__main__": |
| 94 | + app.run(host='0.0.0.0', port=5000, debug=True) |
0 commit comments