浏览代码

Update examples

Steven Silvester 8 年之前
父节点
当前提交
d515cd4fd6

+ 2 - 2
examples/console/index.html

@@ -8,7 +8,7 @@
     <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.js"></script>
   </head>
   <body>
-    <script id='jupyter-config-data' type="application/json">{ "baseUrl": "{{base_url}}" }</script>
-    <script src="build/bundle.js"></script>
+    <script id='jupyter-config-data' type="application/json">{ "baseUrl": "{{base_url}}"}</script>
+    <script src="example/bundle.js"></script>
   </body>
 </html>

+ 25 - 96
examples/console/main.py

@@ -8,115 +8,44 @@ Example
 -------
 
 To run the example, see the instructions in the README to build it. Then
-run ``python main.py`` and navigate your browser to ``localhost:8765``.
-
-Note
-----
-
-This file provides the Python code for interacting with the Jupyter notebook
-server using ``ZMQ`` and the ``tornado`` web server.
+run ``python main.py``.
 
 """
-import re
-import subprocess
-import sys
-import threading
-
-import tornado.web
+import os
+from jinja2 import FileSystemLoader
+from notebook.base.handlers import IPythonHandler, FileFindHandler
+from notebook.notebookapp import NotebookApp
+from traitlets import Unicode
 
-# Install the pyzmq ioloop. Must be done after importing tornado.web and
-# before importing any additional tornado modules
-from zmq.eventloop import ioloop
-ioloop.install()
 
-PORT = 8765
-"""int: Port number of web application"""
-
-
-class MainPageHandler(tornado.web.RequestHandler):
+class ExampleHandler(IPythonHandler):
     """Handle requests between the main app page and notebook server."""
 
-    def initialize(self, base_url):
-        """Intitialize the base URL of the handler."""
-        self.base_url = base_url
-
     def get(self):
         """Get the main page for the application's interface."""
-        return self.render("index.html", static=self.static_url,
-                           base_url=self.base_url)
-
-
-def main(argv):
-    """Start the 'console' example.
-
-    - Start the Tornado main event loop for the Jupyter notebook server
-    - Set up the main page event handler for the 'console' example
-
-    """
-    nb_command = [sys.executable, '-m', 'notebook', '--no-browser',
-                  '--debug',
-                  # FIXME: allow-origin=* only required for notebook < 4.3
-                  '--NotebookApp.allow_origin="*"',
-                  # disable user password:
-                  '--NotebookApp.password=',
-              ]
-    nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
-                                 stdout=subprocess.PIPE)
-
-    # Wait for Jupyter notebook server to complete start up
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Jupyter Notebook is running at:' in line:
-            base_url = re.search(r'(http[^\?]+)', line).groups()[0]
-            break
+        return self.write(self.render_template("index.html",
+            static=self.static_url, base_url=self.base_url))
 
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Control-C' in line:
-            break
+    def get_template(self, name):
+        loader = FileSystemLoader(os.getcwd())
+        return loader.load(self.settings['jinja2_env'], name)
 
-    def print_thread():
-        while 1:
-            line = nb_server.stdout.readline().decode('utf-8').strip()
-            if not line:
-                continue
-            print(line)
-    thread = threading.Thread(target=print_thread)
-    thread.setDaemon(True)
-    thread.start()
 
-    handlers = [
-        (r"/", MainPageHandler, {'base_url': base_url}),
-        (r'/(.*)', tornado.web.StaticFileHandler, {'path': '.'}),
-    ]
+class ExampleApp(NotebookApp):
 
-    app = tornado.web.Application(handlers, static_path='build',
-                                  template_path='.',
-                                  compiled_template_cache=False)
-    app.listen(PORT, 'localhost')
+    default_url = Unicode('/example')
 
