Spaces:
No application file
No application file
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from sqlalchemy import create_engine
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
app = Flask(__name__)
|
| 7 |
+
|
| 8 |
+
# Database connection
|
| 9 |
+
DATABASE_URL = os.environ.get('DATABASE_URL', 'postgresql://user:password@localhost:5432/database')
|
| 10 |
+
engine = create_engine(DATABASE_URL)
|
| 11 |
+
|
| 12 |
+
@app.route('/user/<int:user_id>', methods=['GET'])
|
| 13 |
+
def get_user_data(user_id):
|
| 14 |
+
"""Endpoint to fetch user data by ID"""
|
| 15 |
+
try:
|
| 16 |
+
# Query database for specific user
|
| 17 |
+
query = f"SELECT * FROM your_table WHERE user_id = {user_id}"
|
| 18 |
+
df = pd.read_sql(query, engine)
|
| 19 |
+
|
| 20 |
+
if df.empty:
|
| 21 |
+
return jsonify({'error': 'User not found'}), 404
|
| 22 |
+
|
| 23 |
+
return jsonify(df.to_dict('records')), 200
|
| 24 |
+
|
| 25 |
+
except Exception as e:
|
| 26 |
+
return jsonify({'error': str(e)}), 500
|
| 27 |
+
|
| 28 |
+
@app.route('/user/<int:user_id>/csv', methods=['GET'])
|
| 29 |
+
def get_user_csv(user_id):
|
| 30 |
+
"""Endpoint to download user data as CSV"""
|
| 31 |
+
try:
|
| 32 |
+
query = f"SELECT * FROM your_table WHERE user_id = {user_id}"
|
| 33 |
+
df = pd.read_sql(query, engine)
|
| 34 |
+
|
| 35 |
+
if df.empty:
|
| 36 |
+
return jsonify({'error': 'User not found'}), 404
|
| 37 |
+
|
| 38 |
+
# Return as CSV
|
| 39 |
+
return df.to_csv(index=False), 200, {
|
| 40 |
+
'Content-Type': 'text/csv',
|
| 41 |
+
'Content-Disposition': f'attachment; filename=user_{user_id}_data.csv'
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
except Exception as e:
|
| 45 |
+
return jsonify({'error': str(e)}), 500
|
| 46 |
+
|
| 47 |
+
if __name__ == '__main__':
|
| 48 |
+
app.run(host='0.0.0.0', port=5000)
|