serve.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. """PostProcessor for serving reveal.js HTML slideshows."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import print_function
  5. import os
  6. import webbrowser
  7. import threading
  8. from tornado import web, ioloop, httpserver, log, gen
  9. from tornado.httpclient import AsyncHTTPClient
  10. from traitlets import Bool, Unicode, Int
  11. from .base import PostProcessorBase
  12. class ProxyHandler(web.RequestHandler):
  13. """handler the proxies requests from a local prefix to a CDN"""
  14. @gen.coroutine
  15. def get(self, prefix, url):
  16. """proxy a request to a CDN"""
  17. proxy_url = "/".join([self.settings['cdn'], url])
  18. client = self.settings['client']
  19. response = yield client.fetch(proxy_url)
  20. for header in ["Content-Type", "Cache-Control", "Date", "Last-Modified", "Expires"]:
  21. if header in response.headers:
  22. self.set_header(header, response.headers[header])
  23. self.finish(response.body)
  24. class ServePostProcessor(PostProcessorBase):
  25. """Post processor designed to serve files
  26. Proxies reveal.js requests to a CDN if no local reveal.js is present
  27. """
  28. open_in_browser = Bool(True,
  29. help="""Should the browser be opened automatically?"""
  30. ).tag(config=True)
  31. browser = Unicode(u'',
  32. help="""Specify what browser should be used to open slides. See
  33. https://docs.python.org/3/library/webbrowser.html#webbrowser.register
  34. to see how keys are mapped to browser executables. If
  35. not specified, the default browser will be determined
  36. by the `webbrowser`
  37. standard library module, which allows setting of the BROWSER
  38. environment variable to override it.
  39. """).tag(config=True)
  40. reveal_cdn = Unicode("https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.5.0",
  41. help="""URL for reveal.js CDN.""").tag(config=True)
  42. reveal_prefix = Unicode("reveal.js",
  43. help="URL prefix for reveal.js").tag(config=True)
  44. ip = Unicode("127.0.0.1",
  45. help="The IP address to listen on.").tag(config=True)
  46. port = Int(8000, help="port for the server to listen on.").tag(config=True)
  47. def postprocess(self, input):
  48. """Serve the build directory with a webserver."""
  49. dirname, filename = os.path.split(input)
  50. handlers = [
  51. (r"/(.+)", web.StaticFileHandler, {'path' : dirname}),
  52. (r"/", web.RedirectHandler, {"url": "/%s" % filename})
  53. ]
  54. if ('://' in self.reveal_prefix or self.reveal_prefix.startswith("//")):
  55. # reveal specifically from CDN, nothing to do
  56. pass
  57. elif os.path.isdir(os.path.join(dirname, self.reveal_prefix)):
  58. # reveal prefix exists
  59. self.log.info("Serving local %s", self.reveal_prefix)
  60. else:
  61. self.log.info("Redirecting %s requests to %s", self.reveal_prefix, self.reveal_cdn)
  62. handlers.insert(0, (r"/(%s)/(.*)" % self.reveal_prefix, ProxyHandler))
  63. app = web.Application(handlers,
  64. cdn=self.reveal_cdn,
  65. client=AsyncHTTPClient(),
  66. )
  67. # hook up tornado logging to our logger
  68. log.app_log = self.log
  69. http_server = httpserver.HTTPServer(app)
  70. http_server.listen(self.port, address=self.ip)
  71. url = "http://%s:%i/%s" % (self.ip, self.port, filename)
  72. print("Serving your slides at %s" % url)
  73. print("Use Control-C to stop this server")
  74. if self.open_in_browser:
  75. try:
  76. browser = webbrowser.get(self.browser or None)
  77. b = lambda: browser.open(url, new=2)
  78. threading.Thread(target=b).start()
  79. except webbrowser.Error as e:
  80. self.log.warning('No web browser found: %s.' % e)
  81. browser = None
  82. try:
  83. ioloop.IOLoop.instance().start()
  84. except KeyboardInterrupt:
  85. print("\nInterrupted")
  86. def main(path):
  87. """allow running this module to serve the slides"""
  88. server = ServePostProcessor()
  89. server(path)
  90. if __name__ == '__main__':
  91. import sys
  92. main(sys.argv[1])