How to create a local server in python and host website


Hey Guys! In this tutorial, we will learn how to create a local server and host a website on it. We know that every file available there on the internet is hosted on the server. While setting up a web development environment we generally use localhost, but there are many problems with the localhost and we need a third party application or software to set up that. We will learn how we can simply write a few lines of code and create our own local server to set up a web development environment. Let’s get started with it…




Writing Python code for creating a local server:-
from http.server import HTTPServer, BaseHTTPRequestHandler

class Serv(BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path == '/':
            self.path = '/index.html'
        try:
            file_to_open = open(self.path[1:]).read()
            self.send_response(200)
        except:
            file_to_open = "File not found"
            self.send_response(404)
        self.end_headers()
        self.wfile.write(bytes(file_to_open, 'utf-8'))

httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()


Here we used port 8080 to interact with our server. If you have any doubts about code please feel free to ask in the comment section. Now let’s create an HTML file and host it in this local server.

HTML File Code:

<html>
    <head>
        <title>TharVid- Local Server Using Python</title>
    </head>
    <body>
        <h1>loves contributing to ScoreLab.</h1>
    </body>
</html>

Note:- Don’t forget to name your HTML file as index.html as a server in python with automatically find this page as a Home page of your website either it will list the directory and you will have to open the file manually.

Congrats! You are now ready with code. Now run your program and open the localhost URL with a specified port in your browser, it will open your website.

In this tutorial, localhost browser will look like http://localhost:8080

You can find code given here on GitHub Here

Hope you enjoyed this tutorial, visit our site for regular updates and comment below if you find this tutorial useful. Thank You!


2 تعليقات

إرسال تعليق
أحدث أقدم