在python中使用gevent的静态Web服务器演示

时间:2018-11-02 07:36:33

标签: python gevent

我的静态Web服务器演示在python中使用gevent时存在一些问题。当我的浏览器使用http://localhost:8080.It访问我的Web服务器时没有任何响应。如果我的静态Web服务器演示未使用gevent,则运作良好,gevent一定有问题。

#coding=utf-8
from socket import *
from gevent import monkey
import re
import gevent

monkey.patch_all()

def handle_client(client_socket):

    recv_data = client_socket.recv(1024).decode("utf-8")
    response_header_lines = recv_data.splitlines()
    for line in response_header_lines:
        print(line)

    http_request_line = response_header_lines[0]
    get_file_name = re.match("[^/]+(/[^ ]*)", http_request_line).group(1)
    print("file name is ===>%s"%get_file_name)  #for test

    if get_file_name == "/":
        get_file_name = DOCUMENTS_ROOT + "/index.html"
    else:
        get_file_name = DOCUMENTS_ROOT + get_file_name

    print("file name is ===2>%s"%get_file_name)

    try:
        f = open(get_file_name, "rb")
    except IOError:
        response_header = "HTTP/1.1 404 not found\r\n"
        response_header += "\r\n"
        response_body = "404 not found"
    else:
        response_header = "HTTP/1.1 200 OK\r\n"
        response_header += "\r\n"
        response_body = f.read()
        f.close()
    finally:
        client_socket.send(response_header.encode("utf-8"))
        client_socket.send(response_body)
        client_socket.close()

def main():

    server_socket = socket(AF_INET, SOCK_STREAM)
    server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    server_socket.bind(("", 8080))
    server_socket.listen(128)
    while True:
        client_socket, client_addr = server_socket.accept()
        #handle_client(client_socket)
        gevent.spawn(handle_client, client_socket)

    server_socket.close()

DOCUMENTS_ROOT = "./html"

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:2)

您应先应用猴子补丁 ,然后再导入将要修补的任何模块,socket在此处:

from gevent import monkey
monkey.patch_all()

from socket import *

...

its doc强调:

  

应在产品生命周期中尽早进行修补   程序。例如,主模块(针对   主要,否则将是第一次导入),最好以此代码开头,最好在其他任何导入之前