Skip to content
This repository has been archived by the owner on Aug 2, 2023. It is now read-only.

Definitive settings for Django when using reload? #1778

Closed
AndreasBackx opened this issue Sep 17, 2019 · 4 comments
Closed

Definitive settings for Django when using reload? #1778

AndreasBackx opened this issue Sep 17, 2019 · 4 comments

Comments

@AndreasBackx
Copy link

AndreasBackx commented Sep 17, 2019

I've been trying to piece all of the information together from the various issues here on using Django's reload functionality with ptvsd. Currently I'm not even sure what is supported.

The custom protocol arguments seem to have been removed from VS Code in August 2018 though the README still seems to mention them. I remember reading in a comment somewhere while I was looking through the issues (until I caved and just posted this question) that mentioned "debugOptions" is no longer used, but should still be received? Maybe I misinterpreted that comment.

In the end I am left wondering how you can debug a Django application (in a container if that makes a difference) and make VS Code automatically reattach (or not detach at all) when reloading Django. Currently I've tried all types of attach options in launch.json to no avail, it detaches every time Django reloads.

# manage.py
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise

    import ptvsd
    if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
        ptvsd.enable_attach(address=('0.0.0.0', 3000))

    execute_from_command_line(sys.argv)
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Project in Docker",
            "type": "python",
            "request": "attach",
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "/src/"
                }
            ],
            "redirectOutput": true,
            "django": true,
            "subProcess": true,
            "port": 3002,
            "host": "0.0.0.0"
        }
    ]
}

This is what I am using, note that port 3000 in the container is remapped to 3002. Debugging seems to work flawlessly, but saving a file leads to a Django reload which then leads to the debug session ending.

Could some information be posted on how to accomplish this? I am unsure where what is tracked as various issues seem to revolve around Django/Flask reloading and subprocess support.

@karthiknadig
Copy link
Member

@AndreasBackx For development in a container I recommend using https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers. There are few changes I recommend in your code to work around current debugger limitations. Note that this will work with python3 only (see #943 for reasons). We are working on fixing that.

Another reason to use remote containers is that: Each time there is a reload, a new process is started. Each process requires it's own debugger port. Each sub-process will use a ephemeral port. To attach to this port from out side the container you will have to explicitly map it.

Here is how you can do it:

  1. Re-open your code in the container
  2. Ensure that you have python extension installed
  3. Change your manage.py a bit to use multiprocessing with spawn mode.
# manage.py
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    import multiprocessing
    multiprocessing.set_start_method('spawn', True)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)
  1. Use this launch configuration to connect.
        {
            "name": "Django",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/manage.py",
            "args": [ "runserver" ],
            "django": true,
            "subProcess": true,
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "."
                }
            ]
        },

We are working on addressing both the #943 issue and also provide a way to use single port to debug multiple processes.

@AndreasBackx
Copy link
Author

Unfortunately we are working with a (micro) service architecture so I have multiple Django projects open in a VS Code workspace and each project runs in its own container. Using the remote containers plugin is neat, but it's not really feasible in our use case.

So for my use case, I assume I'll have to wait for #943 to be resolved as it resolves this as well?

@karthiknadig
Copy link
Member

karthiknadig commented Sep 25, 2019

Yes, #943 should resolve this as well.

@karthiknadig
Copy link
Member

Closing this since this issue is already tracked by an earlier item.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants