图片无法在基于 python 的网络服务器上加载

Image won't load on python-based webserver

我构建了一个简单的 Web 服务器,它可以获取请求并发送响应。因此,当服务器收到无效请求时,如 "localhost/not-a-page",服务器将发送包含 HTML 文件内容的响应“404.html”,网页应显示图像。到目前为止,还不错。

但是404页面加载时,页面找不到图片。 HTML 部分是正确的,可以离线使用。我试图将图像移动到多个位置,相对于 Python 脚本,相对于 HTML。但它就是找不到。嗨,我正在努力使服务器尽可能低级,我想了解服务器的工作原理。所以我没有使用任何与服务器相关的库。我只使用 Python.

的套接字库

我将不胜感激在不使用其他库的情况下解决此问题的任何帮助,

编辑 这是相关的 Python 部分:

import socket

import threading

import os



default_error_page = """\

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

<title>Error response</title>

</head>

<body>

<center>

<h1>Response</h1>

<p>Error code: %(code)d</p>

<p>Message: %(status)s.</p>

</center>

</body>

</html>

"""


default_header_status = "HTTP/1.1 %(code)d %(status)s\r\n"

default_header_content_type = "Content-Type: text/html; charset=utf-8\r\n\r\n"

buffer_size = 1024



def get_page(code):

    page = default_error_page

    if code == 200:

        pass

    else:

        file = open(os.path.dirname(__file__) + "/www/not-found.html", 'r')

        page = file.read()

    return page


class BaseServer:


    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_name = ""

    host_name = ""

    host_port = 8000 # default port

    is_shutdown = False


    def __init__(self, name):

        self.server_name = name


    def start_server(self):

        thread = threading.Thread(target=self.run_server(), name=self.server_name)

        thread.start()


    def run_server(self):

        self.server_socket.bind((self.host_name, self.host_port)) # bind to host

        self.server_socket.listen()

        while not self.is_shutdown:

            conn, addr = self.server_socket.accept()

            self.handle_request(conn, addr)


    def handle_request(self, connection, address):

        print(str(address[0]) + " Connected! (port " + str(address[1]) + ")")

        result = self.parse_request(connection.recv(buffer_size))

        if result == 0:

            page = self.parse_response(200)

        else:

            page = self.parse_response(404)

        connection.sendall(bytes(page))


    def parse_request(self, data):

        if len(data) == 0:

            return

        strings = str(bytes(data).decode('utf-8')).split('\r\n')

        command, path, version = strings[0].split()

        print("command - " + command)

        print("path - " + path)

        print("version - " + version)


        status = 1


        if path == "/":

            status = 0


        return status


    def parse_response(self, code):

        status = "ERROR"

        if code == 200:

            status = "OK"

        elif code == 404:

            status = "NOT FOUND"


        base_header = (default_header_status % {'code': code, 'status': status})

        base_content_type = default_header_content_type

        # page = (default_error_page % {'code': code, 'status': status})

        page = str(get_page(code))

        return_string = str(base_header + base_content_type + page).encode('utf-8')

        print(return_string)

        return return_string



def main():

    server = BaseServer("Home Server")

    server.start_server()




if __name__ == "__main__":

    main()

这是 HTML:

<html>


<head>

<link rel="stylesheet" type="text/css" href="/style/main.css"/>

<style>

    *{

    padding:0;

    margin:0;

}

body{

    background-color:#ffe6b3;

}

h1{

    margin-top:30px;

    background-color:#ffcc66;

    font-size:3em;

    display:inline-block;

    color:#3a0000;

}

p{

    margin-top:80px;

    font-size:2em;

    color:#3a0000;

}

#img404{

    background-image:url(../images/404.gif);

    width:100%;

    height:50%;

    background-repeat:no-repeat;

    background-position:center 20%;

}

</style>

</head>


<body>

    <center>

        <div class=top>

            <h1>ERROR 404</h1>

        </div>

        <p>

         Sorry, we could not find the page :(

        </p>

        <div id="img404">


        </div>

    </center>

</body>


</html>

对不起,如果它不是很可读,但我在 phone。

迪马

不要像../images/img.gif那样对图像使用相对路径。而是使用相对于根的完整 url 或 url。

解决了我的问题。 看到日志后,我意识到浏览器发送了另一个图像请求。 愚蠢的我,我的代码是:

if path ="/":
    status = 0
else:
    status = 1

所以对于每个不是 root("/") 的请求,服务器都会 return 404。

哎呀