UserAddresDone
Some checks failed
K8S Fission Deployment / Deployment fission functions (push) Failing after 20s
Some checks failed
K8S Fission Deployment / Deployment fission functions (push) Failing after 20s
This commit is contained in:
322
apps/crud.py
322
apps/crud.py
@@ -1,65 +1,301 @@
|
||||
import io
|
||||
|
||||
from flask import Response
|
||||
from helpers import S3_BUCKET, get_secret, s3_client
|
||||
from helpers import init_db_connection
|
||||
from PIL import Image
|
||||
import logging
|
||||
|
||||
# Giả sử bạn đã cấu hình logger
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Create&Update function to upload or update user avatar S3/Minio
|
||||
def update_or_create_avatar(user_id: str, file):
|
||||
def exists_address_for_post(user_id: str, address: str):
|
||||
cursor = None # Khởi tạo cursor để đảm bảo không gặp lỗi khi vào finally
|
||||
conn = None # Khởi tạo conn để đảm bảo không gặp lỗi khi vào finally
|
||||
try:
|
||||
file_data = file.read()
|
||||
# Bản chất là đường dẫn trong bucket + tên file = user_id
|
||||
object_name = f"{get_secret('S3_PREFIX')}/{user_id}"
|
||||
result = s3_client.put_object(
|
||||
Bucket=S3_BUCKET,
|
||||
Key=object_name,
|
||||
Body=io.BytesIO(file_data),
|
||||
ContentLength=len(file_data),
|
||||
ContentType=file.content_type,
|
||||
)
|
||||
conn = init_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
return result, 200
|
||||
cursor.execute("""
|
||||
SELECT 1
|
||||
FROM ailbl_user_address
|
||||
WHERE user_id = %s AND address = %s
|
||||
""", (user_id, address))
|
||||
|
||||
row = cursor.fetchone() # Nếu có kết quả, trả về dữ liệu 1 dòng
|
||||
return row is not None # Nếu tồn tại, trả về True
|
||||
except Exception as e:
|
||||
logger.error(f"Database error checking address existence: {e}")
|
||||
raise
|
||||
finally:
|
||||
if cursor:
|
||||
cursor.close()
|
||||
if conn:
|
||||
conn.close() # Đảm bảo đóng kết nối sau khi xong
|
||||
|
||||
|
||||
def create_address(user_id: str, data):
|
||||
try:
|
||||
conn = init_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
query = """
|
||||
INSERT INTO ailbl_user_address (user_id, address, area_code, city_code, created, modified)
|
||||
VALUES (%s, %s, %s, %s, NOW(), NOW())
|
||||
"""
|
||||
# Lay cac truong tu data
|
||||
address = data.get("address")
|
||||
area_code = data.get("area_code")
|
||||
city_code = data.get("city_code")
|
||||
|
||||
# Thực thi câu truy vấn SQL để thêm địa chỉ
|
||||
cursor.execute(query, (user_id, address, area_code, city_code))
|
||||
conn.commit() # Lưu thay đổi vào cơ sở dữ liệu
|
||||
|
||||
return {
|
||||
"user_id": user_id,
|
||||
"address": address,
|
||||
"area_code": area_code,
|
||||
"city_code": city_code,
|
||||
"status": "added"
|
||||
}, 200
|
||||
except Exception as e:
|
||||
logging.error(f"Error creating address: {e}")
|
||||
return {"error": str(e)}, 500
|
||||
finally:
|
||||
if cursor:
|
||||
cursor.close()
|
||||
if conn:
|
||||
conn.close()
|
||||
|
||||
|
||||
def filter_address(user_id: str, paging):
|
||||
conn = None # Khởi tạo conn với giá trị None
|
||||
cursor = None
|
||||
try:
|
||||
conn = init_db_connection() # Kết nối cơ sở dữ liệu
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Xây dựng điều kiện lọc
|
||||
conditions = ["user_id = %(user_id)s"]
|
||||
values = {"user_id": user_id} # Điều kiện cơ bản cho user_id
|
||||
|
||||
# Lọc theo address
|
||||
if paging.filter.address:
|
||||
conditions.append("LOWER(Address) LIKE %(address)s")
|
||||
values["address"] = f"%{paging.filter.address.lower()}%"
|
||||
|
||||
# Lọc theo area_code
|
||||
if paging.filter.area_code:
|
||||
conditions.append("AreaCode = %(area_code)s")
|
||||
values["area_code"] = paging.filter.area_code
|
||||
|
||||
# Lọc theo city_code
|
||||
if paging.filter.city_code:
|
||||
conditions.append("CityCode = %(city_code)s")
|
||||
values["city_code"] = paging.filter.city_code
|
||||
|
||||
# Lọc theo ngày tạo
|
||||
if paging.filter.created_from:
|
||||
conditions.append("Created >= %(created_from)s")
|
||||
values["created_from"] = paging.filter.created_from
|
||||
|
||||
if paging.filter.created_to:
|
||||
conditions.append("Created <= %(created_to)s")
|
||||
values["created_to"] = paging.filter.created_to
|
||||
|
||||
# Lọc theo ngày sửa đổi
|
||||
if paging.filter.modified_from:
|
||||
conditions.append("Modified >= %(modified_from)s")
|
||||
values["modified_from"] = paging.filter.modified_from
|
||||
|
||||
if paging.filter.modified_to:
|
||||
conditions.append("Modified <= %(modified_to)s")
|
||||
values["modified_to"] = paging.filter.modified_to
|
||||
|
||||
# Kết hợp điều kiện lọc
|
||||
where_clause = " AND ".join(conditions)
|
||||
if where_clause:
|
||||
where_clause = "WHERE " + where_clause
|
||||
|
||||
# Sắp xếp kết quả nếu có:
|
||||
order_clause = ""
|
||||
if paging.sortby:
|
||||
direction = "ASC" if paging.asc else "DESC"
|
||||
order_clause = f"ORDER BY {paging.sortby} {direction}"
|
||||
|
||||
# Kết hợp truy vấn
|
||||
sql = f"""
|
||||
SELECT
|
||||
id,
|
||||
user_id,
|
||||
address,
|
||||
area_code,
|
||||
city_code,
|
||||
created,
|
||||
modified,
|
||||
COUNT(*) OVER() AS total
|
||||
FROM ailbl_user_address
|
||||
{where_clause}
|
||||
{order_clause}
|
||||
LIMIT %(limit)s OFFSET %(offset)s
|
||||
"""
|
||||
values["limit"] = paging.size
|
||||
values["offset"] = paging.page * paging.size
|
||||
|
||||
print("SQL Query: ", sql) # In ra câu truy vấn SQL
|
||||
print("Values: ", values) # In ra các tham số
|
||||
|
||||
cursor.execute(sql, values) # Thực thi câu truy vấn với các giá trị
|
||||
|
||||
# Lấy tất cả các kết quả
|
||||
addresses = cursor.fetchall()
|
||||
print("Fetched addresses: ", addresses) # In ra kết quả
|
||||
|
||||
# Nếu không có kết quả
|
||||
if not addresses:
|
||||
return {"message": "No addresses found"}, 404
|
||||
|
||||
address_list = []
|
||||
for address in addresses:
|
||||
address_dict = {
|
||||
"id": address[0],
|
||||
"user_id": address[1],
|
||||
"address": address[2],
|
||||
"area_code": address[3],
|
||||
"city_code": address[4],
|
||||
"created": address[5],
|
||||
"modified": address[6]
|
||||
}
|
||||
|
||||
# Kiểm tra xem có cột 'total' hay không
|
||||
if len(address) > 7:
|
||||
address_dict["total"] = address[7]
|
||||
|
||||
address_list.append(address_dict)
|
||||
|
||||
return address_list, 200
|
||||
|
||||
except Exception as e:
|
||||
return {"error": str(e)}, 500
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_avatar_url(user_id: str): # Read function to get user avatar from S3/Minio
|
||||
def exists_address_for_delete(address_id: str, user_id: str):
|
||||
try:
|
||||
response = s3_client.get_object(
|
||||
Bucket=S3_BUCKET,
|
||||
Key=f"{get_secret('S3_PREFIX')}/{user_id}"
|
||||
)
|
||||
# image_data = response["body"].read(content_type)
|
||||
image_data = response['Body'].read()
|
||||
# Kiểm tra xem địa chỉ có tồn tại cho user_id này không
|
||||
conn = init_db_connection()
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute("""
|
||||
SELECT 1
|
||||
FROM ailbl_user_address
|
||||
WHERE id = %s AND user_id = %s
|
||||
""", (address_id, user_id))
|
||||
|
||||
with Image.open(io.BytesIO(image_data)) as img:
|
||||
fmt = img.format.lower() # ví dụ: 'jpeg', 'png', 'webp'
|
||||
content_type = f"image/{'jpeg' if fmt == 'jpg' else fmt}"
|
||||
# return Response(
|
||||
# io.BytesIO(image_data),
|
||||
# content_type=content_type,
|
||||
# direct_passthrough=True,
|
||||
# )
|
||||
|
||||
return Response(
|
||||
image_data,
|
||||
content_type=content_type,
|
||||
direct_passthrough=True
|
||||
), 200
|
||||
row = cursor.fetchone()
|
||||
return row is not None # Nếu có kết quả, địa chỉ tồn tại
|
||||
|
||||
except Exception as e:
|
||||
return {"error": str(e)}, 500
|
||||
logger.error(f"Database error checking address existence: {e}")
|
||||
raise
|
||||
finally:
|
||||
if conn:
|
||||
conn.close() # Đảm bảo kết nối được đóng
|
||||
|
||||
|
||||
# Delete Function to delete user avatar from S3/Minio
|
||||
def delete_avatar(user_id: str) -> dict:
|
||||
def delete_address(address_id: str, user_id: str):
|
||||
try:
|
||||
result = s3_client.delete_object(
|
||||
Bucket=S3_BUCKET,
|
||||
Key=f"{get_secret('S3_PREFIX')}/{user_id}"
|
||||
)
|
||||
return result, 200
|
||||
conn = init_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Xóa địa chỉ từ bảng ailbl_user_address
|
||||
cursor.execute("""
|
||||
DELETE FROM ailbl_user_address
|
||||
WHERE id = %s AND user_id = %s
|
||||
""", (address_id, user_id))
|
||||
|
||||
conn.commit() # Lưu thay đổi vào cơ sở dữ liệu
|
||||
return {"message": "Address deleted successfully"}, 200
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error deleting address: {e}")
|
||||
return {"error": str(e)}, 500
|
||||
finally:
|
||||
if cursor:
|
||||
cursor.close()
|
||||
if conn:
|
||||
conn.close()
|
||||
|
||||
|
||||
def update_address(address_id, user_id, request_data):
|
||||
try:
|
||||
conn = init_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Xây dựng câu lệnh UPDATE
|
||||
update_query = """
|
||||
UPDATE ailbl_user_address
|
||||
SET address = %s, area_code = %s, city_code = %s, modified = NOW()
|
||||
WHERE id = %s AND user_id = %s
|
||||
RETURNING id;
|
||||
"""
|
||||
cursor.execute(update_query, (
|
||||
request_data.get("address"),
|
||||
request_data.get("area_code"),
|
||||
request_data.get("city_code"),
|
||||
address_id,
|
||||
user_id
|
||||
))
|
||||
|
||||
# Lấy kết quả sau khi thực hiện UPDATE
|
||||
result = cursor.fetchone()
|
||||
if result:
|
||||
conn.commit()
|
||||
return {"id": result[0], "status": "updated"}, 200
|
||||
else:
|
||||
return {"error": "Address not found or not updated"}, 404
|
||||
|
||||
except Exception as e:
|
||||
# conn.rollback()
|
||||
# current_app.logger.error(f"[update_address] DB Error: {e}")
|
||||
return {"error": "DATABASE_ERROR"}, 500
|
||||
|
||||
finally:
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
|
||||
# def get_address_by_id(address_id: str): Update chưa xong
|
||||
# conn = None
|
||||
# cursor = None
|
||||
# try:
|
||||
# conn = init_db_connection()
|
||||
# with conn.cursor() as cursor:
|
||||
# cursor.execute("""
|
||||
# SELECT address, area_code, city_code, created, modified
|
||||
# FROM ailbl_user_address
|
||||
# WHERE id = %s;
|
||||
# """, (address_id,))
|
||||
|
||||
# row = cursor.fetchone()
|
||||
# if row:
|
||||
# return {
|
||||
# "address": row[0],
|
||||
# "area_code": row[1],
|
||||
# "city_code": row[2],
|
||||
# "created": row[3],
|
||||
# "modified": row[4]
|
||||
# }
|
||||
# else:
|
||||
# return None # Nếu không tìm thấy địa chỉ, trả về None
|
||||
|
||||
# except Exception as e:
|
||||
# return {"error": "DATABASE_ERROR"}, 500
|
||||
# finally:
|
||||
# if cursor:
|
||||
# cursor.close()
|
||||
# if conn:
|
||||
# conn.close()
|
||||
|
||||
Reference in New Issue
Block a user