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, 'redis.StrictRedis', 'redis.StrictRedis', False, 'import redis\n'), (13, 'psycopg2.connect', 'psycopg2.connect', False, 'import psycopg2\n'), (28, 'bottle.request.forms.get', 'request.forms.get', False, 'from bottle import Bottle, request\n'), (29, 'bottle.request.forms.get', 'request.forms.get', False, 'from bottle import Bottle, request\n'), (23, 'json.dumps', 'json.dumps', False, 'import json\n')]