python - SimpleHTTPServer 和 SocketServer

标签 python python-2.7 socketserver simplehttpserver

我创建了一个“处理程序”python 脚本,如下所示:

import SimpleHTTPServer
import SocketServer

PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "Serving at port:", PORT
httpd.serve_forever()

我还有一个 javascript 函数,它向服务器发送一个 URL 请求信息。这一切都很好,当我运行我的处理程序脚本,然后运行我的 javascript 时,我可以在终端中看到来自 JS 的所有数据:

localhost.localadmin - - [20/Feb/2013] "GET /?var=data/ HTTP/1.1" 200 -

我想做的是能够从我的处理程序脚本访问这些数据,理想情况下是这样的:

data = httpd.server_forever()  #How do I do somethign like this

我如何完成这样的事情?

最佳答案

您可以像这样继承 SimpleHTTPServer.SimpleHTTPRequestHandler:

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  def do_GET(self):
      # Your code here
      print "Client requested:", self.command, self.path

      SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

PORT = 8000

httpd = SocketServer.TCPServer(("", PORT), MyHandler)

print "Serving at port:", PORT
httpd.serve_forever()

这将在控制台打印:

Client requested GET /?var=data/

查看 SimpleHTTPRequestHandler 上的文档和 BaseHTTPRequestHandler获取更多信息。

关于python - SimpleHTTPServer 和 SocketServer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14984401/

相关文章:

python - Python 中的打字效果

python - 不支持的格式字符?

python - 函数接受表示十进制数字的字符串并以二进制格式返回它

python更改UDPServer中的最大限制接收缓冲区

python - 希望在 Python 中模拟 socat 的功能

python - 为什么指定end关键字时python3的print语句不刷新输出?

python - 通过 groupby 建立开始/结束日期

python - pymongo $set 子文档数组

python - Pandas - 搜索术语(无论搜索术语的大小写)

python - 无法在 SocketServer.TCPServer 中重用套接字