我们如何为flask中的标题设置多个选项。例如:我想在 Cache-Control 标题中设置两个选项,一个是 max-age ,另一个是公共/私有。我如何在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
答案 0 :(得分:6)
resp.headers
是一个python字典,因此它将键“Cache-Control”映射到一个值。当您将其设置两次时,您将覆盖之前设置的值。幸运的是,您可以使用以逗号分隔的列表和这些标题:
resp.headers['Cache-Control'] = 'public, max-age=20'