如何在 VSCode 中調試容器化的 Django 應用程序

本教程介紹如何在 Visual Studio Code (VS Code) 中調試容器化的 Django 應用程序。

目標

在本教程結束時,您應該能夠:

  1. 創建 VS Code 運行配置以附加到 Docker 容器
  2. 修改manage.py,啟動一個debugpy(Python Tools for Visual Studio Debug Server)調試服務器
  3. 在 VS Code 中調試容器化的 Django 項目

創建運行配置

如果您尚未為項目設置運行配置,請添加.vscode/launch.json文件:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Run Django",
      "type": "python",
      "request": "attach",
      "pathMappings": [
        {
          "localRoot": "${workspaceFolder}/app",
          "remoteRoot": "/usr/src/app"
        }
      ],
      "port": 3000,
      "host": "127.0.0.1",
    }
  ]
}

確保更新localRootremoteRoot值,VS Code 使用它來映射工作區和遠程主機文件系統之間的源文件。儘管這些值會根據您的項目設置方式而有所不同,但您通常可以從 Docker 卷配置中獲取此信息。

例如,假設您的 Docker Compose 文件中有以下配置:

volumes:
  - ./app/:/usr/src/app/

本地文件夾路徑應該設置為(例如 ),./app/而應該設置為容器內的文件夾(例如)。值得注意的是,容器內的這個文件夾也可能是您的工作目錄:localRoot"${workspaceFolder}/app"remoteRoot"/usr/src/app"

WORKDIR /usr/src/app

"request": "attach"表示我們想要將 VS Code 的調試器連接到一個已經在運行的進程。在上面的配置中,我們告訴它連接到 127.0.0.1 的 3000 端口。我們將很快配置 debugpy 運行127.0.0.1:3000

完成後,單擊最左側活動欄中的“運行”圖標。您現在應該Run Django在側欄中看到除了播放按鈕之外的配置:

VS 代碼運行視圖

修改manage.py

將 VS Code 設置為附加到 debugpy,讓我們將其集成到我們的應用程序中。

首先,將debugpy包添加到您的需求文件中:

debugpy==1.5.1

由於 debugpy 與 Django 應用程序一起運行,我們需要將其配置為在我們的manage.py文件中運行:

from django.conf import settings

if settings.DEBUG:
    if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
        import debugpy
        debugpy.listen(("0.0.0.0", 3000))
        print('Attached!')

您的文件將類似於:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

    # start new section
    from django.conf import settings

    if settings.DEBUG:
        if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
            import debugpy
            debugpy.listen(("0.0.0.0", 3000))
            print('Attached!')
    # end new section

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        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?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

在這裡,我們首先確定項目是否在DEBUG模式下運行。如果是這樣,那麼如果它是 Django 的重新加載(如果您在服務器運行時更改某些代碼),我們將確保沒有附加調試器。

debugpy.listen()方法啟動調試服務器。您還可以阻止執行,直到調試器附加wait_for_client()

from django.conf import settings

if settings.DEBUG:
    if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
        import debugpy
        debugpy.listen(("0.0.0.0", 3000))
        debugpy.wait_for_client()
        print('Attached!')

由於 debugpy 將在端口 3000 上運行,因此您需要將該端口公開給主機。如果您使用的是 Docker Compose,則可以像這樣公開端口:

version: '3.8'

services:
  web:
    build: ./app
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - ./app/:/usr/src/app/
    ports:
      - 8000:8000
      - 3000:3000

如果您不使用 Compose,請確保在運行容器時公開端口:

$ docker run -d -p 8000:8000 -p 3000:3000 web

調試容器化的 Django 應用程序

構建新映像以安裝 debugpy 後,啟動新容器。

在代碼中的某處設置斷點。然後在 VS Code 中再次打開“運行”視圖並確保Run Django選擇了我們之前創建的配置。單擊播放按鈕開始調試會話。

您現在應該能夠到達斷點並開始調試在 Docker 容器內運行的 Django 應用程序。

VS 代碼斷點

結論

在本教程中,我們向您展示瞭如何配置 VS Code 以調試在 Docker 中運行的 Django 應用程序。

提示:如果您使用的是 Python 3.7 或更高版本,debugpy 還支持 Python 的breakpoint()功能。

來源:  https ://testdriven.io

#django #vscode 

What is GEEK

Buddha Community

如何在 VSCode 中調試容器化的 Django 應用程序
Ahebwe  Oscar

Ahebwe Oscar

1620177818

Django admin full Customization step by step

Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register  and unregister  models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.

Database

Custom Titles of Django Admin

Exclude in Django Admin

Fields in Django Admin

#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization

Ahebwe  Oscar

Ahebwe Oscar

1620185280

How model queries work in Django

How model queries work in Django