-    # For Windows, add no-op to wake every 5 seconds (5000 ms) to handle
-    # signals that may be ignored by the Tornado main event loop
-    if sys.platform.startswith('win'):
-        pc = ioloop.PeriodicCallback(lambda: None, 5000)
-        pc.start()
+    def init_webapp(self):
+        """initialize tornado webapp and httpserver.
+        """
+        super(ExampleApp, self).init_webapp()
+        default_handlers = [
+            (r'/example/?', ExampleHandler),
+            (r"/example/(.*)", FileFindHandler,
+                {'path': 'build'}),
+        ]
+        self.web_app.add_handlers(".*$", default_handlers)
 
-    loop = ioloop.IOLoop.current()
-    print('Browse to http://localhost:%s' % PORT)
-    try:
-        # Start the Tornado main event loop
-        loop.start()
-    except KeyboardInterrupt:
-        print(" Shutting down on SIGINT")
-    finally:
-        nb_server.kill()
-        loop.close()
 
 if __name__ == '__main__':
-    main(sys.argv)
+    ExampleApp.launch_instance()

+ 1 - 1
examples/filebrowser/index.html

@@ -8,6 +8,6 @@
   </head>
   <body>
     <script id='jupyter-config-data' type="application/json">{ "baseUrl": "{{base_url}}" }</script>
-    <script src="build/bundle.js"></script>
+    <script src="example/bundle.js"></script>
   </body>
 </html>

+ 25 - 96
examples/filebrowser/main.py

@@ -8,115 +8,44 @@ Example
 -------
 
 To run the example, see the instructions in the README to build it. Then
-run ``python main.py`` and navigate your browser to ``localhost:8765``.
-
-Note
-----
-
-This file provides the Python code for interacting with the Jupyter notebook
-server using ``ZMQ`` and the ``tornado`` web server.
+run ``python main.py``.
 
 """
-import re
-import subprocess
-import sys
-import threading
-
-import tornado.web
+import os
+from jinja2 import FileSystemLoader
+from notebook.base.handlers import IPythonHandler, FileFindHandler
+from notebook.notebookapp import NotebookApp
+from traitlets import Unicode
 
-# Install the pyzmq ioloop. Must be done after importing tornado.web and
-# before importing any additional tornado modules
-from zmq.eventloop import ioloop
-ioloop.install()
 
-PORT = 8765
-"""int: Port number of web application"""
-
-
-class MainPageHandler(tornado.web.RequestHandler):
+class ExampleHandler(IPythonHandler):
     """Handle requests between the main app page and notebook server."""
 
-    def initialize(self, base_url):
-        """Intitialize the base URL of the handler."""
-        self.base_url = base_url
-
     def get(self):
         """Get the main page for the application's interface."""
-        return self.render("index.html", static=self.static_url,
-                           base_url=self.base_url)
-
-
-def main(argv):
-    """Start the 'filebrowser' example.
-
-    - Start the Tornado main event loop for the Jupyter notebook server
-    - Set up the main page event handler for the 'filebrowser' example
-
-    """
-    nb_command = [sys.executable, '-m', 'notebook', '--no-browser',
-                  '--debug',
-                  # FIXME: allow-origin=* only required for notebook < 4.3
-                  '--NotebookApp.allow_origin="*"',
-                  # disable user password:
-                  '--NotebookApp.password=',
-              ]
-    nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
-                                 stdout=subprocess.PIPE)
-
-    # Wait for Jupyter notebook server to complete start up
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Jupyter Notebook is running at:' in line:
-            base_url = re.search(r'(http[^\?]+)', line).groups()[0]
-            break
+        return self.write(self.render_template("index.html",
+            static=self.static_url, base_url=self.base_url))
 
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Control-C' in line:
-            break
+    def get_template(self, name):
+        loader = FileSystemLoader(os.getcwd())
+        return loader.load(self.settings['jinja2_env'], name)
 
-    def print_thread():
-        while 1:
-            line = nb_server.stdout.readline().decode('utf-8').strip()
-            if not line:
-                continue
-            print(line)
-    thread = threading.Thread(target=print_thread)
-    thread.setDaemon(True)
-    thread.start()
 
