from flask import Flask, jsonify , request,render_template,
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
books = [
{"id": 1, "name": '三国演义'},
{"id": 2, "name": '水浒传'},
{"id": 3, "name": '西游记'},
{"id": 4, "name": '红楼梦'},
]
@app.route('/')
def hello_world():
return 'hello world'
@app.route('/books/list')
def book_list():
# return books # 直接返回books会报错的,类型格式不支持
return jsonify(books) # 直接返回books会报错的,类型格式不支持
'''
@app.route('/book/<int:book_id>')#根据id获取字典里其中一个值
def book_detail(book_id):
for book in books:
if book_id == book['id']:
return book
return f"id:{book_id}的图书不存在!"
'''
@app.route('/book/<int:book_id>')#根据id获取字典里其中一个值
def book_detail(book_id):
for book in books:
if book_id == book['id']:
return book
if book_id != book['id'] :#这里book_id != book 不能和book_id == book 放在同一级(判断会出错,除了1,其他id都会报不存在:因为在同一级, book_id 与 book['id']会一直不等),
return f"id:{book_id}的图书不存在!"
if __name__ == '__main__':
app.run(debug=True)
http://127.0.0.1:5000/books/list
http://127.0.0.1:5000/book/1
http://127.0.0.1:5000/book/9