init
This commit is contained in:
83
01_fastapi_first_step/client.py
Normal file
83
01_fastapi_first_step/client.py
Normal file
@@ -0,0 +1,83 @@
|
||||
import requests
|
||||
import sys
|
||||
|
||||
SERVER_URL = "http://localhost:8000"
|
||||
|
||||
def post_message(user_name, content):
|
||||
"""서버로 메시지를 전송합니다."""
|
||||
payload = {
|
||||
"name": user_name,
|
||||
"message": content
|
||||
}
|
||||
|
||||
try:
|
||||
|
||||
response = requests.post(f"{SERVER_URL}/messages", json=payload)
|
||||
if response.status_code == 200:
|
||||
print("전송 성공!")
|
||||
return True
|
||||
else:
|
||||
print(f"전송 실패: {response.text}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"오류 발생: {e}")
|
||||
return False
|
||||
|
||||
def get_messages(start_index):
|
||||
"""서버로부터 새로운 메시지를 가져옵니다."""
|
||||
try:
|
||||
response = requests.get(f"{SERVER_URL}/messages", params={"start": start_index})
|
||||
|
||||
if response.status_code == 200:
|
||||
new_messages = response.json()
|
||||
if not new_messages:
|
||||
print("새로운 메시지가 없습니다.")
|
||||
else:
|
||||
for msg in new_messages:
|
||||
print(f"[{msg['timestamp']}] {msg['name']}: {msg['message']}")
|
||||
return new_messages
|
||||
else:
|
||||
print(f"메시지 수신 실패: {response.text}")
|
||||
return []
|
||||
|
||||
except Exception as e:
|
||||
print(f"오류 발생: {e}")
|
||||
return []
|
||||
|
||||
def main():
|
||||
print("FastAPI 채팅 클라이언트에 오신 것을 환영합니다!")
|
||||
user_name = input("이름을 입력해주세요 > ").strip()
|
||||
if not user_name:
|
||||
user_name = "Anonymous"
|
||||
|
||||
start_index = 0
|
||||
|
||||
while True:
|
||||
print("\n수행할 작업을 선택해주세요:")
|
||||
print("1. 메시지 전송")
|
||||
print("2. 수신한 메시지 보기")
|
||||
print("3. 종료")
|
||||
|
||||
choice = input("> ").strip()
|
||||
|
||||
if choice == "1":
|
||||
message_content = input("메시지 내용: ").strip()
|
||||
if message_content:
|
||||
post_message(user_name, message_content)
|
||||
else:
|
||||
print("메시지를 입력해주세요.")
|
||||
|
||||
elif choice == "2":
|
||||
new_msgs = get_messages(start_index)
|
||||
start_index += len(new_msgs)
|
||||
|
||||
elif choice == "3":
|
||||
print("프로그램을 종료합니다.")
|
||||
sys.exit(0)
|
||||
|
||||
else:
|
||||
print("잘못된 입력입니다. 1~3 사이의 숫자를 입력해주세요.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user