[英]embedding jupyter notebook/ google colab in Django app
我想建立一個網站並將能夠創建單元格並在其中運行 python 代碼的 jupyter notebook 功能嵌入到我的網站中
為了創建一個網站,我使用 Django 並且我想嵌入 google collab 或 jupyter notebook
順便說一句,我已經進行了足夠的研究,並且一直堅持使用 StackOverflow 鏈接,其中沒有關於此的答案或他們想在 jupyter 筆記本中使用 django 的鏈接
提前感謝你們可以提供的任何指導或任何參考。
注意::我使用“jupyter-lab”你可以使用“jupyter notebook”
1-重定向到“jupyter notebook”的第一個選項
django view.py
from django.shortcuts import redirect,HttpResponse
import subprocess
import time
def open_jupiter_notbook(request):
b= subprocess.check_output("jupyter-lab list".split()).decode('utf-8')
if "9999" not in b:
a=subprocess.Popen("jupyter-lab --no-browser --port 9999".split())
start_time = time.time()
unreachable_time = 10
while True and "9999" not in b:
timer = time.time()
elapsed_time = timer-start_time
b= subprocess.check_output("jupyter-lab list".split()).decode('utf-8')
if "9999" in b:
break
if elapsed_time > unreachable_time:
return HttpResponse("Unreachable")
path = b.split('\n')[1].split('::',1)[0]
#You can here add data to your path if you want to open file or anything
return redirect(path)
如果你想在模板中實現它而不是重定向,你可以在 Django 模板中使用以下代碼:
<iframe src="{% url 'open_jupiter_notbook' %}" width= 600px height=200px></iframe>
2-第二個選項:
只需使用此 subprocess.check_output subprocess.check_output("your command".split())
即可使用 jupyter notebook 命令
先導出再導入,看這里好解釋
from google.colab import files
src = list(files.upload().values())[0]
open('mylib.py','wb').write(src)
import mylib
有一篇中型文章解釋了如何在此處執行此操作。 要點:
INSTALLED_APPS
python manage.py shell_plus --notebook
- 如果您希望 jupiter 始終可以訪問,您可以在后台運行它。A jupyter notebook is basically a kernel that runs (interactive) python or any other language on the backend and a web based frontend that communicates with this kernel. 這種通信是通過使用 zeromq 完成的。 在引擎蓋下是 websockets。 后端可以根據需要運行任何其他語言,例如 Julia。 前端可以是 web 以外的其他東西,例如終端控制台或 qt 控制台(在這種情況下,我們不會將其稱為 jupyter notebook,因為名稱中的 notebook 部分代表 Z2567A5EC9705EB7AC2C984033E 接口)。
在 python 服務器端,您必須啟動 jupyter notebook 服務器。 這里我們使用端口 8123。我們生成一個隨機令牌,客戶端也必須使用該令牌。
pip3 install notebook
from uuid import uuid4
from notebook.notebookapp import NotebookApp
PORT = 8123
TOKEN = str(uuid4())
app = NotebookApp()
app.initialize(["--port", f"{PORT}", f"--NotebookApp.token={TOKEN}"])
(正在建設的響應 - 顯示服務器處理程序)
(在https://gist.github.com/bollwyvl/bd56b58ba0a078534272043327c52bd1中的完整示例)
您在 Jupyter 筆記本中看到的所有客戶端行為都在 javascript 中實現。 客戶端行為是指創建新的單元格、打印結果、顯示圖表、建立 javascript 端的通信等等。 如果您希望所有這些,那么您幾乎需要
如果您打算擁有所有這些行為,那么使用iframe
包括常規的 jupyter 筆記本會更好。 如果您計划擁有更簡單的東西,例如只有一個單元並且不需要完整的筆記本,那么您可以自己實現一個簡單的客戶端。 對於中間解決方案,您還可以獲取已經完成的 jupyter notebook 頁面的一部分並為您獲取其中的一部分(順便說一句,它使用 BSD 許可證)。
我們談論的是客戶端,但是由於客戶端代碼必須從服務器發送到客戶端,所以仍然在服務器中您必須指示 django 發送以下 html 和 javascript:
(響應正在建設中)
(響應正在建設中)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.