J
J
jallvar2018-02-12 19:27:41
Python
jallvar, 2018-02-12 19:27:41

Python tornado how to make responses asynchronous?

Hi everyone, please advise. I am writing a WebSocket server on Tornado.
The algorithm is as follows:
-A person connects to the server
-Sends to the message - parameters {param1: 1, param2: 2}
-The server, based on these parameters from the database, issues responses, i.e., something like a live tape. Every 10 seconds in an infinite loop with time.sleep sends results. And everything is fine, but in this mode it works only with 1 client.
If, simply, close the tab, then the connection hangs. And the server is not accepting new messages

class capitalizationHandler(Handler.WebSocketHandler): #Наследую от измененного Handler'a Tornado (Ничего там интересного, просто, уменьшил код
    @tornado.web.asynchronous
    def on_message(self, message):

        while True:
            response = requests.get(url) #Через reuquests, да-да, простите меня

            if response.status_code != 200:
                self.write_message(u"bad parameters #3")
                print(url)
                break

            self.write_message(response.content)

            time.sleep(Config.script2Pause) #Config.script2Pause = 10 сек

if __name__ == '__main__':
    ws_app = Application()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(8808)
    tornado.ioloop.IOLoop.instance().start()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-12
@jallvar

time.sleep()is a blocking operation. You cannot block asynchronous code. Use yield gen.sleep(Config.script2Pause).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question