Python

Jupyter 透過自訂 Files Handler 停用檔案下載功能教學與範例

介紹如何透過自訂檔案處理函數,停用 Jupyter 的檔案下載功能,禁止使用者下載檔案。

禁止下載檔案 Files Handler

建立一個 Python 指令稿 forbid_files_handler.py,內容如下:

from tornado import web
from notebook.base.handlers import IPythonHandler

# 禁止下載檔案 Files Handler
class ForbidFilesHandler(IPythonHandler):
  @web.authenticated
  def head(self, path):
    self.log.info("HEAD: File download forbidden.")
    raise web.HTTPError(403)

  @web.authenticated
  def get(self, path, include_body=True):
    self.log.info("GET: File download forbidden.")
    raise web.HTTPError(403)

將以上這個 Python 指令稿存放在個人的 Jupyter 設定檔目錄 ~/.jupyter/ 之下。

建立 Jupyter 設定檔

建立一個 Jupyter 設定檔 ~/.jupyter/jupyter_notebook_config.py

# 產生 Jupyter 設定檔模板
jupyter notebook --generate-config

這個自動產生的設定檔裡面會包含各種可用的 Jupyter 參數以及使用說明,若需要更改參數設定的話,只需要將註解拿掉,再調整參數值即可。

替換 Files Handler

參考 Jupyter 的說明文件,將 ~/.jupyter/jupyter_notebook_config.py 之中的 files_handler_class 替換為自訂的 ForbidFilesHandler,關鍵內容如下:

import os, sys

# 新增 forbid_files_handler 所在位置
sys.path.append('/home/officeguide/.jupyter/')

# 引入自訂 ForbidFilesHandler
import forbid_files_handler

# 以 ForbidFilesHandler 覆蓋標準的 Files Handler
c.ContentsManager.files_handler_class = 'forbid_files_handler.ForbidFilesHandler'
c.ContentsManager.files_handler_params = {}

此處在引入 forbid_files_handler 模組之前,要新增 forbid_files_handler 所在位置,請自行修改這個的存放位置。

設定完成之後,就可以按照一般的方式啟動 Jupyter,在這樣的設定之下,若使用者在檔案上按下滑鼠右鍵並選擇「Download」下載檔案,就只會出現 HTTP 403 禁止下載的錯誤,無法下載任何檔案。

參考資料:Ujjwal BhardwajJupyterLab-DownloadUploadDisabledJupyter GitHub Issues #293

Share
Published by
Office Guide

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago