I
I
Ilya Flakin2017-03-01 11:56:55
Python
Ilya Flakin, 2017-03-01 11:56:55

How to respond to the client in the request handler and continue executing the code?

A small server on a tornado, an example of a request handler:

class MessageHandler(tornado.web.RequestHandler):

    @gen.coroutine
    def post(self):
        if self.request.body == 'aaa':
            self.write("Запрос получен")
            self.finish()
            MyFunc() # Функция которая может выполняться длительное время
        else:
            self.write("Неверный запрос")

When the condition is met, I answer the client that everything is fine, and so that the client does not wait for the completion of the request processing (which can be delayed by the MyFunc() function), I execute self.finish() - am I doing the right thing in this case?
The second question is about the MyFunc() function - it will execute requests to other services with saving information on the HDD, i.e. it is blocking. I understand that the server will not process the following requests until it completes, so there is a desire to put it in a separate thread, as described in this article https://habrahabr.ru/post/231201/ - is this the right idea?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tirael78, 2017-03-01
@Tirael78

1 To answer the client - "everything is fine" before the actual execution of the request - in principle, it is not correct. What if something goes wrong? and you have already told the client that everything is fine.
2 into a separate thread or a separate process? the correct answer depends on the type of operations performed, if you have complex calculations there, then the stream will not suit you, it is useful for I / O operations. Please note that the implementation of parallelism in windows and unix will be different.
in general, in essence, it’s right to make such decisions through the queue manager, they put synchronous tasks into a certain microservice, then you can ensure the persistence of tasks and give the correct answer to the user and not worry that the main thread will be blocked.
Well, to summarize, of course, I don’t know the reasons for choosing this technology, but now there is a ready-made implementation of asynchrony in python. I'm talking about asyncio, of course it won't get rid of blocking problems for you, but it will allow you to solve asynchrony issues in a more elegant way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question