You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm going to run the code below to get the data from mssql in a modal window, and display only the data in the "decide" column in a dropdown format so that the user can modify it as a dropdown when making modifications, but the drop-down option doesn't appear even when I click on the cell dropdown, so I don't know. plz help me ㅠㅠ
trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
if trigger_id == 'submit-date':
# 조회 버튼이 클릭된 경우 데이터 조회 및 반환
if not submit_clicks:
raise PreventUpdate
# 선택된 기간 및 양불 상태에 따라 쿼리문을 동적으로 생성
if selected_status == '전체': # 전체를 선택한 경우
query = f"SELECT DetectedAt, id, ImageName, decide, redboximage_name FROM DetectedObjects WHERE DetectedAt BETWEEN '{start_date}' AND '{end_date}'"
else: # NG 또는 OK를 선택한 경우
query = f"SELECT DetectedAt, id, ImageName, decide, redboximage_name FROM DetectedObjects WHERE DetectedAt BETWEEN '{start_date}' AND '{end_date}' AND decide = '{selected_status}'"
# 모델명이 선택된 경우 WHERE 절에 추가
if selected_model != '전체':
query += f" AND ImageName LIKE '%_{selected_model}_%'"
# grab이 선택된 경우 WHERE 절에 추가
if selected_grab != '전체':
query += f" AND ImageName LIKE '%_{selected_grab}_%'"
df = pd.read_sql(query, conn)
# DetectedAt 열의 값을 원하는 형식으로 변환
df['시간'] = pd.to_datetime(df['DetectedAt']).dt.strftime('%Y년%m월%d일 %H:%M:%S')
# 모델명 열의 데이터에서 "_"를 기준으로 세 번째 파트만 가져오기
df['모델명'] = df['ImageName'].apply(lambda x: re.split(r'_', x)[2])
# 새로운 열 추가 및 데이터 채우기
df['Trim No'] = df['id']
df['grab'] = df['ImageName'].apply(lambda x: re.split(r'_', x)[3] if len(re.split(r'_', x)) >= 4 else '')
df['양불'] = df['decide']
df['원본'] = df['ImageName']
df['빨간박스'] = df['redboximage_name']
# 나타내길 원하는 열 선택
selected_columns = ['시간', '모델명', 'Trim No', 'grab', '양불', '원본', '빨간박스']
df = df[selected_columns]
# 데이터를 DataTable에 맞게 변환하여 반환
return df.to_dict('records')
elif trigger_id == 'modify-button':
# 수정 버튼이 클릭된 경우 수정한 데이터를 반환
if not modify_clicks:
raise PreventUpdate
# 수정한 데이터를 SQL 데이터베이스에 업데이트하는 작업 수행
for row in data:
# SQL UPDATE 쿼리 실행
update_query = f"UPDATE DetectedObjects SET decide = '{row['양불']}' WHERE Id = '{row['Trim No']}' AND ImageName = '{row['원본']}'"
cursor.execute(update_query)
conn.commit()
return data
이미지를 base64로 인코딩하여 HTML에 삽입하는 함수
def encode_image(image_path):
with open(image_path, "rb") as img_file:
encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
return f"data:image/jpeg;base64,{encoded_string}"
display_image 콜백 함수 수정
@app.callback(
Output('additional-info', 'children'),
[Input('modal-output', 'active_cell')],
[State('modal-output', 'data'),
State('select-options', 'value')]
)
def display_image_or_open_folder(active_cell, data, radio_value):
if active_cell:
row_index = active_cell['row']
col_id = active_cell['column_id']
if col_id in ['원본', '빨간박스']:
image_path = data[row_index][col_id]
if radio_value == 'checked':
# 라디오 버튼이 "체크됨" 상태일 때는 해당 이미지 파일을 엽니다.
subprocess.Popen([image_path], shell=True) # 이미지 파일 열기
return None
else:
# 라디오 버튼이 "체크안됨" 상태일 때는 이미지를 표시합니다.
image_html = html.Img(src=encode_image(image_path), style={'width': '100%', 'height': '100%'})
return html.Div(image_html, style={'width': '280px', 'height': '280px'})
return None
@app.callback(
Output('select-grab', 'value'),
[Input('main-modal', 'is_open')],
[State('select-grab', 'value')]
)
def update_grab_input(is_open, current_value):
if is_open and current_value is None:
# 모달이 열릴 때 기존 값이 없으면 초기값 설정
return 'GRAB값 (ex: 전체 , 1R1)'
else:
return current_value
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Select Topic Area
Product Feedback
Body
I'm going to run the code below to get the data from mssql in a modal window, and display only the data in the "decide" column in a dropdown format so that the user can modify it as a dropdown when making modifications, but the drop-down option doesn't appear even when I click on the cell dropdown, so I don't know. plz help me ㅠㅠ
MSSQL 서버에 연결
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=주건우의노트북;DATABASE=르노코리아실전;Trusted_Connection=yes;')
cursor = conn.cursor()
SQL 쿼리 실행 및 데이터 가져오기 (원하는 열만 선택)
query = "SELECT Id , ModelName, ModelTypeFromImage, ClassName0, Value0, ClassName1, Value1, DetectedAt FROM DetectedObjects"
df = pd.read_sql(query, conn)
DetectedAt 열의 값을 YYYY년MM월DD일 hh:mm:ss 형식으로 변환
df['DetectedAt'] = pd.to_datetime(df['DetectedAt']).dt.strftime('%Y년%m월%d일 %H:%M:%S')
Dash 애플리케이션 생성
app = dash.Dash(name, external_stylesheets=[dbc.themes.BOOTSTRAP])
오늘의 날짜 가져오기
today = datetime.now().strftime("%Y년%m월%d일")
cell_style = {
'border': '1px solid black',
'overflowX': 'auto', # 수평 스크롤바 추가
'overflowY': 'auto', # 수직 스크롤바 추가
'width': '100%',
'height': '100%', # 수직 스크롤바를 위해 높이를 100%로 설정
'margin-right': '10px',
'max-height': '400px',
'max-width': '300px',
'text-align': 'center'
}
@app.callback(
Output('modal-output', 'data'),
[Input('submit-date', 'n_clicks'),
Input('modify-button', 'n_clicks')],
[State('modal-output', 'data'),
State('date-picker-range', 'start_date'),
State('date-picker-range', 'end_date'),
State('select-status', 'value'),
State('select-model', 'value'),
State('select-grab', 'value')]
)
def query_and_update_data(submit_clicks, modify_clicks, data, start_date, end_date, selected_status, selected_model, selected_grab):
ctx = dash.callback_context
if not ctx.triggered:
raise PreventUpdate
이미지를 base64로 인코딩하여 HTML에 삽입하는 함수
def encode_image(image_path):
with open(image_path, "rb") as img_file:
encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
return f"data:image/jpeg;base64,{encoded_string}"
display_image 콜백 함수 수정
@app.callback(
Output('additional-info', 'children'),
[Input('modal-output', 'active_cell')],
[State('modal-output', 'data'),
State('select-options', 'value')]
)
def display_image_or_open_folder(active_cell, data, radio_value):
if active_cell:
row_index = active_cell['row']
col_id = active_cell['column_id']
if col_id in ['원본', '빨간박스']:
image_path = data[row_index][col_id]
if radio_value == 'checked':
# 라디오 버튼이 "체크됨" 상태일 때는 해당 이미지 파일을 엽니다.
subprocess.Popen([image_path], shell=True) # 이미지 파일 열기
return None
else:
# 라디오 버튼이 "체크안됨" 상태일 때는 이미지를 표시합니다.
image_html = html.Img(src=encode_image(image_path), style={'width': '100%', 'height': '100%'})
return html.Div(image_html, style={'width': '280px', 'height': '280px'})
return None
조회 모달 내용 정의 부분
modal = html.Div(
[
dbc.Button("조회", id="open_main-modal", className="btn-lg btn-block"),
dbc.Modal(
[
dbc.ModalHeader("기간 및 조회 조건 선택"),
dbc.ModalBody(
[
dbc.Row(
[
dbc.Col(
[
dcc.DatePickerRange(
id='date-picker-range',
display_format='YYYY-MM-DD',
style={'margin-bottom': '10px'}
),
dbc.Row([
dbc.Col(
dcc.Dropdown(
id='select-status',
options=[
{'label': '양불 선택', 'value': '', 'disabled': True},
{'label': '전체', 'value': '전체'},
{'label': 'NG', 'value': 'NG'},
{'label': 'OK', 'value': 'OK'},
{'label': '수정완료', 'value': '수정완료'}
],
value='',
style={'margin-bottom': '10px'}
),
width=4
),
dbc.Col(
dcc.Dropdown(
id='select-model',
options=[
{'label': '모델명 선택', 'value': '', 'disabled': True},
{'label': '전체', 'value': '전체'},
{'label': 'HZG', 'value': 'HZG'},
{'label': 'LJLHEV', 'value': 'LJLHEV'},
{'label': 'LJLICE', 'value': 'LJLICE'}
],
value='',
style={'margin-bottom': '10px'}
),
width=4
),
dbc.Col(
dcc.Input(
id='select-grab',
type='text',
placeholder='GRAB 값을 입력하세요',
style={'margin-bottom': '10px'}
),
width=4
),
]),
dbc.Row(
[
dbc.Col(
dbc.Button("조회", id="submit-date", className="mr-2"),
width=6
),
dbc.Col(
dbc.Button("수정", id="modify-button", className="btn-lg btn-block"),
width=6
),
],
style={'margin-top': '10px'}
)
],
width=8
),
dbc.Col(
html.Div(
id='additional-info',
style={
'border': '1px solid black',
'height': '300px',
'width': '300px',
'padding': '10px'
}
),
width=4
)
]
),
dbc.Row(
dbc.Col(
dash_table.DataTable(
id='modal-output',
columns=[
{'name': '시간', 'id': '시간', 'editable': False},
{'name': '모델명', 'id': '모델명', 'editable': False},
{'name': 'Trim No', 'id': 'Trim No', 'editable': False},
{'name': 'grab', 'id': 'grab', 'editable': False},
{
'name': '양불',
'id': '양불',
'editable': True,
'presentation': 'dropdown', # 드롭다운으로 표시할 때 사용하는 속성
},
{'name': '원본', 'id': '원본', 'editable': False},
{'name': '빨간박스', 'id': '빨간박스', 'editable': False},
],
dropdown={
'양불': {
'options': [
{'label': 'OK', 'value': 'OK'},
{'label': 'NG', 'value': 'NG'},
{'label': '수정완료', 'value': '수정완료'}
]
}
},
style_cell=cell_style,
style_table={'overflowX': 'auto', 'overflowY': 'auto', 'max-height': '400px'}
),
)
),
dbc.Row(
dbc.Col(
dcc.RadioItems(
id='select-options',
options=[
{'label': '체크됨', 'value': 'checked'},
{'label': '체크안됨', 'value': 'unchecked'}
],
value='unchecked', # 기본값 '체크안됨'
inline=True
),
width=12
),
style={'margin-bottom': '10px'}
),
]
),
dbc.ModalFooter(
dbc.Button("Close", id="close_main-modal", className="ml-auto")
),
],
id="main-modal",
size="xl",
),
]
)
GRAB 값을 받아오는 콜백 함수
@app.callback(
Output('select-grab', 'value'),
[Input('main-modal', 'is_open')],
[State('select-grab', 'value')]
)
def update_grab_input(is_open, current_value):
if is_open and current_value is None:
# 모달이 열릴 때 기존 값이 없으면 초기값 설정
return 'GRAB값 (ex: 전체 , 1R1)'
else:
return current_value
Beta Was this translation helpful? Give feedback.
All reactions