Server http displays a variable from .txt with python

Viewed 574

I would like to make a HTTP request (PYTHON) with a web server that displays a data from a .txt file.

I have this data1.txt file that contains:

bonjour

and here is my code webserver.py:

#!/usr/bin/python
from http.server import BaseHTTPRequestHandler,HTTPServer
    
class myHandler(BaseHTTPRequestHandler):
    def do_GET(self):

        ###############################

        File = open('data1.txt',"r")
        if(File == None):
            print("File Not Found..")
        else:
            while(True):
                # extracting data from records 
                record = File.readline()
                if (record == ''): break
        File.close()

        ###############################


        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        self.wfile.write(
            b"Hello from <b>Raspberry Pi</b> running <b><i>Python</i></b>")
        self.wfile.write(
            b"<a href='http://helloraspberrypi.blogspot.com'>Hello Raspberry Pi</>")
        self.wfile.write(
            b"$record" )
        return

try:
    server = HTTPServer(('localhost', 8080), myHandler)
    print ('HTTPServer started')
    server.serve_forever()
    
except KeyboardInterrupt:
    print ('server.socket.close()')
    server.socket.close()

I would like to display bonjour thanks to the following line self.wfile.write(b"$record" ) from the variable record which corresponds to bonjour: record = File.readline() = bonjour

My issue is that I don't know how to call the variable, I tried with $record but it's not working.

2 Answers

The solution is to split the .txt file (variable data) and then to encode it:

#!/usr/bin/python
from http.server import BaseHTTPRequestHandler,HTTPServer

class myHandler(BaseHTTPRequestHandler):
    def do_GET(self):

         ###############################

         File = open('data1.txt',"r")
         if(File == None):
             print("File Not Found..")
         else:
             while(True):
                 # extracting data from records 
                 record = File.readline()
                 print(record.encode())
                 if (record == ''): break
                 data = record.split()
                 print("data:",data[0].encode())

         File.close()

         ###############################


         self.send_response(200)
         self.send_header('Content-type','text/html')
         self.end_headers()
         self.wfile.write(
        "<h1>".encode() + data[0].encode() + "</h1>".encode())
         return

try:
    server = HTTPServer(('localhost', 8080), myHandler)
    print ('HTTPServer started')
    server.serve_forever()

except KeyboardInterrupt:
    print ('server.socket.close()')
    server.socket.close()

Thank you for your help!

First note that the documentation recommends against this approach:

Warning: http.server is not recommended for production. It only implements basic security checks.

Something like Flask is just as easy, and a little more typical for production use. Anyway, continuing with your use of http.server:

  • You're not actually serving text content; you're serving HTML content, so rename your .txt file to .html
  • Consider using a different handler, namely SimpleHTTPRequestHandler, that serves content from the filesystem directly
  • Move your Hello (etc.) to the .html

You've also misconstrued how file operations work in Python when the file is not found. This is not going to work:

        if(File == None):
            print("File Not Found..")

because on failure, open does not return None; it raises an exception.

For your record reference the fix should be just

self.wfile.write(record.encode())

You also need to drop your read-loop; currently this:

if (record == ''): break

is guaranteeing that your shown record will be a blank string. Instead, just do a single file.read() and show the works, rather than reading line by line.

Related