M
M
Max Payne2018-03-14 12:18:11
Python
Max Payne, 2018-03-14 12:18:11

When and how to properly use Python's asynchronous features?

I've already read several dozen manuals - it won't reach me in any way:
1) When should yield be used in Tornado coroutines? At the moment, all my code works without them (that is, as far as I understand, synchronously). As an example, I will give this class:

class http_cb(tornado.web.RequestHandler):
    bots = {}

    def msg_to_event(self, cb): return (cb.get('id'), cb.get('date'), cb.get('user_id'), cb.get('user_id'), cb.get('body'), cb.get('attachments'))

    def md5(self, s): return md5(str(s).encode('utf-8')).hexdigest()
    
    @gen.coroutine
    def post(self, *args, **kwargs):
        bot_name, key = args
        if bot_name not in self.bots.keys(): self.write('bot not in bots list')
        else:
            POST = tornado.escape.json_decode(self.request.body)
            if self.md5('{}:{}'.format(bot_name, POST['group_id'])) != POST['secret']: self.write('invalid secret')
            else:
                if (POST['type'] == 'confirmation'): self.write(key)
                else:
                    if (POST['type'] == 'message_new') and (POST['object']['out'] == 0): r = self.bots[bot_name].f(self.msg_to_event(POST['object']))
                    if (POST['type'] == 'group_join'): r = {'peer_id': POST['object']['user_id'], 'message': 'Привет!'}
                    if (POST['type'] == 'group_leave'): r = {'peer_id': POST['object']['user_id'], 'message': 'Пока!'}
                    try:
                        if type(r) == dict:
                            self.bots[bot_name].send(r)
                            self.write('ok')
                    except Exception as e: print(e)

2) When in normal asynchronous programming should one use async before a function and await inside? When do certain types of actions (what?) occur?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question