I recently became interested in back end web frameworks in python, but I didn't want to use django or flask. (I want to make something similar to django or flask) So I decided to make my own. This is what I have so far. I have been programming for nearly two years and I mostly do c++. But I would like to improve my python. What can I do to improve this, or my python in general? Thanks!

import socket as Socket

class Server:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.__run_allowed = True
        self.__HTTP_response_codes = {200: " OK", 404: " Not Found"}
        self.__socket = Socket.socket(Socket.AF_INET, Socket.SOCK_STREAM)

    def run(self):
        self.__socket.bind((self.host, self.port))
        while self.__run_allowed:
            connection, address = self.__socket.accept()
            request = connection.recv(1024).decode("utf-8")
            webpage = request.split(' ')[1].split('?')[0].lstrip('/')
            docInfo = self.__getDocumentInfoTuple__(webpage)
            header = self.__generateHTTPResponseHeader__(docInfo[1], docInfo[2])
            connection.send(header + docInfo[0])

    def __getDocumentInfoTuple__(self, page):
        html = None
        return_code = 200
        content_type = "text/html"
            with open(page) as file:
                html = str.encode(file.read())
            with open("404.html") as file:
                html = str.encode(file.read())
                return_code = 404
            print("Failed to find requested page!\nDefaulting to PageNotFound.html...")
        if page.endswith(".html"):
            content_type = "text/html"
        elif page.endswith(".css"):
            content_type = "text/css"
        elif page.endswith(".js"):
            content_type = "text/javascript"
        return (html, return_code, content_type)

    def __generateHTTPResponseHeader__(self, HTTP_response_code, content_type):
        header = b"HTTP/1.1 " + str.encode(str(HTTP_response_code)) + str.encode(self.__HTTP_response_codes[HTTP_response_code]) + b"\r\n"
        header += b"Content-Type: " + str.encode(content_type) + b"; Encoding: UTF-8\n\n"
        return header

def main(`enter code here`):
    server = Server("", 8080)

if __name__ == "__main__":
  • 1
    \$\begingroup\$ Django and Flask are no web servers, they are frameworks for writing web applications. It is not clear what your exact intention is with the web server so that it is hard to say how it can be improved. But some obvious deficiencies are that you don't really follow the HTTP standard (\n vs \r\n), don't deal properly with requests larger than 1024 bytes, cannot deal with POST, cannot deal with HTTPS, cannot handle more than one connection at a time, no support for keep-alive .... But these might be mostly intentional limitations to keep it simple - only you don't say so. \$\endgroup\$ – Steffen Ullrich Feb 2 '19 at 19:59
  • \$\begingroup\$ I'm wanting to be able to use forms and really just do many of the things that django and flask can do. Sorry for the mistake about them being web servers. I relize that now and have fixed it. \$\endgroup\$ – That_one_guy Feb 2 '19 at 20:04
  • \$\begingroup\$ This is an ambitious goal and there as a long way to go from what you currently have. I suggest you have a look at the source code of http.server for a start and try to understand how it works internally. But note that even http.server is only suitable as a low performance test server, so if you need performance you need to learn from even more complex servers. \$\endgroup\$ – Steffen Ullrich Feb 2 '19 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.