diffido.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import json
  5. import logging
  6. from tornado.ioloop import IOLoop
  7. # from lxml.html.diff import htmldiff
  8. from apscheduler.schedulers.tornado import TornadoScheduler
  9. from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
  10. import tornado.httpserver
  11. import tornado.ioloop
  12. import tornado.options
  13. from tornado.options import define, options
  14. import tornado.web
  15. from tornado import gen, escape
  16. CONF_DIR = ''
  17. JOBS_STORE = 'sqlite:///storage/jobs.db'
  18. API_VERSION = '1.0'
  19. SCHEDULES_FILE = 'conf/schedules.json'
  20. class DiffidoBaseException(Exception):
  21. """Base class for diffido custom exceptions.
  22. :param message: text message
  23. :type message: str
  24. :param status: numeric http status code
  25. :type status: int"""
  26. def __init__(self, message, status=400):
  27. super(DiffidoBaseException, self).__init__(message)
  28. self.message = message
  29. self.status = status
  30. class BaseHandler(tornado.web.RequestHandler):
  31. """Base class for request handlers."""
  32. # Cache currently connected users.
  33. _users_cache = {}
  34. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  35. document = None
  36. collection = None
  37. # A property to access the first value of each argument.
  38. arguments = property(lambda self: dict([(k, v[0].decode('utf-8'))
  39. for k, v in self.request.arguments.items()]))
  40. @property
  41. def clean_body(self):
  42. """Return a clean dictionary from a JSON body, suitable for a query on MongoDB.
  43. :returns: a clean copy of the body arguments
  44. :rtype: dict"""
  45. return escape.json_decode(self.request.body or '{}')
  46. def write_error(self, status_code, **kwargs):
  47. """Default error handler."""
  48. if isinstance(kwargs.get('exc_info', (None, None))[1], DiffidoBaseException):
  49. exc = kwargs['exc_info'][1]
  50. status_code = exc.status
  51. message = exc.message
  52. else:
  53. message = 'internal error'
  54. self.build_error(message, status=status_code)
  55. def is_api(self):
  56. """Return True if the path is from an API call."""
  57. return self.request.path.startswith('/v%s' % API_VERSION)
  58. def initialize(self, **kwargs):
  59. """Add every passed (key, value) as attributes of the instance."""
  60. for key, value in kwargs.items():
  61. setattr(self, key, value)
  62. def build_error(self, message='', status=400):
  63. """Build and write an error message.
  64. :param message: textual message
  65. :type message: str
  66. :param status: HTTP status code
  67. :type status: int
  68. """
  69. self.set_status(status)
  70. self.write({'error': True, 'message': message})
  71. class SchedulesHandler(BaseHandler):
  72. def read_schedules(self):
  73. if not os.path.isfile(SCHEDULES_FILE):
  74. return {}
  75. with open(SCHEDULES_FILE, 'r') as fd:
  76. return json.loads(fd.read())
  77. def write_schedules(self, schedules):
  78. with open(SCHEDULES_FILE, 'w') as fd:
  79. fd.write(json.dumps(schedules, indent=2))
  80. @gen.coroutine
  81. def get(self, id_=None, *args, **kwargs):
  82. schedules = self.read_schedules()
  83. self.write(schedules)
  84. class TemplateHandler(BaseHandler):
  85. """Handler for the / path."""
  86. app_path = os.path.join(os.path.dirname(__file__), "dist")
  87. @gen.coroutine
  88. def get(self, *args, **kwargs):
  89. page = 'index.html'
  90. if args and args[0]:
  91. page = args[0].strip('/')
  92. arguments = self.arguments
  93. self.render(page, **arguments)
  94. def run_scheduled(id_=None, *args, **kwargs):
  95. print('RUNNING %d' % id_)
  96. def run():
  97. print('runno!')
  98. def serve():
  99. jobstores = {'default': SQLAlchemyJobStore(url=JOBS_STORE)}
  100. scheduler = TornadoScheduler(jobstores=jobstores)
  101. scheduler.start()
  102. #scheduler.remove_job('run')
  103. #scheduler.add_job(run, 'interval', minutes=1)
  104. define('port', default=3210, help='run on the given port', type=int)
  105. define('address', default='', help='bind the server at the given address', type=str)
  106. define('ssl_cert', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_cert.pem'),
  107. help='specify the SSL certificate to use for secure connections')
  108. define('ssl_key', default=os.path.join(os.path.dirname(__file__), 'ssl', 'diffido_key.pem'),
  109. help='specify the SSL private key to use for secure connections')
  110. define('debug', default=False, help='run in debug mode')
  111. define('config', help='read configuration file',
  112. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  113. tornado.options.parse_command_line()
  114. logger = logging.getLogger()
  115. logger.setLevel(logging.INFO)
  116. if options.debug:
  117. logger.setLevel(logging.DEBUG)
  118. ssl_options = {}
  119. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  120. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  121. init_params = dict(listen_port=options.port, logger=logger, ssl_options=ssl_options,
  122. scheduler=scheduler)
  123. _schedules_path = r'schedules/?(?P<id_>\d+)?'
  124. application = tornado.web.Application([
  125. ('/api/%s' % _schedules_path, SchedulesHandler, init_params),
  126. (r'/api/v%s/%s' % (API_VERSION, _schedules_path), SchedulesHandler, init_params),
  127. (r'/?(.*)', TemplateHandler, init_params),
  128. ],
  129. static_path=os.path.join(os.path.dirname(__file__), 'dist/static'),
  130. template_path=os.path.join(os.path.dirname(__file__), 'dist/'),
  131. debug=options.debug)
  132. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  133. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  134. options.address if options.address else '127.0.0.1',
  135. options.port)
  136. http_server.listen(options.port, options.address)
  137. try:
  138. IOLoop.instance().start()
  139. except (KeyboardInterrupt, SystemExit):
  140. pass
  141. if __name__ == '__main__':
  142. serve()