Django和IPython:子目录

时间:2016-01-21 16:46:49

标签: python django ipython jupyter

我喜欢使用IPython(或现在的Jupyter)笔记本来进行我的Django项目所需的某些计算。 Shell_plus为我做的工作。但随着IPython笔记本数量的增长,它在Django项目根文件夹中变得非常混乱。我创建了名为Calculations的子目录,但正如预期的那样,Django不会被加载到这样的笔记本中。有没有办法顺利附加子目录路径?

1 个答案:

答案 0 :(得分:0)

正如上面的评论所指出的,this github issue 有解决方案。我已将我认为的最少步骤提炼如下。

  1. Django 项目布局

     /project
       /someapp
       /notebooks
         ipython_config.py
       settings.py
    
  2. settings.py 的内容

     NOTEBOOK_ARGUMENTS = [
              '--notebook-dir', 'notebooks',
              ]
    
  3. notebooks/ipython_config.py 的内容

    import sys
    import os
    
    FILE_PATH = os.path.abspath(os.path.dirname(__file__))
    PROJECT_BASE_PATH = os.path.abspath(os.path.join(FILE_PATH, '..'))
    
    # Allows the kernel to "see" the project during initialization. This
    # FILE_PATH corresponds to Jupyter's "notebook-dir", but we want notebooks to
    # behave as though they resided in the base directory to allow for clean
    # imports.
    print("sys.path BEFORE = {}".format(sys.path))
    sys.path.insert(1, PROJECT_BASE_PATH)
    print("sys.path AFTER = {}".format(sys.path))
    
    # Any additional initialization logic goes here
    
  4. 使用 shell_plus 启动

    python manage.py shell_plus --notebook

  5. 我必须为日志文件创建一个文件夹

    mkdir -p notebooks/logs