Проблемы анализа на веб-прокси-сервере HTTPPython

Программы на Python
Anonymous
Проблемы анализа на веб-прокси-сервере HTTP

Сообщение Anonymous »

В упражнении на Python мне нужно разработать небольшой веб-прокси-сервер, способный кэшировать веб-страницы. Этому прокси-серверу нужно понимать только простые GET-запросы, но он способен обрабатывать все виды объектов, не только HTML, но и изображения. Ниже приведены мои коды:

Код: Выделить всё

# Proxy Server
from socket import *
import sys

# Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM)
serverName = '0.0.0.0'
serverPort = 8000
tcpSerSock.bind((serverName, serverPort))
tcpSerSock.listen(1)

while 1:
# Start receiving data from the client
print('Ready to server...')
tcpCliSock, addr = tcpSerSock.accept()
print('Received a connection from:', addr)
message = tcpCliSock.recv(1024).decode()
print(message)

# Extract the filename from the given message
filename = message.split()[1].partition("/")[2]
print(f"filename: {filename}")
fileExists = "False"

try:
# Check whether the file exist in the cache
f = open(filename, "r")
outputdata = f.readlines()
fileExists = "True"

# ProxyServer finds a cache hit and generates a response message
tcpCliSock.send(b"HTTP/1.0 200 OK\r\n")
tcpCliSock.send(b"Content-Type:text/html\r\n")

#############################################
for line in outputdata:
tcpCliSock.send(line)
print("Read from cache")

except IOError:
if fileExists == "False":
# Create a socket on the proxyserver
c = socket(AF_INET, SOCK_STREAM)
hostn = filename.replace("www.", "", 1).partition("/")[0]
print(f"hostn:{hostn}")
try:
c.connect((hostn, 80))
print("Successfully connected")
request_str = "GET /"+" HTTP/1.0\r\n\r\n"
c.sendall(request_str.encode())

buf_data = b""
# Read the response into buffer
while True:
data = c.recv(1024)
if not data:
break
buf_data += data

# Create a new file in the cache for the requested file
# Also send the response in the buffer to client socket and the corresponding file in the cache
tcpCliSock.send(buf_data)
# tcpCliSock.send("\r\n".encode())

# The use of tempFile?
# tempFile = open("./"+filename.replace("/", "_"), "wb")
# tempFile.write(buf_data)
except Exception as E:
print("Illegal request")
print(E)
else:
nf_header = "404 Not Found"
tcpCliSock.send(nf_header.encode())
tcpCliSock.close()

tcpSerSock.close()
sys.exit()
Ссылка, которую я использовал для тестирования этой программы: «http://127.0.0.1:8000/httpforever.com». Программа выше зависла, когда браузер запрашивает файл «favicon.ico». Ниже приведен вывод в консоли и (часть) выходного HTML-файла. В полном выходном html-файле загружаются все тексты и ссылки.
Изображение

Изображение

Я считаю, что вывод является желаемым, но программа не может завершить последний запрос, то есть запрос значка. Я считаю, что это связано с тем, что у меня нет правильного способа анализа переменной имени файла, чтобы сокет не мог подключиться к правильному хосту. Мой вопрос: как устранить ошибки getaddrinfo? Любые подсказки или помощь будут очень признательны.

Вернуться в «Python»