某些HTTP代理不支持任意HTTP方法或更新的HTTP方法(例如PATCH)。在这种情况下,有可能通过完全违反协议的另一种HTTP方法来“代理” HTTP方法。
它的工作方式是让客户端执行HTTP POST请求并设置X-HTTP-Method-Override标头。然后,在将方法传递给Flask之前,将其替换为标头值。
这可以通过HTTP中间件来完成:
class HTTPMethodOverrideMiddleware(object):
allowed_methods = frozenset([
'GET',
'HEAD',
'POST',
'DELETE',
'PUT',
'PATCH',
'OPTIONS'
])
bodyless_methods = frozenset(['GET', 'HEAD', 'OPTIONS', 'DELETE'])
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()
if method in self.allowed_methods:
environ['REQUEST_METHOD'] = method
if method in self.bodyless_methods:
environ['CONTENT_LENGTH'] = '0'
return self.app(environ, start_response)
要将其与Flask一起使用,请使用中间件包装app对象:
from flask import Flask
app = Flask(__name__)
app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)
https://flask.palletsprojects.com/en/1.1.x/patterns/methodoverrides/
网友评论