Django shell_plus:如何访问Docker容器中的Jupyter笔记本

2024-09-28 01:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问Docker容器中django extensions中使用shell_plus命令创建的Jupyter笔记本

docker-compose -f local.yml run --rm django python manage.py shell_plus --notebook

我的配置基于@RobM和@Mark Chackerian对这个Stack Overflow question的回答。例如,我安装并配置了一个自定义内核,我的Django apps配置文件的常量NOTEBOOK_ARGUMENTS设置为:

NOTEBOOK_ARGUMENTS = [
    '--ip', '0.0.0.0',
    '--port', '8888',
    '--allow-root',
    '--no-browser',
]

我可以在日志中看到容器已成功启动:

[I 12:58:54.877 NotebookApp] The Jupyter Notebook is running at:
[I 12:58:54.877 NotebookApp] http://10d56bab37fc:8888/?token=b2678617ff4dcac7245d236b6302e57ba83a71cb6ea558c6
[I 12:58:54.877 NotebookApp]  or http://127.0.0.1:8888/?token=b2678617ff4dcac7245d236b6302e57ba83a71cb6ea558c6

但是我无法打开url。我已在我的docker-compose中转发了8888端口,尝试使用localhost而不是127.0.0.1,并尝试使用容器IP,但未成功

我觉得我错过了这里显而易见的东西……感谢您的帮助


Tags: djangocomposedockertokenhttpjupyterplusextensions
3条回答

让它工作,但它为什么这样做是我无法理解的。在docker-compose run命令中公开端口就成功了

docker-compose -f local.yml run  rm -p 8888:8888 django python manage.py shell_plus  notebook

我的印象是,在我的local.yml中暴露端口也会在run开始的容器中打开它们

为了到2020年的记录,我设法在{}中设置了一个工作{}设置{}:

development.py(settings.py)

INSTALLED_APPS += [
    "django_extensions",
]

SHELL_PLUS = "ipython"

SHELL_PLUS_PRINT_SQL = True

NOTEBOOK_ARGUMENTS = [
    " ip",
    "0.0.0.0",
    " port",
    "8888",
    " allow-root",
    " no-browser",
]

IPYTHON_ARGUMENTS = [
    " ext",
    "django_extensions.management.notebook_extension",
    " debug",
]

IPYTHON_KERNEL_DISPLAY_NAME = "Django Shell-Plus"

SHELL_PLUS_POST_IMPORTS = [ # extra things to import in notebook
    ("module1.submodule", ("func1", "func2", "class1", "etc")),
    ("module2.submodule", ("func1", "func2", "class1", "etc"))

]

os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" # only use in development 

requirements.txt

django-extensions
jupyter
notebook
Werkzeug  # needed for runserver_plus
...

docker compose.yml

version: "3"

services:
  db:
    image: postgres:13
    environment:
      - POSTGRES_HOST_AUTH_METHOD=trust
    restart: always
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data/
  web:
    build: .
    environment:
      - DJANGO_SETTINGS_MODULE=settings.development
    command:
      - scripts/startup.sh
    volumes:
      - ...
    ports:
      - "8000:8000" # webserver 
      - "8888:8888" # ipython notebook
    depends_on:
      - db

volumes:
  postgres_data:

从主机终端运行以下命令:

docker-compose exec web python manage.py shell_plus  notebook

最后在主机的web浏览器中导航到http://localhost:8888/?token=<xxxx>

如果您想使用类似jupyter笔记本的独立服务:

jupyter_notebook:
  build:
    context: .
    dockerfile: docker/dev/web/Dockerfile
  command: python manage.py shell_plus  notebook
  depends_on:
    - web
  ports:
  - 8888:8888 # ipython notebook
  env_file:
    - .env

之后:

docker-compose logs -f 'jupyter_notebook'

您将在日志中获得访问令牌

相关问题 更多 >

    热门问题