Welcome to my blog, hey everyone in this article we are going to be working with queries in Django so for any web app that you build your going to want to write a query so you can retrieve information from your database so in this article I’ll be showing you all the different ways that you can write queries and it should cover about 90% of the cases that you’ll have when you’re writing your code the other 10% depend on your specific use case you may have to get more complicated but for the most part what I cover in this article should be able to help you so let’s start with the model that I have I’ve already created it.

**Read More : **How to make Chatbot in Python.

Read More : Django Admin Full Customization step by step

let’s just get into this diagram that I made so in here:

django queries aboutDescribe each parameter in Django querset

we’re making a simple query for the myModel table so we want to pull out all the information in the database so we have this variable which is gonna hold a return value and we have our myModel models so this is simply the myModel model name so whatever you named your model just make sure you specify that and we’re gonna access the objects attribute once we get that object’s attribute we can simply use the all method and this will return all the information in the database so we’re gonna start with all and then we will go into getting single items filtering that data and go to our command prompt.

Here and we’ll actually start making our queries from here to do this let’s just go ahead and run** Python manage.py shell** and I am in my project file so make sure you’re in there when you start and what this does is it gives us an interactive shell to actually start working with our data so this is a lot like the Python shell but because we did manage.py it allows us to do things a Django way and actually query our database now open up the command prompt and let’s go ahead and start making our first queries.

#django #django model queries #django orm #django queries #django query #model django query #model query #query with django

如何在 VSCode 中調試容器化的 Django 應用程序

本教程介紹如何在 Visual Studio Code (VS Code) 中調試容器化的 Django 應用程序。

目標

在本教程結束時,您應該能夠:

  1. 創建 VS Code 運行配置以附加到 Docker 容器
  2. 修改manage.py,啟動一個debugpy(Python Tools for Visual Studio Debug Server)調試服務器
  3. 在 VS Code 中調試容器化的 Django 項目

創建運行配置

如果您尚未為項目設置運行配置,請添加.vscode/launch.json文件:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Run Django",
      "type": "python",
      "request": "attach",
      "pathMappings": [
        {
          "localRoot": "${workspaceFolder}/app",
          "remoteRoot": "/usr/src/app"
        }
      ],
      "port": 3000,
      "host": "127.0.0.1",
    }
  ]
}

確保更新localRootremoteRoot值,VS Code 使用它來映射工作區和遠程主機文件系統之間的源文件。儘管這些值會根據您的項目設置方式而有所不同,但您通常可以從 Docker 卷配置中獲取此信息。

例如,假設您的 Docker Compose 文件中有以下配置:

volumes:
  - ./app/:/usr/src/app/

本地文件夾路徑應該設置為(例如 ),./app/而應該設置為容器內的文件夾(例如)。值得注意的是,容器內的這個文件夾也可能是您的工作目錄:localRoot"${workspaceFolder}/app"remoteRoot"/usr/src/app"

WORKDIR /usr/src/app

"request": "attach"表示我們想要將 VS Code 的調試器連接到一個已經在運行的進程。在上面的配置中,我們告訴它連接到 127.0.0.1 的 3000 端口。我們將很快配置 debugpy 運行127.0.0.1:3000

完成後,單擊最左側活動欄中的“運行”圖標。您現在應該Run Django在側欄中看到除了播放按鈕之外的配置:

VS 代碼運行視圖

修改manage.py

將 VS Code 設置為附加到 debugpy,讓我們將其集成到我們的應用程序中。

首先,將debugpy包添加到您的需求文件中:

debugpy==1.5.1

由於 debugpy 與 Django 應用程序一起運行,我們需要將其配置為在我們的manage.py文件中運行:

from django.conf import settings

if settings.DEBUG:
    if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
        import debugpy
        debugpy.listen(("0.0.0.0", 3000))
        print('Attached!')

您的文件將類似於:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')

    # start new section
    from django.conf import settings

    if settings.DEBUG:
        if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
            import debugpy
            debugpy.listen(("0.0.0.0", 3000))
            print('Attached!')
    # end new section

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        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?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

在這裡,我們首先確定項目是否在DEBUG模式下運行。如果是這樣,那麼如果它是 Django 的重新加載(如果您在服務器運行時更改某些代碼),我們將確保沒有附加調試器。

debugpy.listen()方法啟動調試服務器。您還可以阻止執行,直到調試器附加wait_for_client()

from django.conf import settings

if settings.DEBUG:
    if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'):
        import debugpy
        debugpy.listen(("0.0.0.0", 3000))
        debugpy.wait_for_client()
        print('Attached!')

由於 debugpy 將在端口 3000 上運行,因此您需要將該端口公開給主機。如果您使用的是 Docker Compose,則可以像這樣公開端口:

version: '3.8'

services:
  web:
    build: ./app
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - ./app/:/usr/src/app/
    ports:
      - 8000:8000
      - 3000:3000

如果您不使用 Compose,請確保在運行容器時公開端口:

$ docker run -d -p 8000:8000 -p 3000:3000 web

調試容器化的 Django 應用程序

構建新映像以安裝 debugpy 後,啟動新容器。

