import requests标签:status,code,管理系统,flask,book,books,print,response,客户端 From: https://www.cnblogs.com/zndxall/p/18137817
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)