PageRenderTime 378ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/emailer/emailer2.py

https://gitlab.com/qb1t/mitro
Python | 78 lines | 40 code | 20 blank | 18 comment | 6 complexity | 240d4f3ab96011cedc087d4718354068 MD5 | raw file
  1. #!/usr/bin/env python
  2. '''Emailer2: Send users emails
  3. Uses Amazon SES to send emails.
  4. To create a new template:
  5. 1. Write the HTML for the template into templates/templatename_html.html
  6. 2. Convert to email using http://premailer.dialect.ca/ . Save as templates/templatename.html
  7. WARNING: Premailer will escape templates ({{}}) in links; manually fix these
  8. 3. Save a plain text version as templates/templatename.txt
  9. 4. Add type string to email_queue.py as _TYPE_(NAME), add to _VALID_TYPES
  10. 5. Add a new else if to _loop_once
  11. 6. Write the function to send the email (copy the existing examples?)
  12. '''
  13. import datetime
  14. import json
  15. import logging
  16. import sqlalchemy
  17. import sqlalchemy.exc
  18. import sqlalchemy.ext.declarative
  19. import sqlalchemy.orm
  20. from sqlalchemy.pool import StaticPool
  21. from sqlalchemy.pool import NullPool
  22. import tornado.options
  23. from auth import email_queue
  24. from auth import models2
  25. from auth import statsd
  26. Session = sqlalchemy.orm.sessionmaker()
  27. _once = False
  28. def connect_to_database(url):
  29. global _once
  30. assert not _once
  31. _once = True
  32. engine = sqlalchemy.create_engine(url, poolclass=sqlalchemy.pool.NullPool, echo=False)
  33. Session.configure(bind=engine)
  34. def main():
  35. logging.root.setLevel(logging.INFO)
  36. connect_to_database('postgres:///mitro')
  37. extra_args = tornado.options.parse_command_line()
  38. # Verify that mandrill is configured
  39. if tornado.options.options.enable_email:
  40. assert len(tornado.options.options.mandrill_api_key) > 0
  41. # Datadog listens for statsd requests on port 8125
  42. statsd_client = statsd.StatsdClient('localhost', 8125, 'emailer')
  43. backoff_sleeper = email_queue.BackoffSleeper()
  44. email_queue_type = models2.EmailQueue
  45. while True:
  46. try:
  47. email_queue.poll_forever(Session, email_queue_type, statsd_client)
  48. except sqlalchemy.exc.OperationalError, e:
  49. # In case Postgres is not running, retry the connection a few times before dying.
  50. # This is long enough to get upstart to keep restarting the emailer
  51. if not backoff_sleeper.shouldRetryAfterSleep():
  52. logging.error('Failing after %d retries', backoff_sleeper.max_retries())
  53. raise
  54. logging.error('SQLAlchemy exception; retrying after timeout')
  55. if __name__ == '__main__':
  56. main()