我想将所有我的HTTP响应头设置为以下内容:
response.headers["X-Frame-Options"] = "SAMEORIGIN"
我查看了这个问题,但它只更改一个特定控制器的标头。我想在“before_request”函数中更改所有标头,类似于以下逻辑。我该怎么做?
@app.before_request
def before_request():
# response.headers["X-Frame-Options"] = "SAMEORIGIN"
我想将所有我的HTTP响应头设置为以下内容:
response.headers["X-Frame-Options"] = "SAMEORIGIN"
我查看了这个问题,但它只更改一个特定控制器的标头。我想在“before_request”函数中更改所有标头,类似于以下逻辑。我该怎么做?
@app.before_request
def before_request():
# response.headers["X-Frame-Options"] = "SAMEORIGIN"
@app.after_request()
钩子来设置头部信息。在这个钩子函数中,你会得到一个响应对象,可以在上面设置头部信息。@app.after_request
def apply_caching(response):
response.headers["X-Frame-Options"] = "SAMEORIGIN"
return response
当这个钩子运行时,Flask.request
上下文仍然可用,因此您仍然可以基于请求来改变响应。
@app.before_request
来获取你的头部令牌并检查其有效性(头部应该在 JavaScript 中发送请求),然后你的 after request
是你应该更改响应头的地方。 - John Ruddellresponse.headers["Content-Security-Policy"] = "frame-ancestors 'self'"
- macnewbold# Helper function to return a response with status code and CORS headers
def prepare_response(res_object, status_code):
response = flask.jsonify(res_object)
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
return response, status_code
middleware.py
import flask
from flask import request, g
class SimpleMiddleWare(object):
"""
Simple WSGI middleware
"""
def __init__(self, app):
self.app = app
self._header_name = "any_request_header"
def __call__(self, environ, start_response):
"""
middleware to capture request header from incoming http request
"""
request_id_header = environ.get(self._header_name) # reading all request headers
environ[self._header_name] = request_id_header
def new_start_response(status, response_headers, exc_info=None):
"""
set custom response headers
"""
# set the above captured request header as response header
response_headers.append((self._header_name, request_id_header))
# example to access flask.g values set in any class thats part of the Flask app & then set that as response header
values = g.get(my_response_header, {})
if values.get('x-custom-header'):
response_headers.append(('x-custom-header', values.get('x-custom-header')))
return start_response(status, response_headers, exc_info)
return self.app(environ, new_start_response)
从主类调用中间件
文件:main.py
from flask import Flask
import asyncio
from gevent.pywsgi import WSGIServer
from middleware import SimpleMiddleWare
app = Flask(__name__)
app.wsgi_app = SimpleMiddleWare(app.wsgi_app)
g
在import语句中是什么?values = g.get(my_response_header, {})
。另外,my_response_header
是什么? - user6308605
X-Frame-Options
已被frame-ancestors
指令所取代。有关frame-ancestors
的更多信息,请访问https://www.w3.org/TR/CSP2/#directive-frame-ancestors,并使用开源库实现Flask CSP:https://github.com/twaldear/flask-csp。 - potench