-    handlers = [
-        (r"/", MainPageHandler, {'base_url': base_url}),
-        (r'/(.*)', tornado.web.StaticFileHandler, {'path': '.'}),
-    ]
+class ExampleApp(NotebookApp):
 
-    app = tornado.web.Application(handlers, static_path='build',
-                                  template_path='.',
-                                  compiled_template_cache=False)
-    app.listen(PORT, 'localhost')
+    default_url = Unicode('/example')
 
-    # For Windows, add no-op to wake every 5 seconds (5000 ms) to handle
-    # signals that may be ignored by the Tornado main event loop
-    if sys.platform.startswith('win'):
-        pc = ioloop.PeriodicCallback(lambda: None, 5000)
-        pc.start()
+    def init_webapp(self):
+        """initialize tornado webapp and httpserver.
+        """
+        super(ExampleApp, self).init_webapp()
+        default_handlers = [
+            (r'/example/?', ExampleHandler),
+            (r"/example/(.*)", FileFindHandler,
+                {'path': 'build'}),
+        ]
+        self.web_app.add_handlers(".*$", default_handlers)
 
-    loop = ioloop.IOLoop.current()
-    print('Browse to http://localhost:%s' % PORT)
-    try:
-        # Start the Tornado main event loop
-        loop.start()
-    except KeyboardInterrupt:
-        print(" Shutting down on SIGINT")
-    finally:
-        nb_server.kill()
-        loop.close()
 
 if __name__ == '__main__':
-    main(sys.argv)
+    ExampleApp.launch_instance()

+ 1 - 1
examples/filebrowser/src/index.ts

