Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

Code Habit

[python] 간단한 http request client 구현 본문

카테고리 없음

[python] 간단한 http request client 구현

코드베어 2024. 6. 9. 12:28

회사 작업 중 서버를 Active/Pause 상태로 변환하는데 http 통신을 할 필요가 있어 파이썬으로 간단하게 구현해 보았다.

 

필요요구 사항과 구현된 프로그램 특징은 다음과 같다.

 - 프레임 크기에 따른 체크박스 자동 배치 ( 줄 바꿈 처리 )

 - 성공/실패 여부 Text로 출력하면서 자동 스크롤 되는 debug 창 필요. 

 - 파이썬 기본 내장 라이브러리인 tkinter 사용하여 간단한 ui 구현 ( 체크박스, push 버튼, Debug Text 창 )

 - 파이썬 requests 라이브러리 사용하여 http request 구현

 

import tkinter as tk
import requests
from dataclasses import dataclass
from tkinter import scrolledtext

@dataclass
class Address:
    host:str
    ip:str
    checked:bool

addresses = [
     Address("hostname_1", "127.0.0.1", False),
     Address("hostname_2", "127.0.0.1", False),
     Address("hostname_3", "127.0.0.1", False),
     Address("hostname_4", "127.0.0.1", False),
]

def on_connect_button_click():
    for addr in addresses:  
        if(addr.checked.get() == True):
            url = f"http://{addr.ip}:8060/connect_request?key=server1"
            if send_request_get(url) == False:
                add_debug_info(f"Failed to Request Connect nats {addr.host}")
            else:
                add_debug_info(f"Success to Request Connect nats {addr.host}")

def on_disconnect_button_click():
    for addr in addresses:
        if(addr.checked.get() == True):
            url = f"http://{addr.ip}:8060/disconnect_request?key=server1"
            if send_request_get(url) == False:
                add_debug_info(f"Failed to Request Disconnect nats {addr.host}")
            else:
                add_debug_info(f"Success to Request Disconnect nats {addr.host}")
                
def on_reset_button_click():
    for addr in addresses:
        addr.checked.set(False)

def send_request_get(url) -> bool:
    result = True
    try:
        response = requests.get(url)
        if response.status_code == 200:
            result = True
        else:
            result = False
    except requests.RequestException as e:
        result = False

    return result

def add_debug_info(message):
    debug_area.insert(tk.END, message + "\n")
    debug_area.yview(tk.END)  # 자동 스크롤

root = tk.Tk()
root.title("transcoder connect")

frame = tk.Frame(root)
frame.pack(fill='both', expand=True)

row = 0
checkboxes = []
for addr in addresses:
    var = tk.BooleanVar()
    addr.checked = var
    checkbutton = tk.Checkbutton(frame, text=addr.host, variable=var)
    checkboxes.append(checkbutton)
    row += 1

# 체크박스 배치 및 프레임 넓이에 따라 자동 줄 바꿈 배치
def place_checkboxes():
    row, column = 0, 0
    frame.update_idletasks()  # 현재 프레임의 크기 업데이트
    frame_width = frame.winfo_width()  # 프레임의 너비
    padding = 5  # 적당한 패딩 값
    current_width = padding

    for checkbox in checkboxes:
        checkbox.grid_forget()  # 이전 그리드 설정을 초기화
        checkbox_width = checkbox.winfo_reqwidth()  # 체크박스의 요청 너비
        if current_width + checkbox_width > frame_width:
            row += 1
            column = 0
            current_width = padding
        checkbox.grid(row=row, column=column, sticky="w", padx=padding, pady=padding)
        current_width += checkbox_width + padding
        column += 1
        
# 초기 체크박스 배치
place_checkboxes()

# 창 크기 변경 시 체크박스 재배치
root.bind('<Configure>', lambda e: place_checkboxes())

button = tk.Button(root, text="connect", command=on_connect_button_click)
button.pack()

button2 = tk.Button(root, text="disconnect", command=on_disconnect_button_click)
button2.pack()

button3 = tk.Button(root, text="reset", command=on_reset_button_click)
button3.pack()

debug_area = scrolledtext.ScrolledText(root, wrap=tk.WORD)
debug_area.pack()

# 시작 !
add_debug_info("Initializing system...")

root.mainloop()

 

기능 요구사항이 복잡하지 않아 간단하게 구현할 수 있는 파이썬을 사용하였고 갠적으로는 주로 쓰는 언어가 아니라 코드가 좀 엉성할 수 있다 .. ㅎㅎ;