newTao/modules/dataview.py

155 lines
5.8 KiB
Python

from collections import OrderedDict
from PyQt5.QtWidgets import QTableView, QHeaderView
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from bson.objectid import ObjectId
class DataView(QTableView):
def __init__(self, mydb, dbviewer1):
super().__init__()
self.mydb = mydb
self.dbviewer1 = dbviewer1
print(f"class DataView 현재 DB상태 : {self.mydb}")
def collect_data(self, selected_keyword_data):
# 컬렉션 설정
keywords_col = self.mydb["keywords"]
print(f"keywords_col : {keywords_col}")
naver_shopping_col = self.mydb["NaverShopping"]
print(f"naver_shopping_col : {naver_shopping_col}")
print(f"넘겨받은 selected_keyword_data : {selected_keyword_data}")
# keywords 컬렉션에서 키워드 정보 가져오기
keyword_infos = keywords_col.find({"_id": {"$in": selected_keyword_data}})
print(f"keyword_infos : {keyword_infos}")
# try:
# keyword_info = keywords_col.find_one({"_id": ObjectId(selected_keyword_data)})
for keywords in keyword_infos:
# 키워드, 카테고리, state 정보 추출
keyword = keywords["키워드"]
print(f"keyword : {keyword}")
category = keywords["카테고리"]
print(f"category : {category}")
state = keywords["state"]
print(f"state : {state}")
# 네이버쇼핑 컬렉션에서 키워드 ID 기반으로 상품 목록 가져오기
products = naver_shopping_col.find({"keyword_id": {"$in": selected_keyword_data}})
# print(f"네이버쇼핑 products : {products}")
# # products를 list로 변환
# products_list = list(products)
# print(f"네이버쇼핑 products_list : {products_list}")
# 상품 데이터 리스트
product_list = []
print("상품 데이터 리스트 초기화")
# 상품 데이터 루프 처리
for product in products:
# product_info = naver_shopping_col.find_one({"_id": product})
# 상품 정보 추출
print("상품 정보 추출")
product_id = product["_id"]
productName = product["productName"]
overseaTp = product["overseaTp"]
keepCnt = product["keepCnt"]
imageUrl = product["imageUrl"]
price = product["price"]
openDate = product["openDate"]
rank = product["rank"]
manuTag = product["manuTag"]
reviewCountSum = product["reviewCountSum"]
dlvryPrice = product["dlvryPrice"]
purchaseCnt = product["purchaseCnt"]
# 상품 정보 OrderedDict에 저장
product_dict = OrderedDict([
("키워드", keyword),
("BASE카테고리", category),
("상품명", productName),
("해외배송여부", overseaTp),
("찜수", keepCnt),
("리뷰수", reviewCountSum),
("구매건수", purchaseCnt),
("가격", price),
("배송비포함가격", dlvryPrice),
("등록일", openDate),
("순위", rank),
("상품태그", manuTag),
("이미지주소", imageUrl),
("상태", state),
("상품 ID", product_id),
])
# 상품 정보 리스트에 추가
product_list.append(product_dict)
print(f"product_list : {product_list}")
return product_list
# self.show_viewer(product_list)
def show_viewer11(self, product_list):
# QTableView 객체 생성
# dbViewer1 = QTableView()
# dbViewer1 = self.findChild(QTableView, "dbViewer1")
if not product_list: # product_list가 비어있는 경우 처리
print("product_list가 비어있습니다.")
return
# 모델 생성 및 데이터 설정
model = QStandardItemModel(len(product_list), len(product_list[0]))
for row, product_data in enumerate(product_list):
for col, value in enumerate(product_data.values()):
item = QStandardItem(str(value))
model.setItem(row, col, item)
# 헤더 설정
headers = list(product_list[0].keys())
model.setHorizontalHeaderLabels(headers) # 컬럼 헤더 제목 설정
# MainTao.ui 파일에서 dbViewer1 객체 참조
self.dbviewer1 = self.findChild(QTableView, "dbviewer1")
# 모델을 QTableView에 설정
self.dbviewer1.setModel(model)
# 헤더 가로 크기 조절 방식 설정
for i in range(len(headers)):
self.dbviewer1.horizontalHeader().setSectionResizeMode(i, QHeaderView.Stretch)
# QTableView 표시
self.dbviewer1.show()
def show_viewer(self, product_list):
if not product_list:
print("No products to display.")
return
# Create a model for the QTableView
model = QStandardItemModel()
# Assuming product_list is a list of dictionaries, where each dictionary represents a product
if product_list:
# Set model headers using the keys from the first item in product_list
model.setHorizontalHeaderLabels(list(product_list[0].keys()))
for product in product_list:
# Create a list of QStandardItems from product values
row = [QStandardItem(str(value)) for value in product.values()]
model.appendRow(row)
self.dbviewer1.setModel(model)
self.dbviewer1.horizontalHeader().setStretchLastSection(True)
self.dbviewer1.resizeColumnsToContents()