Search code examples
pythonhtmllocalserver

data show into html file with python local server


I've a simple local server with python where contains 2 variable and these variable's data i want to access into a index.html file.

My Code

from http.server import HTTPServer, BaseHTTPRequestHandler

ulta_palta_list = ['Pagla', 'Janina', 'Bangladesh']
name = "someone"

class DataHeadServer(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), DataHeadServer)
httpd.serve_forever()
print("Server Running")

Here ulta_palta_list and name variable i wanto access under index file such like as django framework.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
<h1>Hello, Python</h1>
</body>
</html>

Socket is better for this? Thanks


Solution

  • So you have the contents of index.html as a string in a variable named file_to_open (which I would recommend renaming, btw.) then you can use placeholders within index.html. ex.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Home</title>
    </head>
    <body>
    <h1>Hello, Python</h1>
    <p>the list = {ulta_palta_list}</p>
    <p>the name = {name}</p>
    </body>
    </html>
    

    then use str.format prior to writing it out

    file_to_open = file_to_open.format(ulta_palta_list=ulta_palta_list, name=name)