Python Socket Raw HTTP 服务器发送图像问题

Python Socket Raw HTTP server sending image problem

提问人:Mertcan Bilek 提问时间:11/18/2023 最后编辑:Remy LebeauMertcan Bilek 更新时间:11/18/2023 访问量:43

问:

我尝试发送像HTML和CSS文档一样的图像。在开发人员控制台上,它似乎是成功的,但是当我想在我的网页上看到它时,它似乎不起作用。它们未正确发送。

第一张图片:

first image

第二张图片:

second image

开发者控制台:

developer console

实际的第一张图片:

actual first image

def handle_response(request_data):

    method, path, protocol = request_data.split("\r\n")[0].split(" ")
    print(method)
    print(path)
    print(protocol)

    if path == "/":
        file_path = "website" + path + "index.html"
    else:
        file_path = "website" + path

    print(file_path)

    if os.path.exists(file_path):
        with open(file_path, "rb") as response_file:
            response_content = response_file.read()

        response_type, _= mimetypes.guess_type(file_path)
        if "text" in response_type:
            response = f"HTTP/1.1 200 OK\r\nContent-Type: {response_type}\r\n\r\n{response_content.decode('utf-8')}"
        elif "image" in response_type:
            print(response_type)
            response = f"HTTP/1.1 200 OK\r\nContent-Type: {response_type}\r\n\r\n{response_content}"

    else:
        response = "HTTP/1.1 404 Not Found\r\n\r\n<h1>404 Not Found</h1>"

    return response
Python HTTP 套接字 服务器

评论

1赞 President James K. Polk 11/18/2023
完全不可读。
0赞 erik258 11/18/2023
格式化代码的简单方法是三重反引号。代码块前后的 ''' 行,您不需要弄乱缩进
0赞 Steffen Ullrich 11/18/2023
请举一个更完整的例子。目前尚不清楚handle_response的实际使用方式。
0赞 Remy Lebeau 11/18/2023
您没有显示您正在查询的 URL,也没有显示语句的任何输出。此外,您的 HTTP 响应不完整。至少,您应该包括其中。printContent-Length
0赞 Kurtis Rader 11/18/2023
不要尝试编写原始 HTTP 内容。有许多“龙在这里”的陷阱,例如没有正确逃避价值观。始终使用适当的库(即抽象)。

答: 暂无答案