-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
57 lines (45 loc) · 1.44 KB
/
Copy pathmain.py
File metadata and controls
57 lines (45 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Web server for py-uv-db project."""
import os
from flask import Flask, jsonify
import psycopg2
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
def get_db_connection():
"""Get database connection using environment variables."""
# Try DB_URL first, otherwise build from individual parameters
db_url = os.getenv('DB_URL')
if db_url:
conn = psycopg2.connect(db_url)
else:
conn = psycopg2.connect(
host=os.getenv('DB_HOST'),
database=os.getenv('DB_NAME'),
port=os.getenv('DB_PORT', '5432'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASS')
)
return conn
@app.route('/')
def hello():
"""Return hello world message."""
return "hello world"
@app.route('/users')
def get_users():
"""Return list of users from the database."""
try:
conn = get_db_connection()
cursor = conn.cursor()
# Fetch all users
cursor.execute('SELECT id, name FROM users ORDER BY id')
users = cursor.fetchall()
cursor.close()
conn.close()
# Convert to list of dictionaries
users_list = [{"id": user_id, "name": name} for user_id, name in users]
return jsonify(users_list)
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000, debug=True)