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

标签 python http request

我正在尝试用 Python 创建一个多线程 Web 服务器。我已经设法让它与基本文本一起工作,但我在将它适应 HTTP 时遇到了问题。

它在发送 GET 请求时也会崩溃,但在仅使用“connect”时不会崩溃。我没有在 localhost:port 上正确设置服务器吗?

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

#! /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()

最佳答案

您需要像这样从连接接收数据:

while(True):
    c, addr = s.accept()
    data = c.recv(1024)
    print(data)
    connections.put_nowait((c, addr))

请参阅 HTTP 规范以了解如何读取请求

http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4

关于python - 如何在 python 中解析 HTTP 请求(自定义 Web 服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18606211/

相关文章:

python - Pycharm 中的 Jupyter Notebook 身份验证 token

python - 如何在模拟类的对象上定义任意属性?

http - 通过 HTTP POST 发送哪些特定数据可能会导致 HTTP 504 错误?

android - 如何从浏览器 Activity 中获取 http 响应代码?

go - 使用 POSTMAN 访问 FormValue Golang 中的 POST 请求值

swift - Alamofire 多次请求迭代

python - PIL.Image模块中各种图像缩放算法有什么区别?

python - 如何从 http.client.HTTPResponse 对象中获取 URL?

c# - .NET 中的轻量级 HTTP 服务器库

Laravel 5.4 表单请求唯一验证: how to access id?