Python,Flask:如何为所有响应设置响应标头

Python, Flask: How to set response header for all responses(Python,Flask:如何为所有响应设置响应标头)
本文介绍了Python,Flask:如何为所有响应设置响应标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我所有的 http 标头响应设置为这样的:

I want to set all of my http headers responses to something like this:

response.headers["X-Frame-Options"] = "SAMEORIGIN"

我检查了 这个问题,但它只会改变一个特定控制器的标题.我想在类似于以下逻辑的before_request"函数中更改所有标题.我该怎么做?

I checked this question, but it only changes the header for one specific controller. I want to change all of my headers maybe in "before_request" function similar to the following logic. How can I do that?

@app.before_request
def before_request():
    # response.headers["X-Frame-Options"] = "SAMEORIGIN"

推荐答案

@app.after_request() 钩子,此时你有一个响应对象来设置标题:

Set the header in a @app.after_request() hook, at which point you have a response object to set the header on:

@app.after_request
def apply_caching(response):
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    return response

flask.request 上下文 在这个钩子运行时仍然可用,所以此时你仍然可以根据请求改变响应.

The flask.request context is still available when this hook runs, so you can still vary the response based on the request at this time.

这篇关于Python,Flask:如何为所有响应设置响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)