在代碼中的某處設置斷點。然後在 VS Code 中再次打開“運行”視圖並確保Run Django選擇了我們之前創建的配置。單擊播放按鈕開始調試會話。

您現在應該能夠到達斷點並開始調試在 Docker 容器內運行的 Django 應用程序。

VS 代碼斷點

結論

在本教程中,我們向您展示瞭如何配置 VS Code 以調試在 Docker 中運行的 Django 應用程序。

提示:如果您使用的是 Python 3.7 或更高版本,debugpy 還支持 Python 的breakpoint()功能。

來源:  https ://testdriven.io

#django #vscode 

Ananya Gupta

Ananya Gupta

1597123834

Main Pros and Cons of Django As A Web Framework for Python Developers

Django depicts itself as “the web system for fussbudgets with cutoff times”. It was intended to help Python engineers take applications from idea to consummation as fast as could be expected under the circumstances.

It permits fast turn of events on the off chance that you need to make a CRUD application with batteries included. With Django, you won’t need to rehash an already solved problem. It just works and lets you center around your business rationale and making something clients can utilize.

Pros of Django

“Batteries included” theory

The standard behind batteries-included methods normal usefulness for building web applications accompanies the system, not as isolated libraries.

Django incorporates much usefulness you can use to deal with normal web advancement undertakings. Here are some significant level functionalities that Django gives you, which else you need to stay together if you somehow happened to utilize a small scale structure:

ORM

Database relocations

Client validation

Administrator board

Structures

Normalized structure

Django as a system proposes the right structure of an undertaking. That structure helps designers in making sense of how and where to execute any new component.

With a generally acknowledged venture structure that is like numerous tasks, it is a lot simpler to discover online good arrangements or approach the network for help. There are numerous energetic Python designers who will assist you with comprehending any issue you may experience.

Django applications

Django applications (or applications for short) permit designers to separate a task into numerous applications. An application is whatever is introduced by putting in settings.INSTALLED_APPS. This makes it simpler for engineers to add usefulness to the web application by coordinating outer Django applications into the venture.

There are many reusable modules and applications to accelerate your turn of events learn through Online Django Class and Check the Django website.

Secure of course

Django gives great security assurance out of the crate and incorporates avoidance components for basic assaults like SQL Injection (XSS) and Cross-site Request Forgery (CSRF). You can discover more subtleties in the official security diagram control.

REST structure for building APIs

Django REST Framework, commonly condensed “DRF”, is a Python library for building APIs. It has secluded and adaptable engineering that functions admirably for both straightforward and complex web APIs.

DRF gives a lot of verification and authorization strategies out of the case. It is an adaptable, full-included library with measured and adjustable engineering. It accompanies nonexclusive classes for CRUD tasks and an implicit API program for testing API endpoints.

GraphQL structure for building APIs

Huge REST APIs regularly require a lot of solicitations to various endpoints to recover every single required datum. GraphQL it’s a question language that permits us to share related information in a lot simpler design. For a prologue to GraphQL and an outline of its ideas, if it’s not too much trouble allude to the authority GraphQL documentation.

Graphene-Django gives reflections that make it simple to add GraphQL usefulness to your Django venture. Ordinary Django models, structures, validation, consent arrangements, and different functionalities can be reused to manufacture GraphQL blueprint. It additionally gives an implicit API program for testing API endpoints.

Cons of Django

Django ORM

Django ORM, made before SQLAlchemy existed, is currently much sub-par compared to SQLAlchemy. It depends on the Active Record design which is more regrettable than the Unit of Work design embraced by SQLAlchemy. This implies, in Django, models can “spare” themselves and exchanges are off as a matter of course, they are a bit of hindsight. Peruse more in Why I kind of aversion Django.

Django advances course popularity increses day by day:

Django is huge and is viewed as strong bit of programming. This permits the network to create several reusable modules and applications yet has additionally restricted the speed of advancement of the Django. On head of that Django needs to keep up in reverse similarity, so it advances gradually.

Rundown - Should I use Django as a Python designer?

While Django ORM isn’t as adaptable as SQLAlchemy and the enormous environment of reusable modules and applications hinders structure advancement - plainly Django ought to be the best option web system for Python engineers.

Elective, light systems, similar to Flask, while offering a retreat from Django huge biological system and designs, in the long haul can require substantially more additional libraries and usefulness, in the end making many experienced Python engineers winding up wishing they’d began with Django.

Django undertaking’s security and network have become enormously over the previous decade since the system’s creation. Official documentation and instructional exercises are probably the best anyplace in programming advancement. With each delivery, Django keeps on including huge new usefulness.

#django online training #django online course #online django course #django course #django training #django certification course

Marget D

Marget D

1626077187

4 key Features of Django Framework that Make it the Best Amongst all!

Django is one of the popular python based open-source web frameworks mainly used by the developers who like to have rapid development along with the clean pragmatic design.

Read this blog to know the various Django Features with details.

#django framework #django web development #django development company #django development services #python django development company #python django development