如何在Python中解析HTTP请求(自定义Web服务器)

2024-10-01 11:38:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python创建一个多线程web服务器。我已经设法使它能够处理基本文本,但是我在适应HTTP时遇到了困难。在

它在发送GET请求时也会崩溃,但在仅使用“connect”时不会崩溃。我没有正确设置服务器吗本地主机:端口?在

但是,主要问题是我有一个客户机套接字,但我不知道如何从中提取请求数据。在

#! /usr/bin/env python3.3
import socket, threading, time, sys, queue

#initial number of worker threads
kNumThreads = 50

#queue of all the incoming requests
connections = queue.Queue(-1)


class Request_Handler(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while(True):
            #Get the request socket data from the queue
            global connections
            self.connection = connections.get()
            self.addr = self.connection[1]
            self.socket = self.connection[0]

            #I have the socket, but how do I parse the request from here?
            #Also is there a better way to respond than to manually create a response here?

            self.response = 'HTTP/1.1 200 OK/nContent-Type: text/html; charset=UTF-8/n/n <html><body>Hello World</body></html>'
            print("got here")
            self.socket.send(self.response.encode('utf-8'))
            self.socket.close()
            requests.task_done()


#creates kNumThreads threads that will handle requests
def create_threads():
    for n in range(0, kNumThreads):
       RH = Request_Handler()
       RH.start()

def main():
    s = socket.socket()
    port = int(sys.argv[1])

    #sets up the server locally
    s.bind(('127.0.0.1', port))
    s.listen(100)

    #create the worker threads   
    create_threads()

    #accept connections and add them to queue
    while(True):
        c, addr = s.accept()
        connections.put_nowait((c, addr))

if __name__ == '__main__':
    main()

Tags: thetoselfherequeuedefcreatesocket