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

Sac*_*put 7 python django jupyter-notebook

我想建立一个网站,并将能够创建单元格并在其中运行 python 代码的 jupyter 笔记本功能嵌入到我的网站中

为了创建一个网站,我使用 Django,我想嵌入 google collab 或 jupyter 笔记本

顺便说一句,我已经进行了足够的研究,并且一直被 StackOverflow 链接所困扰,其中没有关于此问题的答案或他们想要在 jupyter 笔记本中使用 django 的答案

预先感谢你们可以提供的任何指导或任何参考。

AlA*_*AIL 4

您有很多选择可以做到这一点:

注意::我使用“jupyter-lab”你可以使用“jupyter笔记本”

1-第一个选项重定向到“jupyter笔记本”

Django视图.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)
Run Code Online (Sandbox Code Playgroud)

如果你想在模板中实现而不是重定向,可以在Django模板中使用以下代码:

<iframe src="{% url 'open_jupiter_notbook' %}" width= 600px height=200px></iframe>
Run Code Online (Sandbox Code Playgroud)

2-第二个选项:

只需使用 jupyter 笔记本命令即可subprocess.check_output("your command".split())