Skip to content

Instantly share code, notes, and snippets.

@watahani
Last active April 24, 2021 12:02
Show Gist options
  • Save watahani/6c026b6899b2897bb57e947d3b1432d5 to your computer and use it in GitHub Desktop.
Save watahani/6c026b6899b2897bb57e947d3b1432d5 to your computer and use it in GitHub Desktop.
CORS API Sample
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import logging
import json
"""
CORS API Sample (for python 3.7 or later)
Usage::
./server.py [<port>]
"""
class S(BaseHTTPRequestHandler):
def _set_response(self, custom_headers = {}):
if self.path == "/api/step0":
self._set_step_0_headers()
elif self.path == "/api/step1":
self._set_step_1_headers()
elif self.path == "/api/step2":
self._set_step_2_headers()
elif self.path == "/api/step3":
self._set_step_3_headers()
elif self.path == "/api/step4":
self._set_step_4_headers()
elif self.path == "/api/step5":
self._set_step_5_headers()
elif self.path == "/api/step6":
self._set_step_6_headers()
else:
self.send_response(200)
self.end_headers()
def _set_step_0_headers(self):
self.send_response(200)
self.end_headers()
def _set_step_1_headers(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
def _set_step_2_headers(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "https://blog.haniyama.com")
self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")
self.end_headers()
def _set_step_3_headers(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "https://blog.haniyama.com")
self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")
self.send_header("Access-Control-Allow-Methods", "POST, DELETE")
self.send_header("Set-Cookie", "key3=value; SameSite=None; Secure")
# self.send_header("Set-Cookie", "key3=value;")
# self.send_header("Set-Cookie", "none3=value; SameSite=none")
self.send_header("Set-Cookie", "nonesecure3=value; Path=/; SameSite=none; Secure")
self.end_headers()
def _set_step_4_headers(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "https://blog.haniyama.com")
self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")
self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE")
self.send_header("Access-Control-Allow-Credentials", "true")
# self.send_header("Set-Cookie", "key4=value;")
# self.send_header("Set-Cookie", "none4=value; SameSite=none")
self.send_header("Set-Cookie", "nonesecure4=value; Path=/; SameSite=none; Secure")
self.end_headers()
def _set_step_5_headers(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "https://blog.haniyama.com")
self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")
self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE")
self.send_header("Access-Control-Allow-Credentials", "true")
self.send_header("Access-Control-Expose-Headers", "X-Exportable")
self.send_header("X-Exportable", "hogehoge")
self.end_headers()
def _set_step_6_headers(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin", "https://blog.haniyama.com")
self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")
self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE")
self.send_header("Access-Control-Allow-Credentials", "true")
self.send_header("Access-Control-Expose-Headers", "X-Exportable")
self.send_header("X-Exportable", "hogehoge")
self.send_header("Access-Control-Max-Age", "10")
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n",
str(self.path), str(self.headers))
self._set_response()
self.wfile.write("GET request for {},\n\n with request headers:\n{}".format(
self.path, self.headers).encode('utf-8'))
def do_OPTIONS(self):
logging.info("OPTIONS request,\nPath: %s\nHeaders:\n%s\n",
str(self.path), str(self.headers))
self._set_response()
self.wfile.write("OPTIONS request for {},\n\n with request headers:\n{}".format(
self.path, self.headers).encode('utf-8'))
def do_POST(self):
logging.info("POST request,\nPath: %s\nHeaders:\n%s\n",
str(self.path), str(self.headers))
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
body = json.loads(post_data)
self._set_response()
res = json.dumps({
"status": "ok",
"message": "hello {}".format(body.get("name"))
})
self.wfile.write(res.encode('utf-8'))
def do_DELETE(self):
logging.info("DELETE request,\nPath: %s\nHeaders:\n%s\n",
str(self.path), str(self.headers))
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
body = json.loads(post_data)
self._set_response()
res = json.dumps({
"status": "ok",
"message": "deleted {}".format(body.get("name"))
})
self.wfile.write(res.encode('utf-8'))
def run(server_class=ThreadingHTTPServer, handler_class=S, port=8080):
logging.basicConfig(level=logging.INFO)
server_address = ('', port)
httpd = server_class(server_address, handler_class)
logging.info("Starting httpd... port {}\n".format(str(port)))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
logging.info('Stopping httpd...\n')
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment