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.
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!