futranbg commited on
Commit
46612cf
·
verified ·
1 Parent(s): 5af54e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -13
app.py CHANGED
@@ -1,16 +1,130 @@
1
- # app.py
 
 
 
2
 
3
- from flask import Flask
 
4
 
5
- # Tạo một instance của ứng dụng Flask
6
- # __name__ là tên của module hiện tại, Flask sử dụng nó để biết
7
- # nơi tìm các tài nguyên như template và tệp tĩnh.
8
  app = Flask(__name__)
9
 
10
- # Định nghĩa một route (đường dẫn)
11
- # Decorator @app.route('/') nói với Flask rằng khi người dùng truy cập
12
- # địa chỉ gốc của trang web (ví dụ: http://127.0.0.1:5000/),
13
- # hàm bên dưới sẽ được thực thi.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  @app.route('/')
15
  def welcome_page():
16
  """
@@ -56,9 +170,5 @@ def welcome_page():
56
  </html>
57
  """
58
 
59
- # Phần này đảm bảo rằng máy chủ phát triển chỉ chạy khi bạn thực thi tệp này trực tiếp,
60
- # không phải khi nó được import như một module ở nơi khác.
61
- # debug=True cung cấp các thông báo lỗi hữu ích và tự động tải lại máy chủ
62
- # khi bạn thay đổi mã, rất tiện lợi cho việc phát triển.
63
  if __name__ == '__main__':
64
  app.run(debug=True, host='0.0.0.0', port=7860)
 
1
+ import os
2
+ from flask import Flask, jsonify, request, g
3
+ import psycopg2
4
+ from dotenv import load_dotenv
5
 
6
+ # Tải các biến môi trường từ file .env (chỉ cho môi trường phát triển cục bộ)
7
+ load_dotenv()
8
 
 
 
 
9
  app = Flask(__name__)
10
 
11
+ # Cấu hình kết nối sở dữ liệu từ biến môi trường
12
+ DB_HOST = os.getenv('DB_HOST')
13
+ DB_NAME = os.getenv('DB_NAME')
14
+ DB_USER = os.getenv('DB_USER')
15
+ DB_PASSWORD = os.getenv('DB_PASSWORD')
16
+ DB_PORT = os.getenv('DB_PORT')
17
+
18
+ # Hàm để thiết lập kết nối cơ sở dữ liệu
19
+ def get_db_connection():
20
+ if 'db' not in g:
21
+ try:
22
+ g.db = psycopg2.connect(
23
+ host=DB_HOST,
24
+ database=DB_NAME,
25
+ user=DB_USER,
26
+ password=DB_PASSWORD,
27
+ port=DB_PORT
28
+ )
29
+ print("Kết nối đến Supabase PostgreSQL thành công!")
30
+ except Exception as e:
31
+ print(f"Lỗi khi kết nối đến cơ sở dữ liệu: {e}")
32
+ g.db = None # Đảm bảo g.db là None nếu kết nối thất bại
33
+ return g.db
34
+
35
+ # Hàm đóng kết nối cơ sở dữ liệu khi request kết thúc
36
+ @app.teardown_appcontext
37
+ def close_db_connection(exception):
38
+ db = g.pop('db', None)
39
+ if db is not None:
40
+ db.close()
41
+ print("Đã đóng kết nối Supabase PostgreSQL.")
42
+
43
+ @app.route('/test_db')
44
+ def test_db():
45
+ conn = get_db_connection()
46
+ if conn is None:
47
+ return jsonify({"message": "Không thể kết nối đến cơ sở dữ liệu.", "status": "error"}), 500
48
+
49
+ try:
50
+ cur = conn.cursor()
51
+ cur.execute("SELECT version();") # Lấy thông tin phiên bản PostgreSQL
52
+ db_version = cur.fetchone()[0]
53
+ cur.close()
54
+ return jsonify({
55
+ "message": "Kết nối cơ sở dữ liệu thành công!",
56
+ "db_version": db_version,
57
+ "status": "success"
58
+ })
59
+ except Exception as e:
60
+ return jsonify({"message": f"Lỗi truy vấn cơ sở dữ liệu: {e}", "status": "error"}), 500
61
+
62
+ @app.route('/create_table')
63
+ def create_table():
64
+ conn = get_db_connection()
65
+ if conn is None:
66
+ return jsonify({"message": "Không thể kết nối đến cơ sở dữ liệu.", "status": "error"}), 500
67
+
68
+ try:
69
+ cur = conn.cursor()
70
+ cur.execute("""
71
+ CREATE TABLE IF NOT EXISTS users (
72
+ id SERIAL PRIMARY KEY,
73
+ name VARCHAR(100) NOT NULL,
74
+ email VARCHAR(100) UNIQUE NOT NULL
75
+ );
76
+ """)
77
+ conn.commit() # Commit thay đổi
78
+ cur.close()
79
+ return jsonify({"message": "Bảng 'users' đã được tạo (nếu chưa tồn tại).", "status": "success"})
80
+ except Exception as e:
81
+ conn.rollback() # Hoàn tác nếu có lỗi
82
+ return jsonify({"message": f"Lỗi khi tạo bảng: {e}", "status": "error"}), 500
83
+
84
+ @app.route('/add_user', methods=['POST'])
85
+ def add_user():
86
+ conn = get_db_connection()
87
+ if conn is None:
88
+ return jsonify({"message": "Không thể kết nối đến cơ sở dữ liệu.", "status": "error"}), 500
89
+
90
+ data = request.json
91
+ if not data or 'name' not in data or 'email' not in data:
92
+ return jsonify({"message": "Yêu cầu cần 'name' và 'email' trong body JSON.", "status": "error"}), 400
93
+
94
+ name = data['name']
95
+ email = data['email']
96
+
97
+ try:
98
+ cur = conn.cursor()
99
+ cur.execute("INSERT INTO users (name, email) VALUES (%s, %s) RETURNING id;", (name, email))
100
+ user_id = cur.fetchone()[0]
101
+ conn.commit()
102
+ cur.close()
103
+ return jsonify({"message": "Người dùng đã được thêm thành công!", "user_id": user_id, "status": "success"}), 201
104
+ except Exception as e:
105
+ conn.rollback()
106
+ return jsonify({"message": f"Lỗi khi thêm người dùng: {e}", "status": "error"}), 500
107
+
108
+ @app.route('/users')
109
+ def get_users():
110
+ conn = get_db_connection()
111
+ if conn is None:
112
+ return jsonify({"message": "Không thể kết nối đến cơ sở dữ liệu.", "status": "error"}), 500
113
+
114
+ try:
115
+ cur = conn.cursor()
116
+ cur.execute("SELECT id, name, email FROM users;")
117
+ users_data = cur.fetchall()
118
+ cur.close()
119
+
120
+ users_list = []
121
+ for user in users_data:
122
+ users_list.append({"id": user[0], "name": user[1], "email": user[2]})
123
+
124
+ return jsonify({"users": users_list, "status": "success"})
125
+ except Exception as e:
126
+ return jsonify({"message": f"Lỗi khi lấy danh sách người dùng: {e}", "status": "error"}), 500
127
+
128
  @app.route('/')
129
  def welcome_page():
130
  """
 
170
  </html>
171
  """
172
 
 
 
 
 
173
  if __name__ == '__main__':
174
  app.run(debug=True, host='0.0.0.0', port=7860)