【问题标题】:Python Web Server HTML RenderingPython Web 服务器 HTML 渲染
【发布时间】:2014-11-03 02:00:37
【问题描述】:

我正在构建一个 Python Web 服务器并需要它来呈现 HTML 元素。到目前为止,该程序是通过aj@ubuntu: ./server.py --base=home/website/html/ --port=8080 实现的,然后在网络浏览器中连接到 URL http://localhost:8080/index.html。然而,该网页上唯一显示的是HTTP/1.1 200 OK,这很好,因为这意味着我能够连接到服务器。我现在需要的是能够呈现 HTML、CSS 和相应 Javascript 组件的内容的浏览器。有什么建议么?我一直在绞尽脑汁想弄清楚如何做到这一点。

我在下面包含了我的代码:

import socket
import sys
if not sys.version_info[:2] == (3,4):
 print("Error: need Python 3.4 to run program")
 sys.exit(1)
else:
 print("Using Python 3.4 to run program")
import argparse

def main():

parser = argparse.ArgumentParser(description='Project 1 Web Server for COMP/ECPE 177')
parser.add_argument('--version', help='Show program\'s version number and exit')
parser.add_argument('--base', action='store', help='Base directory containing website', metavar='/path/to/directory')
parser.add_argument('--port', action='store', type=int, help='Port number to listen on', metavar='####')
args = parser.parse_args()
#parser.print_help()
#print(args.port, args.base)


# Create TCP socket
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error as msg:
    print("Error: could not create socket")
    print("Description: " + str(msg))
    sys.exit()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Bind to listening port
try:
    host=''  # Bind to all interfaces
    s.bind((host,args.port))
except socket.error as msg:
    print("Error: unable to bind on port %d" % args.port)
    print("Description: " + str(msg))
    sys.exit()

# Listen
try:
    backlog=10  # Number of incoming connections that can wait
                # to be accept()'ed before being turned away
    s.listen(backlog)
except socket.error as msg:
    print("Error: unable to listen()")
    print("Description: " + str(msg))
    sys.exit()    

print("Listening socket bound to port %d" % args.port)

while 1:
# Accept an incoming request
    try:
        (client_s, client_addr) = s.accept()
        # If successful, we now have TWO sockets
        #  (1) The original listening socket, still active
        #  (2) The new socket connected to the client
    except socket.error as msg:
        print("Error: unable to accept()")
        print("Description: " + str(msg))
        sys.exit()

    print("Accepted incoming connection from client")
    print("Client IP, Port = %s" % str(client_addr))

    # Receive data
    try:
        buffer_size=4096
        raw_bytes = client_s.recv(buffer_size)
    except socket.error as msg:
        print("Error: unable to recv()")
        print("Description: " + str(msg))
        sys.exit()

    string_unicode = raw_bytes.decode('ascii')
    print("Received %d bytes from client" % len(raw_bytes))
    print("Message contents: %s" % string_unicode)

    request = str.split(string_unicode)
    #print(request)
    hcmd = request[0]
    filep = request[1]
    protocol = request[2]
    print(filep)

    if filep == '/':
        filep = '/index.html'

    if hcmd == 'GET':
        dest_file = None
        try:
            try:
                dest_file = open(args.base + filep, 'rb')
            except (OSError, IOError) as msg:
                msg = 'HTTP/1.1 404 Request Not Found\r\n\r\n'
                statcode = 1 #404 request not found
                rb1 = bytes(msg, 'ascii')
                client_s.sendall(rb1)

            message_send = 'HTTP/1.1 200 OK\r\n\r\n'
            statcode = 0 #200 OK
            rb2 = bytes(message_send, 'ascii')
            client_s.sendall(rb2)

            if dest_file is not None:
                datasend = dest_file.read()
                client_s.sendall(datasend)
                dest_file.close()
            print(dest_file)
            print(statcode)

        except socket.error as msg:
            msg2 = "Error: "
            sys.exit()

    else:
        message_send = 'HTTP/1.1 501 Not Implemented\r\n\r\n'
        statuscode = 2 #501 not implemented
        rb3 = bytes(message_send, 'ascii')
        client_s.sendall(rb3)
    client_s.close()

#Close both sockets
try:
   s.close()
except socket.error as msg:
   print("Error: unable to close() socket")
   print("Description: " + str(msg))
   sys.exit()

print("Sockets closed, now exiting")

if __name__ == "__main__":
 sys.exit(main())

【问题讨论】:

    标签: javascript python html css sockets


    【解决方案1】:

    您的服务器中是否存在“home/website/html/index.html”?我试过你的代码。访问现有文件时,它工作正常。但是对于提供不存在的文件,您的代码中有一个错误。发送文件内容的代码应该在最里面的'try'块内:

    try:
        dest_file = open(args.base + filep, 'rb')
    
        #---------Should be put here-----------
        message_send = 'HTTP/1.1 200 OK\r\n\r\n'
        statcode = 0 #200 OK
        rb2 = bytes(message_send, 'ascii')
        client_s.sendall(rb2)
    
        if dest_file is not None:
            datasend = dest_file.read()
            client_s.sendall(datasend)
            dest_file.close()
        print(dest_file)
        print(statcode)
        #--------------------------------------
    
    except (OSError, IOError) as msg:
        msg = 'HTTP/1.1 404 Request Not Found\r\n\r\n'
        statcode = 1 #404 request not found
        rb1 = bytes(msg, 'ascii')
        client_s.sendall(rb1)
    

    另外,如果不是为了学习,使用socket搭建web服务器实在是太低级了。你有很多额外的工作要做,例如手动编写常见的 http 标头。尝试一些更高级别的库/框架,例如

    【讨论】:

    • 该位置和文件确实存在,我尝试在我的计算机上处​​理其他几个位置,但结果仍然相同。这是一个类项目,这就是我使用套接字模块的原因。我们被明确告知不要在这个项目中使用 http.client、http.server、socketserver 或 urllib 模块。
    • print(dest_file)的输出是什么
    • 它打印出“/index.html”或我指定的任何文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多