Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import psycopg2
|
| 5 |
+
from psycopg2.extras import RealDictCursor
|
| 6 |
+
import os
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
|
| 9 |
+
app = FastAPI()
|
| 10 |
+
|
| 11 |
+
# Database connection parameters
|
| 12 |
+
DB_CONFIG = {
|
| 13 |
+
"host": "13.126.242.31",
|
| 14 |
+
"database": "aml",
|
| 15 |
+
"user": "dev_cbs_admin",
|
| 16 |
+
"password": "Finovate@2023"
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
def get_db_connection():
|
| 20 |
+
"""Create database connection"""
|
| 21 |
+
return psycopg2.connect(**DB_CONFIG, cursor_factory=RealDictCursor)
|
| 22 |
+
|
| 23 |
+
def read_columns_from_file(template_id: str):
|
| 24 |
+
"""Read column names from output file"""
|
| 25 |
+
filename = f'output_{template_id}.txt'
|
| 26 |
+
try:
|
| 27 |
+
with open(filename, 'r') as f:
|
| 28 |
+
content = f.read()
|
| 29 |
+
# Safely evaluate the string representation of the list
|
| 30 |
+
columns = eval(content)
|
| 31 |
+
return columns
|
| 32 |
+
except Exception as e:
|
| 33 |
+
raise HTTPException(status_code=404, detail=f"Error reading columns from file: {str(e)}")
|
| 34 |
+
|
| 35 |
+
@app.get("/download/{template_id}")
|
| 36 |
+
async def download_excel(template_id: str):
|
| 37 |
+
"""
|
| 38 |
+
Download data as Excel file based on template ID
|
| 39 |
+
"""
|
| 40 |
+
# Read columns from selected file
|
| 41 |
+
columns = read_columns_from_file(template_id)
|
| 42 |
+
|
| 43 |
+
if not columns:
|
| 44 |
+
raise HTTPException(status_code=404, detail="No columns found in output file")
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
# Connect to database
|
| 48 |
+
conn = get_db_connection()
|
| 49 |
+
cur = conn.cursor()
|
| 50 |
+
|
| 51 |
+
# Get existing columns from the table
|
| 52 |
+
cur.execute("""
|
| 53 |
+
SELECT column_name
|
| 54 |
+
FROM information_schema.columns
|
| 55 |
+
WHERE table_name = 'large_transactions'
|
| 56 |
+
""")
|
| 57 |
+
existing_columns = {row['column_name'].lower(): row['column_name'] for row in cur.fetchall()}
|
| 58 |
+
|
| 59 |
+
# Filter out non-existent columns and use actual column names from DB
|
| 60 |
+
valid_columns = []
|
| 61 |
+
for col in columns:
|
| 62 |
+
if col.lower() in existing_columns:
|
| 63 |
+
valid_columns.append(existing_columns[col.lower()])
|
| 64 |
+
|
| 65 |
+
if not valid_columns:
|
| 66 |
+
raise HTTPException(status_code=404, detail="None of the specified columns exist in the table")
|
| 67 |
+
|
| 68 |
+
# Create SQL query with proper column quoting
|
| 69 |
+
quoted_columns = [f'"{col}"' for col in valid_columns]
|
| 70 |
+
query = f"""
|
| 71 |
+
SELECT {', '.join(quoted_columns)}
|
| 72 |
+
FROM large_transactions
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
# Execute query
|
| 76 |
+
cur.execute(query)
|
| 77 |
+
rows = cur.fetchall()
|
| 78 |
+
|
| 79 |
+
# Convert to DataFrame
|
| 80 |
+
df = pd.DataFrame(rows)
|
| 81 |
+
|
| 82 |
+
# Create Excel file in memory
|
| 83 |
+
output = BytesIO()
|
| 84 |
+
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
|
| 85 |
+
df.to_excel(writer, index=False, sheet_name='Data')
|
| 86 |
+
output.seek(0)
|
| 87 |
+
|
| 88 |
+
# Close database connection
|
| 89 |
+
cur.close()
|
| 90 |
+
conn.close()
|
| 91 |
+
|
| 92 |
+
# Return the Excel file as a downloadable response
|
| 93 |
+
return StreamingResponse(
|
| 94 |
+
output,
|
| 95 |
+
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 96 |
+
headers={
|
| 97 |
+
"Content-Disposition": f"attachment; filename=large_transactions_{template_id}.xlsx"
|
| 98 |
+
}
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
raise HTTPException(status_code=500, detail=f"Error fetching data: {str(e)}")
|
| 103 |
+
|
| 104 |
+
@app.get("/templates")
|
| 105 |
+
async def list_templates():
|
| 106 |
+
"""List all available template IDs"""
|
| 107 |
+
try:
|
| 108 |
+
output_files = [f.replace('output_', '').replace('.txt', '')
|
| 109 |
+
for f in os.listdir('.')
|
| 110 |
+
if f.startswith('output_') and f.endswith('.txt')]
|
| 111 |
+
return {"templates": output_files}
|
| 112 |
+
except Exception as e:
|
| 113 |
+
raise HTTPException(status_code=500, detail=f"Error listing templates: {str(e)}")
|