【问题标题】:Python web server using other classes使用其他类的 Python Web 服务器
【发布时间】:2014-10-23 18:25:30
【问题描述】:

我正在为我的树莓派开发一个 python 应用程序。这个软件的目的是监听另一个软件的 POST,当我收到 POST 时,我想通过连接到树莓的 zigbee 模块发送消息。

我的问题是我如何在 python 中为树莓派实现网络服务器,我无法访问能够通过 zigbee 发送消息的类。

[更新] 为了更清楚,我的问题是我无法在 do_POST 方法中访问 wsanProtocol。所以我的界面不能用于 xbee。

你能给我一些关于如何做的想法吗?

这是我的网络服务器的代码:

class webServer(threading.Thread):    
    def __init__(self, serverAddress, port, wsanProtocol):
        self.wsanProtocol = wsanProtocol
        self.serverAddress = serverAddress

    self.port = port
    self.serverRunning = True
        threading.Thread.__init__(self)

    def run(self):
        server_class = BaseHTTPServer.HTTPServer        
        httpd = server_class((self.serverAddress, self.port), MyHandler)
        print time.asctime(), "Server Starts - %s:%s" % (self.serverAddress, self.port)
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            pass
        httpd.server_close()
        print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_HEAD(s):
        s.send_response(200)
        s.send_header("Content-type", "text/html")
        s.end_headers()
    def do_GET(s):
        """Respond to a GET request."""
        if None != re.search('api/v1/nodo/*', s.path):
            nodeID = s.path.split('/')[-1]
            print 'Solicitando informacion del nodo '+nodeID
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            #Prepare JSON with node information        
            #jsonnode = json.dumps(nodeOjbect.__dict__)
            jsonnode = '{ "mac":'+nodeID+', "bat":4.0 }'
            s.wfile.write(jsonnode)        
        if None != re.search('api/v1/st_act/*', s.path):
            nodeID = s.path.split('/')[-1]
            print 'Solicitando informacion del actuador '+nodeID
            s.send_response(200)
            s.send_header("Content-type", "text/html")
            s.end_headers()
            #Prepare JSON with node information        
            #jsonnode = json.dumps(nodeOjbect.__dict__)
            jsonnode = '{ "mac":'+nodeID+', "status":"off" }'
            s.wfile.write(jsonnode)

    def do_POST(self):
        print "ejecutando POST"
        if None != re.search('api/v1/act/*', self.path):
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            if ctype == 'application/json':
                length = int(self.headers.getheader('content-length'))
                data = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
                print data
                req = json.loads(data.keys()[0])
                resCommand = None
                #Cant get access to my wsanProtocol!!
                #webServer.wsanProtocol.executeCommand(10, resCommand, req.tolist())
                print 'Actuacion sobre el nodo ' + req["mac"]
                self.send_response(200)

非常感谢!

【问题讨论】:

  • 你已经发布了很多不相关的代码,但没有说到底是什么问题。当您尝试调用 zigbee 时会发生什么?
  • 不要认为这无关紧要,我正在尝试以 do_POST 方法访问 webServer。当我这样做时,python 失败,告诉我 wsanProtocol 没有 executeCommand 过程。
  • 尝试一步一步地推进可测试,而不是构建整个东西,然后发现它不能完全工作。首先,测试你可以做wsanProtocol.executeCommand(10, something, somethingelse)。然后测试您是否让 Web 服务器正常工作,例如,通过添加调试日志记录。
  • 不确定我是否正确 Anton,我已经在另一个基于套接字的服务器中测试了 executeCommand,它可以正常工作。并且网络服务器本身(不调用 executeCommand)也运行良好......问题是无法弄清楚如何在 do_POST 中使 wsanProtocol 可访问

标签: python webserver xbee


【解决方案1】:

wsanProtocol 是服务器实例的属性,而不是类的属性。您可以通过self.server 访问该实例,如BaseHTTPRequestHandler docs 所示。

【讨论】:

  • 非常感谢丹尼尔,我尝试了以下调用:self.server.wsanProtocol.executeCommand(10, resCommand, req.tolist()) 但收到错误消息:AttributeError: HTTPServer instance has no属性 'wsanProtocol' 我想我做错了什么......
  • 好的,我看到 wsanProtocol 实际上是线程的一个参数。但是你能解释一下你为什么要打扰线程,因为你只听一个 POST 吗?有什么意义?
  • 是的,你是对的,我可以避开这个话题。问题是我原来的服务器是基于套接字的,我需要一个线程,所以我可能没有意识到。
猜你喜欢
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
  • 2017-09-25
  • 2012-12-06
相关资源
最近更新 更多