Python新手,帮助循环



我有这个开源代码,用于响应web-socket请求:

_GOODBYE_MESSAGE = 'Goodbye'

def web_socket_do_extra_handshake(request):
    pass  # Always accept.

def web_socket_transfer_data(request):
while True:
    line = request.ws_stream.receive_message()
    if line == "hello":
        request.ws_stream.send_message("hello was sent")
    if line == "bye":
        request.ws_stream.send_message("bye was sent")
    if line is None:
        return
    #request.ws_stream.send_message(line)
    if line == _GOODBYE_MESSAGE:
        return

现在的问题是我想修改它(transfer_data方法),所以在while循环中,让我们说它检查字符串行,如果它等于某些文本,它应该返回别的东西给客户端,如果行等于别的东西,它应该返回一个不同的字符串。我已经尝试了很多,但它似乎不工作,我知道这是非常基本的,但可以有人请帮助我这个。我想做的另一件事是能够添加延迟响应说5秒,但导入时间不工作。我得到错误,请帮助这个

对于第一个问题,你可以直接输入

if line == "whatever":
   # do stuff here, return, whatever...
   request.ws_stream.send_message(line)
else:
   # do something else....

用于睡眠,您需要

 import time
 time.sleep(seconds)

如果"import time"行失败,说明你的python解释器配置有问题。

有关控制逻辑,请参阅Python文档(链接到2.7)。

注意你可以这样修改if结构:

def web_socket_transfer_data(request):
    while True: # This was at the wrong indent - check it was a copy-paste issue
        line = request.ws_stream.receive_message()
        if line is "hello":
            request.ws_stream.send_message("hello was sent")
        elif line is "bye": # elif is the Pythonic form of else if
            request.ws_stream.send_message("bye was sent")
        elif line is _GOODBYE_MESSAGE or line is None:
            break # This exits the while loop and by extension the method
        time.sleep(5)

至于time.sleep()的问题,您需要确保在文件的开头执行import time。如果这不起作用,您可能需要检查是否可以通过IDLE直接导入它。即运行IDLE并输入import time。如果失败,请发布返回的错误。

相关内容

  • 没有找到相关文章