@@ -92,7 +92,7 @@ function createApp(manager: ServiceManager.IManager): void {
   });
   let mFactory = new TextModelFactory();
   let editorServices = {
-    factory: new CodeMirrorEditorFactory(),
+    factoryService: new CodeMirrorEditorFactory(),
     mimeTypeService: new CodeMirrorMimeTypeService()
   };
   let wFactory = new EditorWidgetFactory({

+ 1 - 1
examples/lab/index.html

@@ -10,6 +10,6 @@
   "wsUrl": "{{ws_url}}",
   "terminalsAvailable": "{{terminals_available}}"
  }</script>
-  <script src="lab/bundle.js" main="index"></script>
+  <script src="example/bundle.js" main="index"></script>
 </body>
 </html>

+ 26 - 85
examples/lab/main.py

@@ -2,101 +2,42 @@
 Copyright (c) Jupyter Development Team.
 Distributed under the terms of the Modified BSD License.
 """
-import re
-import subprocess
-import sys
-import threading
 
-import tornado.web
+import os
+from jinja2 import FileSystemLoader
+from notebook.base.handlers import IPythonHandler, FileFindHandler
+from notebook.notebookapp import NotebookApp
+from traitlets import Unicode
 
-# Install the pyzmq ioloop. This has to be done before anything else from
-# tornado is imported.
-from zmq.eventloop import ioloop
-ioloop.install()
 
-PORT = 8765
-
-
-class MainPageHandler(tornado.web.RequestHandler):
-
-    def initialize(self, base_url, ws_url):
-        self.base_url = base_url
-        self.ws_url = ws_url
+class ExampleHandler(IPythonHandler):
+    """Handle requests between the main app page and notebook server."""
 
     def get(self):
-        return self.render("index.html", static=self.static_url,
-                           terminals_available=sys.platform != 'win32',
-                           base_url=self.base_url, ws_url=self.ws_url,)
-
-
-def main(argv):
-    # Start a notebook server with cross-origin access.
-    nb_command = [sys.executable, '-m', 'notebook', '--no-browser',
-                  '--debug',
-                  # FIXME: allow-origin=* only required for notebook < 4.3
-                  '--NotebookApp.allow_origin="*"',
-                  # disable user password:
-                  '--NotebookApp.password=',
-              ]
-    nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
-                                 stdout=subprocess.PIPE)
-
-    # wait for notebook server to start up
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Jupyter Notebook is running at:' in line:
-            base_url = re.search('(http.*?)$', line).groups()[0]
-            ws_url = base_url.replace('http', 'ws')
-            break
-
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Control-C' in line:
-            break
-
-    def print_thread():
-        while 1:
-            line = nb_server.stdout.readline().decode('utf-8').strip()
-            if not line:
-                continue
-            print(line)
+        """Get the main page for the application's interface."""
+        return self.write(self.render_template("index.html",
+            static=self.static_url, base_url=self.base_url))
 
-    thread = threading.Thread(target=print_thread)
-    thread.setDaemon(True)
-    thread.start()
+    def get_template(self, name):
+        loader = FileSystemLoader(os.getcwd())
+        return loader.load(self.settings['jinja2_env'], name)
 
-    handlers = [
-        (r"/", MainPageHandler, {'base_url': base_url, 'ws_url': ws_url}),
-        (r'/lab/(.*)', tornado.web.StaticFileHandler, {'path': 'build/'}),
-    ]
 
-    app = tornado.web.Application(handlers, static_path='build',
-                                  template_path='.',
-                                  compiled_template_cache=False)
+class ExampleApp(NotebookApp):
 
-    app.listen(PORT, 'localhost')
+    default_url = Unicode('/example')
 
-    if sys.platform.startswith('win'):
-        # add no-op to wake every 5s
-        # to handle signals that may be ignored by the inner loop
-        pc = ioloop.PeriodicCallback(lambda: None, 5000)
-        pc.start()
+    def init_webapp(self):
+        """initialize tornado webapp and httpserver.
+        """
+        super(ExampleApp, self).init_webapp()
+        default_handlers = [
+            (r'/example/?', ExampleHandler),
+            (r"/example/(.*)", FileFindHandler,
+                {'path': 'build'}),
+        ]
+        self.web_app.add_handlers(".*$", default_handlers)
 
-    loop = ioloop.IOLoop.current()
-    print('Browse to http://localhost:%s' % PORT)
-    try:
-        loop.start()
-    except KeyboardInterrupt:
-        print(" Shutting down on SIGINT")
-    finally:
-        nb_server.kill()
-        loop.close()
 
 if __name__ == '__main__':
-    main(sys.argv)
+    ExampleApp.launch_instance()

+ 1 - 1
examples/notebook/index.html

@@ -9,6 +9,6 @@
   </head>
   <body>
     <script id='jupyter-config-data' type="application/json">{ "baseUrl": "{{base_url}}" }</script>
-    <script src="build/bundle.js"></script>
+    <script src="example/bundle.js"></script>
   </body>
 </html>

+ 25 - 96
examples/notebook/main.py

@@ -8,115 +8,44 @@ Example
 -------
 
 To run the example, see the instructions in the README to build it. Then
-run ``python main.py`` and navigate your browser to ``localhost:8765``.
-
-Note
-----
-
-This file provides the Python code for interacting with the Jupyter notebook
-server using ``ZMQ`` and the ``tornado`` web server.
+run ``python main.py``.
 
 """
-import re
-import subprocess
-import sys
-import threading
-
-import tornado.web
+import os
+from jinja2 import FileSystemLoader
+from notebook.base.handlers import IPythonHandler, FileFindHandler
+from notebook.notebookapp import NotebookApp
+from traitlets import Unicode
 
-# Install the pyzmq ioloop. Must be done after importing tornado.web and
-# before importing any additional tornado modules
-from zmq.eventloop import ioloop
-ioloop.install()
 
-PORT = 8765
-"""int: Port number of web application"""
-
-
-class MainPageHandler(tornado.web.RequestHandler):
+class ExampleHandler(IPythonHandler):
     """Handle requests between the main app page and notebook server."""
 
-    def initialize(self, base_url):
-        """Intitialize the base URL of the handler."""
-        self.base_url = base_url
-
     def get(self):
         """Get the main page for the application's interface."""
-        return self.render("index.html", static=self.static_url,
-                           base_url=self.base_url)
-
-
-def main(argv):
-    """Start the 'notebook' example.
-
-    - Start the Tornado main event loop for the Jupyter notebook server
-    - Set up the main page event handler for the 'notebook' example
-
-    """
-    nb_command = [sys.executable, '-m', 'notebook', '--no-browser',
-                  '--debug',
-                  # FIXME: allow-origin=* only required for notebook < 4.3
-                  '--NotebookApp.allow_origin="*"',
-                  # disable user password:
-                  '--NotebookApp.password=',
-              ]
-    nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
-                                 stdout=subprocess.PIPE)
-
-    # Wait for Jupyter notebook server to complete start up
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Jupyter Notebook is running at:' in line:
-            base_url = re.search(r'(http[^\?]+)', line).groups()[0]
-            break
+        return self.write(self.render_template("index.html",
+            static=self.static_url, base_url=self.base_url))
 
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Control-C' in line:
-            break
+    def get_template(self, name):
+        loader = FileSystemLoader(os.getcwd())
+        return loader.load(self.settings['jinja2_env'], name)
 
