Ejemplo n.º 1
0
    def post(self):
        """ Parse a POST request to the /post endpoint and attempt to
        deserialize the request to an event object and persist to database

        :return: Success message to the user if no issues
        :rtype: str

        :raises SQLAlchemyError: If fails roll back transaction and return
            error message
        """
        jwt = parse_token(request)
        if(jwt['role'] is True):
            user_id = int(jwt['sub'])
        else:
            response = jsonify(
                message='You do not have permission to invoke this action')
            response.status_code = 401
            return response

        json_data = request.get_json()
        start_time = json_data.get('eventTime')
        post_schema = PostSchema()
        data = post_schema.load(json_data)

        event = Event(
            data.data['event_id'],
            data.data['market_id'],
            data.data['selection_id'],
            data.data['event_type_id'],
            data.data['meta_data'],
            data.data['comment'],
            json.dumps(data.data['pricedata']),
            user_id,
            json.dumps(data.data['runnerdata'])
        )
        db.session.add(event)
        event.finish_time = calculate_finish_time(
            data.data['event_type_id'],
            start_time)
        try:
            db.session.commit()
            scrape_price_data.apply_async(args=[event.id], countdown=10)
            pundit = User.query.filter_by(id=user_id).first()
            subscriber_list = pundit.subscibers()
            for follower in subscriber_list:
                redis_key = follower['id']
                redis_store.rpush(redis_key, event.id)
                user = User.query.filter_by(id=follower['id']).first()
                send_notification_mail.apply_async(
                    args=[pundit, user, event.meta_data])
            return {'message': 'Event successfully created'}, 200
        except exc.SQLAlchemyError:
            db.session.rollback()
            return {'error_message': 'Failed to register event'}, 500