如何在Python套接字应用程序中接受GET请求?

时间:2012-04-12 06:34:06

标签: python http sockets webserver

我正在编写一个非常基本的Web服务器作为家庭作业,我在localhost端口14000上运行。当我浏览到localhost:14000时,服务器发回一个带有表单的HTML页面(表单的动作是相同的地址 - localhost:14000,不确定是否正确)。

基本上我希望能够在提交后重新加载页面时从GET请求中收集数据 - 我该怎么做?我如何才能访问GET中的内容?

注意:我已经尝试过socket.recv(xxx),如果第一次加载页面则不起作用 - 在这种情况下,我们不是从客户端“接收”任何东西,所以它只是继续旋转。

1 个答案:

答案 0 :(得分:2)

秘密在于conn.recv,它将为您提供请求的浏览器/客户端发送的标头。如果它们看起来像我使用safari生成的那个,你可以很容易地解析它们(即使没有复杂的正则表达式模式)。

    data = conn.recv(1024)
    #Parse headers
    """
    data will now be something like this:

    GET /?banana=True HTTP/1.1
    Host: localhost:50008
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.53.11 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-us
    Accept-Encoding: gzip, deflate
    Connection: keep-alive

    """
    #A simple parsing of the get data would be:
    GET={i.split("=")[0]:i.split("=")[1] for i in data.split("\n")[0].split(" ")[1][2:].split("&")}