From c1f5360a8b06364dd5ae6e916a5cbccf1966d380 Mon Sep 17 00:00:00 2001 From: Fulgen301 Date: Fri, 26 Jul 2019 13:46:34 +0200 Subject: Finally fix CORS --- cors.py | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) (limited to 'cors.py') diff --git a/cors.py b/cors.py index 2826920..d9ff90a 100644 --- a/cors.py +++ b/cors.py @@ -1,4 +1,4 @@ -# Copyright (c) 2018, George Tokmaji +# Copyright (c) 2018-2019, George Tokmaji # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above @@ -12,20 +12,24 @@ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -from bottle import HTTPResponse, route, response, hook +from bottle import HTTPResponse, route, response, request, hook -class ParryHTTPResponse(HTTPResponse): - def __init__(self, body="", status=None, headers=None, **more_headers): - more_headers["Access-Control-Allow-Origin"] = "*" - more_headers["Access-Control-Allow-Methods"] = "GET, POST, HEAD, PUT, PATCH, DELETE" - more_headers["Access-Control-Allow-Headers"] = "*" - super().__init__(body, status, headers, **more_headers) +def set_cors_headers(headers): + headers["Access-Control-Allow-Origin"] = "*" + headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, PATCH, HEAD" + headers["Access-Control-Allow-Headers"] = request.headers.get("Access-Control-Request-Headers", "*") + +HTTPResponse.__oldinit__ = HTTPResponse.__init__ +def newinit(self, body="", status=None, headers=None, **more_headers): + set_cors_headers(more_headers) + self.__oldinit__(body, status, headers, **more_headers) + +HTTPResponse.__init__ = newinit @route("", method="OPTIONS") def options(path): - return ParryHTTPResponse(status=204) + return HTTPResponse(status=204) @hook("after_request") def enable_cors(): - response.headers["Access-Control-Allow-Origin"] = "*" - response.headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, PATCH, HEAD" + set_cors_headers(response.headers) -- cgit v1.2.3-54-g00ecf