Last active
May 2, 2024 12:35
-
-
Save Integralist/ce5ebb37390ab0ae56c9e6e80128fdc2 to your computer and use it in GitHub Desktop.
Python3 HTTP Server.py
This file contains 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
import time | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
HOST_NAME = 'localhost' | |
PORT_NUMBER = 9000 | |
class MyHandler(BaseHTTPRequestHandler): | |
def do_HEAD(self): | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
def do_GET(self): | |
paths = { | |
'/foo': {'status': 200}, | |
'/bar': {'status': 302}, | |
'/baz': {'status': 404}, | |
'/qux': {'status': 500} | |
} | |
if self.path in paths: | |
self.respond(paths[self.path]) | |
else: | |
self.respond({'status': 500}) | |
def handle_http(self, status_code, path): | |
self.send_response(status_code) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
content = ''' | |
<html><head><title>Title goes here.</title></head> | |
<body><p>This is a test.</p> | |
<p>You accessed path: {}</p> | |
</body></html> | |
'''.format(path) | |
return bytes(content, 'UTF-8') | |
def respond(self, opts): | |
response = self.handle_http(opts['status'], self.path) | |
self.wfile.write(response) | |
if __name__ == '__main__': | |
server_class = HTTPServer | |
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler) | |
print(time.asctime(), 'Server Starts - %s:%s' % (HOST_NAME, PORT_NUMBER)) | |
try: | |
httpd.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
httpd.server_close() | |
print(time.asctime(), 'Server Stops - %s:%s' % (HOST_NAME, PORT_NUMBER)) |
Hey @jeffgroversr, you should check out Jekyll for easily deploying static websites through Github Pages - it'll do exactly what you're asking for and comes packaged with a very easy to use local development server. Send me an email at adpena@gmail.com if you have any questions!
👍
(y)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Mark I am new to this. I got this code to work in jupyter notebook. I tried line by link in python 36 but it did not work for me. After it serves us, how do you get a page? For example a have a get.html page and a response.py page. How do I get the response page to come up in the browser?
Thanks Jeff