PageRenderTime 61ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/emailer/server/db.py

https://gitlab.com/qb1t/mitro
Python | 49 lines | 32 code | 12 blank | 5 comment | 1 complexity | acf59cea0b2e4e47c52970ea87cfda88 MD5 | raw file
  1. from tornado.options import define, options
  2. from sqlalchemy import create_engine
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.orm import sessionmaker
  5. from sqlalchemy.pool import StaticPool
  6. from sqlalchemy.pool import NullPool
  7. define('mysql_socket', None, type=str, help='Path to local MySQL socket')
  8. define('mysql_hostname', 'localhost', type=str, help='Hostname of the MySQL server')
  9. define('db_name', 'lectorius', help='Name of MySQL database')
  10. TEST_DATABASE_FN = '/tmp/lectorius.db'
  11. TEST_DATABASE = 'sqlite:///' + TEST_DATABASE_FN
  12. Base = declarative_base()
  13. Session = sessionmaker()
  14. engine = None
  15. def getDatabaseUrl():
  16. # charset parameter forces us to pass MySQL data in UTF-8, ignoring MySQL's config
  17. url = 'mysql://%s:%s@%s/%s?charset=utf8mb4' % (MYSQL_USERNAME,
  18. MYSQL_PASSWORD, options.mysql_hostname, options.db_name)
  19. if options.mysql_socket:
  20. url += '&unix_socket=' + options.mysql_socket
  21. return url
  22. def get_engine():
  23. return engine
  24. def connect_to_database():
  25. '''Connects SQLAlchemy to the database. Call this after command-line parsing.'''
  26. global engine
  27. engine = create_engine(getDatabaseUrl(),
  28. poolclass=NullPool, echo=False)
  29. Session.configure(bind=engine)
  30. def connect_to_test_database():
  31. '''Connects SQLAlchemy to the test database. Call this after command-line
  32. parsing.'''
  33. global engine
  34. # We need to use the StaticPool so everything shares the in-memory DB
  35. engine = create_engine('sqlite://',
  36. poolclass=StaticPool)
  37. Session.configure(bind=engine)