import requests
import json
#Flask應用的URL
base_url='http://localhost:5000'
#獲取所有圖書
def get_all_books():
response = requests.get(f'{base_url}/books')
if response.status_code==200:
return response.json()
else:
print(f'Error:{response.status_code}-{response.text}')
return None
#新增一本圖書
def add_book(book_data):
response=requests.post(f'{base_url}/books',json=book_data)
if response.status_code==201:
return response.json()
else:
print(f'Error:{response.status_code}-{response.text}')
return None
#根據ID獲取圖書
def get_book_by_id(book_id):
url=f'{base_url}/books/{book_id}'
response=requests.get(url)
if response.status_code==200:
return response.json()
elif response.status_code==404:
print('book not found')
return None
else:
print(f'Error:{response.status_code} - {response.text}')
return None
#更新圖書資訊
def update_book(book_id,update_data):
url=f'{base_url}/books/{book_id}'
response=requests.put(url,json=update_data)
if response.status_code==200:
return response.json()
elif response.status_code==404:
print('book not found')
return None
else:
print(f'Error:{response.status_code} - {response.text}')
return None
#刪除圖書
def delete_book(book_id):
url=f'{base_url}/books/{book_id}'
response=requests.delete(url)
if response.status_code==204:
print('book delete successfully')
elif response.status_code==404:
print('book not found')
else:
print(f"error:{response.status_code}-{response.text}")
if __name__=='__main__':
all_books=get_all_books()
if all_books:
print('all books:',all_books)
#增加
new_book={'title':"add1",'author':'add1-author'}
added_book=add_book(new_book)
if added_book:
print('book added:',added_book)
#查詢
book_id=1
book=get_book_by_id(book_id)
if book:
print('book:',book)
#更新
updated_data={'title':'Update Title','author':'update Author'}
updated_book=update_book(book_id,updated_data)
if updated_book:
print('book updated:',updated_book)
#刪除
delete_book(book_id)
all_books = get_all_books()
if all_books:
print('all books:', all_books)