import psycopg2
import redis
import json
from bottle import Bottle, request


class Sender(Bottle):
    def __init__(self):
        super().__init__()
        self.route('/', method='POST', callback=self.send)
        self.fila = redis.StrictRedis(host='queue', port=6379, db=0)
        DSN = 'dbname=email_sender user=postgress host=db'
        self.conn = psycopg2.connect(DSN)

    def register_message(self, assunto, mensagem):
        SQL = 'INSERT INTO emails (assunto, mensagem) VALUES (%s, %s)'
        cur = self.conn.cursor()
        cur.execute(SQL, (assunto, mensagem))
        self.conn.commit()
        cur.close()

        msg = {'assunto': assunto, 'mensagem': mensagem}
        self.fila.rpush('sender', json.dumps(msg))

        print('Message registered!')

    def send(self):
        assunto = request.forms.get('assunto')
        mensagem = request.forms.get('mensagem')

        self.register_message(assunto, mensagem)
        return 'Message queued! Assunto: {} Mensage: {}'.format(
            assunto, mensagem
        )

if __name__ == '__main__':
    sender = Sender()
    sender.run(host='0.0.0.0', port=8080, debug=True)
[((11, 20, 11, 68), 'redis.StrictRedis', 'redis.StrictRedis', (), '', False, 'import redis\n'), ((13, 20, 13, 41), 'psycopg2.connect', 'psycopg2.connect', ({(13, 37, 13, 40): 'DSN'}, {}), '(DSN)', False, 'import psycopg2\n'), ((28, 18, 28, 46), 'bottle.request.forms.get', 'request.forms.get', ({(28, 36, 28, 45): '"""assunto"""'}, {}), "('assunto')", False, 'from bottle import Bottle, request\n'), ((29, 19, 29, 48), 'bottle.request.forms.get', 'request.forms.get', ({(29, 37, 29, 47): '"""mensagem"""'}, {}), "('mensagem')", False, 'from bottle import Bottle, request\n'), ((23, 34, 23, 49), 'json.dumps', 'json.dumps', ({(23, 45, 23, 48): 'msg'}, {}), '(msg)', False, 'import json\n')]