Have you ever wanted to know what it would take to actually write a website in python? Some kind of simple project that would allow you to learn how python creates a front end using just the standard library is easy.
You simply need to use http.server
and socketserver
.
Define a port and create a class that inherits the simple http request handler.
PORT = 9999
class myhttprequesthandler(http.server.SimpleHTTPRequestHandler):
After this you will want to create a method that will serve the HTML content
def do_GET(self):
# This will serve the HTML content
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
# HTML content of the webpage
html = '''
<!DOCTYPE html>
<html>
<head>
<title>My Simple Page</title>
</head>
<body>
<h1>Welcome to My Simple Page</h1>
<p>This is a single page website created using Python's standard library.</p>
</body>
</html>
'''
self.wfile.write(html.encode('utf-8'))
return
Now you just set the handler
handler_object = MyHttpRequestHandler
Then Just bring it all together and make sure that you create a tcp server using the socket server
with socketserver.TCPServer(("", PORT), handler_object) as httpd:
print("Server started at localhost:" + str(PORT))
httpd.serve_forever()
Once you’ve got all this code completed you will be able to modify this code in order to expand the information.
Publish your writings here!
We are always looking to publish your writings on the pyATL website. All content must be related to Python, non-commercial (pitches), and comply with out code of conduct.
If you’re interested, reach out to the editors at hello@pyatl.dev