728x90
728x90
django로 구현한 데이터베이스 중 Exhibition model의 구성은 다음과 같다.
GUI 프로그램을 구현할 수 있는 Python 라이브러리인 PyQt5를 이용하여 프로그램을 작성했다.
728x90
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog, QGridLayout, QLabel, QWidget, QLineEdit, QPushButton, QCheckBox
from PyQt5.QtCore import Qt
import requests
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.titleEdit = QLineEdit()
self.creatorEdit = QLineEdit()
self.infoEdit = QTextEdit()
self.titlesEdit = QTextEdit()
self.infosEdit = QTextEdit()
self.photoEdit = QTextEdit()
self.stateEdit = QLineEdit()
self.stateEdit.setEnabled(False)
self.codeEdit = QLineEdit()
self.codeEdit.setEnabled(False)
self.photoEdit.setEnabled(False)
self.photoButton = QPushButton("사진 선택")
self.okButton = QPushButton("업로드")
self.clearButton = QPushButton("초기화")
self.photoButton.clicked.connect(self.showDialog)
self.okButton.clicked.connect(self.upload)
self.clearButton.clicked.connect(self.clear)
self.checkBoxList = list()
self.cb1 = QCheckBox("일러스트", self)
self.cb2 = QCheckBox("사진", self)
self.cb3 = QCheckBox("회화", self)
self.cb4 = QCheckBox("디자인", self)
self.cb5 = QCheckBox("패션", self)
self.cb6 = QCheckBox("제품", self)
self.cb7 = QCheckBox("졸업", self)
self.cb8 = QCheckBox("인물", self)
self.cb9 = QCheckBox("풍경", self)
self.cb10 = QCheckBox("캐릭터", self)
self.checkBoxList.append(self.cb1)
self.checkBoxList.append(self.cb2)
self.checkBoxList.append(self.cb3)
self.checkBoxList.append(self.cb4)
self.checkBoxList.append(self.cb5)
self.checkBoxList.append(self.cb6)
self.checkBoxList.append(self.cb7)
self.checkBoxList.append(self.cb8)
self.checkBoxList.append(self.cb9)
self.checkBoxList.append(self.cb10)
grid = QGridLayout()
self.setLayout(grid)
grid.addWidget(QLabel("제목"), 0, 0)
grid.addWidget(QLabel("작가"), 1, 0)
grid.addWidget(QLabel("정보"), 2, 0)
grid.addWidget(QLabel("사진 제목"), 3, 0)
grid.addWidget(QLabel("사진 설명"), 4, 0)
grid.addWidget(self.titleEdit, 0, 1)
grid.addWidget(self.creatorEdit, 1, 1)
grid.addWidget(self.infoEdit, 2, 1)
grid.addWidget(self.titlesEdit, 3, 1)
grid.addWidget(self.infosEdit, 4, 1)
grid.addWidget(QLabel("*특수문자 사용 금지\n*사진별 내용은 -로 구분\n*사진선택시 순서 주의"), 5, 1)
grid.addWidget(self.photoButton, 6, 1)
grid.addWidget(QLabel("선택된 사진"), 7, 0)
grid.addWidget(self.photoEdit, 7, 1)
grid.addWidget(QLabel("카테고리"), 8, 0)
grid.addWidget(self.cb1, 8, 1)
grid.addWidget(self.cb2, 9, 1)
grid.addWidget(self.cb3, 10, 1)
grid.addWidget(self.cb4, 11, 1)
grid.addWidget(self.cb5, 12, 1)
grid.addWidget(self.cb6, 13, 1)
grid.addWidget(self.cb7, 14, 1)
grid.addWidget(self.cb8, 15, 1)
grid.addWidget(self.cb9, 16, 1)
grid.addWidget(self.cb10, 17, 1)
grid.addWidget(QLabel("카테고리 코드"), 18, 0)
grid.addWidget(self.codeEdit, 18, 1)
grid.addWidget(self.okButton, 19, 1)
grid.addWidget(self.clearButton, 20, 1)
grid.addWidget(self.stateEdit, 21, 1)
self.stateEdit.setText("")
self.setWindowTitle("Upload Gallery")
self.setGeometry(300, 300, 300, 200)
self.show()
def showDialog(self):
self.fname = QFileDialog.getOpenFileNames(self, 'Select Files', './')
print(self.fname[0])
self.photoEdit.setText("선택된 사진 : 총 " + str(len(self.fname[0])) +"장\n" + '\n'.join(self.fname[0]))
def upload(self):
# STEP 0 - 사전 체크
titles = self.titlesEdit.toPlainText().split("-")
contents = self.infosEdit.toPlainText().split("-")
if not(len(titles) == len(contents) == len(self.fname[0])):
self.stateEdit.setText("오류 : 제목수, 내용수, 사진수 다름")
return
# STEP 1 - make Exhibition
self.stateEdit.setText("업로드 시작")
catCode = self.makeCode()
self.stateEdit.setText("코드 생성 완료")
galleryTitle = self.titleEdit.text()
galleryCreator = self.creatorEdit.text()
galleryInfo = self.infoEdit.toPlainText()
data = {"galleryTitle": galleryTitle, "galleryCreator": galleryCreator, "galleryInfo": galleryInfo, "dueDate":"NONE", "category": catCode}
self.stateEdit.setText("데이터셋 준비 완료")
print(galleryTitle, galleryCreator, galleryInfo)
result = requests.post("http://141.164.40.63:8000/gallery/register/", data=data)
CODE = result.text
if CODE == '-1':
self.stateEdit.setText("오류 : 전시회 생성 실패")
print(CODE)
return
else:
print(CODE)
self.stateEdit.setText("전시회 생성 성공 : \"" + CODE + "\"")
cnt = 0
for f in self.fname[0]:
with open(f, "rb") as img:
data = {"code": CODE, "titles":titles[cnt], "contents":contents[cnt]}
imageData = {"image":img}
result = requests.post("http://141.164.40.63:8000/gallery/create/", data=data, files=imageData)
cnt += 1
self.stateEdit.setText("사진 업로드 중... (" + str(cnt) + "/" + str(len(self.fname[0])) + ")")
self.stateEdit.setText("데이터 업로드 성공")
def makeCode(self):
code = ""
for b in self.checkBoxList:
if b.isChecked() == True:
code += "1"
else:
code += "0"
self.codeEdit.setText(code)
return code
def clear(self):
self.titleEdit.setText("")
self.creatorEdit.setText("")
self.infoEdit.setText("")
self.titlesEdit.setText("")
self.infosEdit.setText("")
self.fnameList = None
self.photoEdit.setText("")
self.stateEdit.setText("초기화 완료")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
PyQt5의 그리드 레이아웃을 이용해 위젯들을 배치하였다.
업로드 버튼을 누르면 request post 방식으로 데이터를 서버로 전송한다.
django gallery 모델의 views.py에서는 register 함수를 이용하여 exhibition object를 DB에 저장한다.
728x90
@csrf_exempt
def register(request):
GalleryTitle = request.POST.get('galleryTitle')
GalleryCreator = request.POST.get('galleryCreator')
GalleryInfo = request.POST.get('galleryInfo')
DueDate = request.POST.get('dueDate')
Category = request.POST.get('category')
# 코드 생성
CODE = makeCode()
createDir(CODE)
j = open(FILE_PATH + "database.json", encoding="utf-8-sig")
newList = {}
newList["DATA"] = []
"""
try:
json_data = json.loads(j.read())
print(json_data["DATA"])
now = datetime.now()
date_time = now.strftime("%Y%m%d")
for i in range (len(json_data["DATA"])):
print(json_data["DATA"][i]["DUEDATE"], end = ' ')
if (int(json_data["DATA"][i]["DUEDATE"])) >= (int(date_time)):
newList["DATA"].append(json_data["DATA"][i])
except Exception as e:
print(e)
"""
dictToAdd = {"CODE":CODE, "TITLE":GalleryTitle, "CREATOR":GalleryCreator, "INFO":GalleryInfo, "AMOUNT":"0", "ARTTITLES":"", "ARTCONTENTS":"", "DUEDATE":str(DueDate), "CATEGORY":Category}
newList["DATA"].append(dictToAdd)
j.close()
print(newList)
"""
with open(FILE_PATH + 'database.json', 'w', encoding='UTF-8-sig') as f:
f.write(json.dumps(newList, ensure_ascii=False, indent=4))
"""
newExhibition = Exhibition(galleryCode=CODE, galleryTitle=GalleryTitle, galleryCreator=GalleryCreator, galleryInfo=GalleryInfo, galleryAmount="0", titles="", contents="", dueDate=DueDate, category=Category)
try :
newExhibition.save(force_insert=True)
# update()
return HttpResponse(CODE)
except Exception as e:
print(e)
return HttpResponse('-1')
django DB에 사진을 전송하고 저장하는 코드는 views.py에서 create 함수가 담당한다.
@csrf_exempt
def create (request):
code = request.POST.get("code")
image_list = request.FILES.getlist("image")
titles = request.POST.get("titles")
contents = request.POST.get("contents")
print(code)
for item in image_list:
images = Images.objects.create(photo=item)
images.save()
file_list = os.listdir(IMAGE_PATH)
bp = Exhibition.objects.get(galleryCode = code)
bp.galleryAmount = str(int(bp.galleryAmount) + 1)
if (bp.galleryAmount == '1') :
bp.titles = titles
bp.contents = contents
else :
bp.contents = bp.contents + "-" + contents
bp.titles = bp.titles + "-" + titles
bp.save()
# imageName = os.path.splitext(IMAGE_PATH + galleryCode + ".jpg")
# print(imageName)
fileName = bp.galleryAmount + ".jpg"
shutil.move(IMAGE_PATH + file_list[0], DATA_PATH +code+"/"+ fileName )
return HttpResponse("1")
728x90
728x90