Jupyter Notebook cross-domain connection Kernel method

Usually, when a new Notebook is opened, it will automatically connect to the current server and create a Session and a Kernel process. The session is bound to the path of the nb (notebook for short, the same below), so you want your server to keep running, no matter whether you refresh the nb or open a new tab of the nb, the session is the same session, and the kernel is the same a kernel.

The above is the basic front-end and back-end interaction process of Notebook. This article focuses on how to connect across domains when nb and Kernel are not in the same domain. That is, let's say the address of nb is a.com/xx.ipynb, but we want to connect b.comto a kernel.

Modify the backend address

The first is the call to create the Session, which happens session.json line 122

utils.ajax(this.session_service_url, {

Here you need to modify it to the domain name you want to connect to, for example 'http://b.com' + this.session_service_url.

After the session and the kernel are created, the interaction between nb and the kernel will use the websocket channel. The ws address is in a format like ws://localhostthis , defined in the notebook.htmltemplate, and rendered by the server when nb is opened:

data-ws-url="{{ws_url | urlencode}}"

After these two changes are made to cross-domain addresses, your nb will automatically send a request to the new server, so naturally your new server needs to add a cross-domain header to the response, which can be achieved simply by modifying the configuration file:

c.NotebookApp.allow_origin = '*'

This configuration item /base/handlers.pywill be accessed in :

[@property](https://my.oschina.net/property)
def allow_origin(self):
    """Normal Access-Control-Allow-Origin"""
    return self.settings.get('allow_origin', '')

handle authentication

Of course, the server is not non-refused to the connection. There are still two things that need to be addressed in the authentication:

One is xsrf token authentication, which can be turned off in the configuration file:

c.NotebookApp.disable_check_xsrf = True

The second is user login authentication. The server uses the token method by default, and the token will be written page.htmlin :

data-jupyter-api-token="{{token | urlencode}}"

Or if you want to bypass the auth process directly base/handlers.py, get_current_useryou can modify the method in .

After completing the above modification, the function of cross-domain connection to the kernel can be realized.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324927622&siteId=291194637