-    def print_thread():
-        while 1:
-            line = nb_server.stdout.readline().decode('utf-8').strip()
-            if not line:
-                continue
-            print(line)
-    thread = threading.Thread(target=print_thread)
-    thread.setDaemon(True)
-    thread.start()
 
-    handlers = [
-        (r"/", MainPageHandler, {'base_url': base_url}),
-        (r'/(.*)', tornado.web.StaticFileHandler, {'path': '.'}),
-    ]
+class ExampleApp(NotebookApp):
 
-    app = tornado.web.Application(handlers, static_path='build',
-                                  template_path='.',
-                                  compiled_template_cache=False)
-    app.listen(PORT, 'localhost')
+    default_url = Unicode('/example')
 
-    # For Windows, add no-op to wake every 5 seconds (5000 ms) to handle
-    # signals that may be ignored by the Tornado main event loop
-    if sys.platform.startswith('win'):
-        pc = ioloop.PeriodicCallback(lambda: None, 5000)
-        pc.start()
+    def init_webapp(self):
+        """initialize tornado webapp and httpserver.
+        """
+        super(ExampleApp, self).init_webapp()
+        default_handlers = [
+            (r'/example/?', ExampleHandler),
+            (r"/example/(.*)", FileFindHandler,
+                {'path': 'build'}),
+        ]
+        self.web_app.add_handlers(".*$", default_handlers)
 
-    loop = ioloop.IOLoop.current()
-    print('Browse to http://localhost:%s' % PORT)
-    try:
-        # Start the Tornado main event loop
-        loop.start()
-    except KeyboardInterrupt:
-        print(" Shutting down on SIGINT")
-    finally:
-        nb_server.kill()
-        loop.close()
 
 if __name__ == '__main__':
-    main(sys.argv)
+    ExampleApp.launch_instance()

+ 1 - 1
examples/terminal/index.html

@@ -11,6 +11,6 @@
   "baseUrl": "{{base_url}}",
   "terminalsAvailable": "{{terminals_available}}"
  }</script>
-    <script src="build/bundle.js"></script>
+    <script src="example/bundle.js"></script>
   </body>
 </html>

+ 26 - 97
examples/terminal/main.py

@@ -8,116 +8,45 @@ Example
 -------
 
 To run the example, see the instructions in the README to build it. Then
