I was creating my python web server that would take the html file in the current directory called "index", read the code and send it as a response, but I saw that when I wanted to display an image, it didn't work, can someone help me please ?
#server.py
import socket
port = 8080
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind(('', port))
listen_socket.listen(1)
print 'Serving on port '+str(port)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print request
response = """\
HTTP/1.1 200 OK
Content-type:text/html\r\n\r
"""
f = open("index.html", 'r')
content = f.read()
client_connection.sendall(response+content)
client_connection.close()
and here is the html code I would like to display
<!--index.html-->
<html>
<body>
<p>image:</p>
<img src="img.jpg" />
</body>
</html>
it would also be preferable if it was possible to do without getting the images directly from urls. Thank you in advance.
Image is not getting rendered because you are not sending that image you are just sending the html page.
You need to identify the request and send resources according to that. I tried to tweak in your code. It is displaying my image correctly.
# server.py
import socket
port = 8080
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind(('', port))
listen_socket.listen(1)
print 'Serving on port ' + str(port)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
print request
if request.split()[1] == '/':
headers = ("HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"\r\n")
f = open("index.html", 'r')
elif request.split()[1] == '/img.jpg':
headers = ("HTTP/1.1 200 OK\r\n"
"Content-Type: image/jpeg\r\n"
"\r\n")
f = open("img.jpg", 'r')
content = f.read()
client_connection.sendall(headers + content)
client_connection.close()
Look at some web frameworks like Django, Flask etc if you want to serve more than just one page.