From 8213c244eaca9a65a51ccb8422b3adb45485ef43 Mon Sep 17 00:00:00 2001 From: Fulgen301 Date: Tue, 16 Oct 2018 18:57:01 +0200 Subject: Subclass HTTPReponse in order to ensure the presence of CORS headers --- cors.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 cors.py (limited to 'cors.py') diff --git a/cors.py b/cors.py new file mode 100644 index 0000000..2826920 --- /dev/null +++ b/cors.py @@ -0,0 +1,31 @@ +# Copyright (c) 2018, 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 +# copyright notice and this permission notice appear in all copies. + +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# 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 + +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) + +@route("", method="OPTIONS") +def options(path): + return ParryHTTPResponse(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" -- cgit v1.2.3-54-g00ecf