-run ``python main.py`` and navigate your browser to ``localhost:8765``.
-
-Note
-----
-
-This file provides the Python code for interacting with the Jupyter notebook
-server using ``ZMQ`` and the ``tornado`` web server.
+run ``python main.py``.
 
 """
-import re
-import subprocess
-import sys
-import threading
-
-import tornado.web
+import os
+from jinja2 import FileSystemLoader
+from notebook.base.handlers import IPythonHandler, FileFindHandler
+from notebook.notebookapp import NotebookApp
+from traitlets import Unicode
 
-# Install the pyzmq ioloop. Must be done after importing tornado.web and
-# before importing any additional tornado modules
-from zmq.eventloop import ioloop
-ioloop.install()
 
-PORT = 8765
-"""int: Port number of web application"""
-
-
-class MainPageHandler(tornado.web.RequestHandler):
+class ExampleHandler(IPythonHandler):
     """Handle requests between the main app page and notebook server."""
 
-    def initialize(self, base_url):
-        """Intitialize the base URL of the handler."""
-        self.base_url = base_url
-
     def get(self):
         """Get the main page for the application's interface."""
-        return self.render("index.html", static=self.static_url,
-                           terminals_available=sys.platform != 'win32',
-                           base_url=self.base_url)
-
-
-def main(argv):
-    """Start the 'terminal' example.
-
-    - Start the Tornado main event loop for the Jupyter notebook server
-    - Set up the main page event handler for the 'terminal' example
-
-    """
-    nb_command = [sys.executable, '-m', 'notebook', '--no-browser',
-                  '--debug',
-                  # FIXME: allow-origin=* only required for notebook < 4.3
-                  '--NotebookApp.allow_origin="*"',
-                  # disable user password:
-                  '--NotebookApp.password=',
-              ]
-    nb_server = subprocess.Popen(nb_command, stderr=subprocess.STDOUT,
-                                 stdout=subprocess.PIPE)
-
-    # Wait for Jupyter notebook server to complete start up
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Jupyter Notebook is running at:' in line:
-            base_url = re.search(r'(http[^\?]+)', line).groups()[0]
-            break
+        return self.write(self.render_template("index.html",
+            static=self.static_url, base_url=self.base_url,
+            terminals_available=True))
 
-    while 1:
-        line = nb_server.stdout.readline().decode('utf-8').strip()
-        if not line:
-            continue
-        print(line)
-        if 'Control-C' in line:
-            break
+    def get_template(self, name):
+        loader = FileSystemLoader(os.getcwd())
+        return loader.load(self.settings['jinja2_env'], name)
 
-    def print_thread():
-        while 1:
-            line = nb_server.stdout.readline().decode('utf-8').strip()
-            if not line:
-                continue
-            print(line)
-    thread = threading.Thread(target=print_thread)
-    thread.setDaemon(True)
-    thread.start()
 
-    handlers = [
-        (r"/", MainPageHandler, {'base_url': base_url}),
-        (r'/(.*)', tornado.web.StaticFileHandler, {'path': '.'}),
-    ]
+class ExampleApp(NotebookApp):
 
-    app = tornado.web.Application(handlers, static_path='build',
-                                  template_path='.',
-                                  compiled_template_cache=False)
-    app.listen(PORT, 'localhost')
+    default_url = Unicode('/example')
 
-    # For Windows, add no-op to wake every 5 seconds (5000 ms) to handle
-    # signals that may be ignored by the Tornado main event loop
-    if sys.platform.startswith('win'):
-        pc = ioloop.PeriodicCallback(lambda: None, 5000)
-        pc.start()
+    def init_webapp(self):
+        """initialize tornado webapp and httpserver.
+        """
+        super(ExampleApp, self).init_webapp()
+        default_handlers = [
+            (r'/example/?', ExampleHandler),
+            (r"/example/(.*)", FileFindHandler,
+                {'path': 'build'}),
+        ]
+        self.web_app.add_handlers(".*$", default_handlers)
 
-    loop = ioloop.IOLoop.current()
-    print('Browse to http://localhost:%s' % PORT)
-    try:
-        # Start the Tornado main event loop
-        loop.start()
-    except KeyboardInterrupt:
-        print(" Shutting down on SIGINT")
-    finally:
-        nb_server.kill()
-        loop.close()
 
 if __name__ == '__main__':
-    main(sys.argv)
+    ExampleApp.launch_instance()