def order_pubsub()

in services/order-async/main.py [0:0]


def order_pubsub():
    envelope = request.get_json()
    if not isinstance(envelope, dict) or 'message' not in envelope:
        return error500()
    message = envelope['message']
    if 'data' not in message or 'attributes' not in message:
        return error500()
    attributes = message['attributes']
    if 'event_id' not in attributes or 'event_type' not in attributes:
        return error500()

    check_result = json.loads(base64.b64decode(message['data']).decode('utf-8'))
    event_id = attributes['event_id']
    event_type = attributes['event_type']

    query = ds_client.query(kind='ProcessedEvent')
    query.keys_only()
    query.add_filter('event_id', '=', event_id)
    if list(query.fetch()): # duplicate
        print('Duplicate event {}'.format(event_id))
        return 'Finished.', 200

    if event_type != 'order_checked':
        print('Unknown event type {}.format(event_type)')
        return 'Finished.', 200

    customer_id = check_result['customer_id']
    order_id = check_result['order_id']
    accepted = check_result['accepted']

    query = ds_client.query(kind='Order')
    query.add_filter('customer_id', '=', customer_id)
    query.add_filter('order_id', '=', order_id)
    order = None
    for result in query.fetch(): # This should return a single entity.
        order = result
        break
    if order is None: # Non existing order
        return error500()

    with ds_client.transaction():
        if accepted:
            order['status'] = 'accepted'
        else:
            order['status'] = 'rejected'
        ds_client.put(order)

        incomplete_key = ds_client.key('ProcessedEvent')
        entity = datastore.Entity(key=incomplete_key)
        entity.update({
            'event_id': event_id,
            'timestamp': datetime.datetime.utcnow()
        })
        ds_client.put(entity)

    return 'Finished.', 200