Exemple #1
0
def route_message(request):
    if request.method == 'POST':
        form = request.form()
        msg = Message(form)
        Message.add(msg)
    header = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n'
    body = template('msg.html')
    msgs = '<br>'.join([str(m) for m in Message.all()])
    body = body.replace('{{messages}}', msgs)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
Exemple #2
0
    def post(self):
        """ POST request handler for MessageListResource. It publishes a
            new message from a user to a specific chatroom given user id
            and chatroom id. 

            It handles bot invoking requests. When a message is sent with
            an slash character ('/') at the begginning, it calls the
            decoupled bot requesting the information that should be obtained
            from the command. Uses pika to produce this AMQP request.

            In case of an error, HTTP status 400 (BAD_REQUEST) is returned.
            Else, HTTP status 200 (OK) is returned.
        """
        request_dict = request.get_json()
        if not request_dict:
            response = {"error": "No input data provided."}
            return response, status.HTTP_400_BAD_REQUEST

        try:
            id_user = int(request_dict['id_user'])
            id_chatroom = int(request_dict['id_chatroom'])
            msg_body = request_dict['msg_body']
            if msg_body[0] == '/':
                bot_body = msg_body + "$" + str(id_user) + "#" + str(
                    id_chatroom)

                connection = pika.BlockingConnection(
                    pika.ConnectionParameters(host='localhost'))
                channel = connection.channel()
                channel.queue_declare(queue='financial')
                channel.basic_publish(exchange='',
                                      routing_key='financial',
                                      body=bot_body)
                print(" [x] Sent " + bot_body)
                connection.close()

                response = {"ok": "Message sent to bot successfully"}
                return response, status.HTTP_200_OK

            message = Message(body=msg_body,
                              timestamp=datetime.datetime.utcnow(),
                              id_user=id_user,
                              id_chatroom=id_chatroom)
            message.add(message)
            db.session.commit()

            response = {
                "ok": "Message published successfully on room %d" % id_chatroom
            }
            return response, status.HTTP_200_OK
        except Exception as e:
            db.session.rollback()
            response = {"error": str(e)}
            return response, status.HTTP_400_BAD_REQUEST
Exemple #3
0
def add():
    form = request.form
    m = Message(form)
    Message.add(m)
    return redirect(url_for('message.index'))