Last active
October 2, 2017 16:27
-
-
Save rloqvist/3670a6ef95a82d4c05b8fcf1e0a4529b to your computer and use it in GitHub Desktop.
For "handmade" json/html data to be used by api's etc..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from http.server import BaseHTTPRequestHandler, HTTPServer | |
| from tkinter import filedialog, Tk | |
| import sys | |
| if "/?" in sys.argv or "--help" in sys.argv: | |
| print("\nUsage:") | |
| print("\t--host=<origin> (REQUIRED)") | |
| print("\t--file=<source> (OPTIONAL)\n") | |
| sys.exit(0) | |
| ORIGIN = '' | |
| for arg in sys.argv: | |
| if "--host=" in arg: | |
| ORIGIN = arg.split("--host=")[-1] | |
| if "--file=" in arg: | |
| filename = arg.split("--file=")[-1] | |
| if not ORIGIN: | |
| print("Please specify the origin of the api requests with the flag") | |
| print("\n\t--host=<origin>\n") | |
| sys.exit(1) | |
| if not filename: | |
| root = Tk() | |
| filename = filedialog.askopenfilename(initialdir=".", title="Select file", filetypes=(("All files","*.*"),("Json files","*.json"),("Html files","*.html"))) | |
| root.destroy() | |
| class S(BaseHTTPRequestHandler): | |
| def do_GET(self): | |
| self.send_response(200) | |
| ext = filename.split(".")[-1].lower() | |
| if ext == "html": | |
| _type = 'text/html' | |
| elif ext == "json": | |
| _type = 'application/json' | |
| self.send_header('Content-type', _type) | |
| self.send_header("Access-Control-Allow-Credentials", "true") | |
| self.send_header("Access-Control-Allow-Origin", ORIGIN) | |
| self.end_headers() | |
| self.wfile.write(open(filename, "rb").read()) | |
| server_address = ('', 8000) | |
| httpd = HTTPServer(server_address, S) | |
| httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment