在 Django 应用程序中嵌入 jupyter notebook/ google colab

embedding jupyter notebook/ google colab in Django app

我想建立一个网站并将能够创建单元格和 运行 python 代码的 jupyter notebook 功能嵌入到我的网站中

我使用 Django 创建网站 我想嵌入 google collab 或 jupyter notebook

顺便说一下,我已经进行了足够的研究,并且一直停留在 Whosebug 链接上,其中没有关于此的答案或他们想在 jupyter notebook 中使用 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 "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- 第二个选项:

只需使用 jupyter notebook 命令 通过使用这个 subprocess.check_output("your command".split())

先导出再导入,看解释清楚

from google.colab import files
src = list(files.upload().values())[0]
open('mylib.py','wb').write(src)
import mylib