我们如何在 Flask 中为标头设置多个选项。例如:我想在Cache-Control标头中设置两个选项,一个是max-age,另一个是public/private。我该如何在 Flask 中实现?目前我已经实现了以下代码。
from flask import Flask, jsonify, abort, request, json, Response
app = Flask(__name__)
book_list = ['Peaceful Warrior', 'The Monk who sold his ferrari', 'Lord of the Rings', 'Game of Thrones', 'The True Name', 'The Da Vinci Code',
'Angels and Demons', 'Fear of Flying', 'Harry Potter and Half Blood Prince']
# create a in-memory book-store
books = [{'id': id, 'name': book} for id, book in enumerate(book_list, 1)]
@app.route('/books', methods=['GET'])
def get_books():
if 'name' in request.args:
req_books = [book for book in books if book['name'] == request.args['name']]
js = json.dumps(req_books)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Cache-Control'] = 'public'
resp.headers['Cache-Control'] = 'max-age=20'
elif 'id' in request.args:
req_books = [book for book in books if book['id'] == request.args['id']]
js = json.dumps(req_books)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Cache-Control'] = 'public'
else:
js = json.dumps(books)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Cache-Control'] = 'public'
return resp
最终,我的响应应该具有以下格式的头信息:-
Cache-Control: public
Cache-Control: max-age=20