Development Tip

Django에서 디버깅하는 방법, 좋은 방법?

yourdevel 2020. 10. 3. 12:05
반응형

Django에서 디버깅하는 방법, 좋은 방법? [닫은]


그래서 저는 Python 과 나중에 Django 로 코딩하는 법을 배우기 시작했습니다 . 처음에는 역 추적을 조사하기가 어려웠고 실제로 내가 뭘 잘못했는지 그리고 구문 오류가 어디에 있는지 알아 냈습니다. 어느 정도 시간이 지났고 어느 정도 진행되었습니다. Django 코드를 디버깅하는 루틴이있는 것 같습니다. 코딩 경험 초기에이 작업을 수행했기 때문에이 작업을 수행하는 방법이 비효율적이며 더 빨리 수행 할 수 있는지 궁금했습니다. 나는 보통 내 코드에서 버그를 찾아서 고칠 수 있지만 더 빨리해야 할까?

나는 일반적으로 Django가 활성화되었을 때 제공하는 디버그 정보를 사용합니다. 생각한대로 일이 끝나면 구문 오류로 코드 흐름을 많이 끊고 흐름의 해당 지점에서 변수를 살펴보고 코드가 내가 원하는 것과 다른 작업을 수행하는 위치를 파악합니다.

그러나 이것이 개선 될 수 있습니까? Django 코드를 디버깅하는 데 좋은 도구 나 더 좋은 방법이 있습니까?


이를 수행하는 방법에는 여러 가지가 있지만 가장 간단한 방법은 Python 디버거 를 사용하는 것 입니다. Django 뷰 함수에 다음 줄을 추가하기 만하면됩니다.

import pdb; pdb.set_trace()

또는

breakpoint()  #from Python3.7

브라우저에서 해당 페이지를로드하려고하면 브라우저가 중단되고 실제 실행 코드에서 디버깅을 계속할지 묻는 메시지가 나타납니다.

그러나 다른 옵션이 있습니다 (권장하지 않습니다).

* return HttpResponse({variable to inspect})

* print {variable to inspect}

* raise Exception({variable to inspect})

그러나 모든 유형의 Python 코드에는 Python 디버거 (pdb)를 사용하는 것이 좋습니다. 이미 pdb 를 사용 하고 있다면 디버깅 을 위해 ipython사용하는 IPDB도 살펴보고 싶을 것 입니다.

pdb에 대한 더 유용한 확장은 다음과 같습니다.

Antash 에서 제안한 pdb ++ .

PatDuJour 가 제안한 pudb .

Seafangs가 제안한 Django에서 Python 디버거 사용 .


Werkzeug 의 인터랙티브 디버거를 정말 좋아 합니다. 트레이스 백의 모든 레벨에서 대화 형 쉘을 얻는다는 점을 제외하면 Django의 디버그 페이지와 비슷합니다. django-extensions 를 사용하면 runserver_plus개발 서버를 시작하고 예외에 대한 Werkzeug의 디버거를 제공 하는 관리 명령을 받게 됩니다.

물론 이것은 브라우저를 가진 모든 사람에게 서버 컨텍스트에서 임의의 파이썬 코드를 실행할 수있는 권한을 부여하므로 로컬에서만 실행해야합니다.


템플릿 태그에 대한 간단한 설명 :

@register.filter 
def pdb(element):
    import pdb; pdb.set_trace()
    return element

이제 템플릿 내에서 {{ template_var|pdb }}pdb 세션 (로컬 개발 서버를 실행중인 경우)을 입력하고 element마음의 내용을 검사 할 수 있습니다 .

템플릿에 도착했을 때 개체에 어떤 일이 발생했는지 확인하는 매우 좋은 방법입니다.


잘 협력하고 디버깅 작업을 더 쉽게 할 수있는 몇 가지 도구가 있습니다.

가장 중요한 것은 Django 디버그 도구 모음 입니다.

그런 다음 Python 로깅 기능을 사용하여 좋은 로깅이 필요합니다 . 로깅 출력을 로그 파일로 보낼 수 있지만 더 쉬운 옵션은 로그 출력을 firepython에 보내는 입니다. 이를 사용하려면 firebug 확장이 있는 Firefox 브라우저를 사용해야합니다 . Firepython에는 Firebug 탭에 서버 측 로깅을 표시하는 firebug 플러그인이 포함되어 있습니다.

Firebug 자체는 개발하는 모든 앱의 자바 스크립트 부분을 디버깅하는데도 중요합니다. (물론 JS 코드가 있다고 가정).

또한 pdb를 사용하여 대화식으로 뷰를 디버깅 하는 django-viewtools좋아 했지만 그렇게 많이 사용하지는 않습니다.

메모리 누수를 추적하기위한 도저와 같은 더 유용한 도구가 있습니다 (여기에 메모리 추적을 위해 SO에 대한 답변에 제공되는 다른 좋은 제안도 있습니다).


나는 PyCharm (eclipse와 동일한 pydev 엔진)을 사용합니다. 시각적으로 코드를 단계별로 살펴보고 무슨 일이 일어나고 있는지 볼 수 있도록 정말 도와줍니다.


지금까지 거의 모든 내용이 언급되었으므로 iPythonpdb.set_trace() 을 사용하는 ipdb.set_trace () 를 사용 하는 대신 더 강력합니다 (자동 완성 및 기타 기능). 여기에는 ipdb 패키지가 필요하므로pip install ipdb


나는 PyPI에 밀었 django-pdb습니다 . pdb에 침입하려고 할 때마다 소스 코드를 편집 할 필요가 없다는 것을 의미하는 간단한 앱입니다.

설치는 그냥 ...

  1. pip install django-pdb
  2. 추가 'django_pdb'INSTALLED_APPS

이제 다음을 실행할 수 있습니다. manage.py runserver --pdb모든보기가 시작될 때 pdb에 침입하려면 ...

bash: manage.py runserver --pdb
Validating models...

0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}

> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)

그리고 실행 : manage.py test --pdb테스트 실패 / 오류시 pdb에 침입하려면 ...

bash: manage.py test testapp --pdb
Creating test database for alias 'default'...
E
======================================================================
>>> test_error (testapp.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error
    one_plus_one = four
NameError: global name 'four' is not defined
======================================================================

> /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error()
-> one_plus_one = four
(Pdb)

이 프로젝트는 GitHub 에서 호스팅되며 , 물론 기여도 환영합니다.


Python을 디버깅하는 가장 쉬운 방법은 특히 Visual Studio에 익숙한 프로그래머의 경우 PTVS (Visual Studio 용 Python 도구)를 사용하는 것입니다. 단계는 간단합니다.

  1. http://pytools.codeplex.com/ 에서 다운로드하여 설치 하십시오.
  2. 중단 점을 설정하고 F5를 누릅니다.
  3. 중단 점에 도달하면 C # / C ++ 프로그램을 디버깅하는 것처럼 쉽게 변수를보고 / 변경할 수 있습니다.
  4. 그게 다야 :)

PTVS를 사용하여 Django를 디버깅하려면 다음을 수행해야합니다.

  1. 프로젝트 설정-일반 탭에서 "시작 파일"을 Django 프로그램의 진입 점 인 "manage.py"로 설정합니다.
  2. 프로젝트 설정-디버그 탭에서 "스크립트 인수"를 "runserver --noreload"로 설정합니다. 여기서 핵심은 "--noreload"입니다. 설정하지 않으면 중단 점이 적중되지 않습니다.
  3. 그것을 즐기십시오.

내가 사용 의 PyDev 정말 좋은 이클립스, 세트 브레이크 포인트, 코드를 한 단계로를, 어떤 객체 및 변수에보기 값은 그것을 시도.


나는 PyCharm을 사용 하고 끝까지 대기합니다. 약간의 비용이 들지만 그로부터 얻는 이점은 귀중합니다. 나는 콘솔에서 디버깅을 시도했고, 그렇게 할 수있는 사람들에게 많은 크레딧을 주었지만, 제 애플리케이션을 시각적으로 디버깅 할 수 있다는 것은 대단합니다.

그래도 PyCharm 은 많은 메모리를 차지합니다. 그러나 다시 말하지만, 좋은 것은 인생에서 공짜가 아닙니다. 최신 버전 3과 함께 제공되었습니다. Django, Flask 및 Google AppEngine에서도 매우 잘 작동합니다. 따라서 대체로 모든 개발자에게 유용한 도구라고 말하고 싶습니다.

아직 사용하지 않는 경우 30 일 동안 평가판을 다운로드하여 PyCharm의 성능을 확인하는 것이 좋습니다. Aptana와 같은 다른 도구도 사용할 수 있다고 확신합니다. 그러나 나는 PyCharm이 보이는 방식도 좋아한다고 생각합니다. 거기에서 내 앱을 디버깅하는 것이 매우 편안합니다.


때로는 특정 방법을 탐색하고 pdb를 호출하는 것이 너무 번거 롭다면 다음을 추가합니다.

import IPython; IPython.embed()

IPython.embed() 호출 한 지점에서 로컬 변수에 액세스 할 수있는 IPython 셸을 시작합니다.


제 관점에서는 일반적인 코드 디버깅 작업을 세 가지 사용 패턴으로 나눌 수 있습니다.

  1. 예외발생했습니다 . runserver_plus 'Werkzeug 디버거를 구출했습니다. 모든 추적 수준에서 사용자 지정 코드를 실행하는 기능은 킬러입니다. 완전히 막힌 경우 클릭 한 번으로 공유 할 요지를 만들 수 있습니다.
  2. 페이지가 렌더링되지만 결과는 잘못되었습니다 . 다시 말하지만 Werkzeug는 흔들립니다. 코드에서 중단 점을 만들려면 중단 assert False할 위치를 입력하기 만하면 됩니다.
  3. 코드는 잘못 작동 하지만 빠른보기는 도움이되지 않습니다. 아마도 알고리즘 문제 일 것입니다. 한숨. 그리고 나는 보통 디버거 콘솔 불 PuDB을 : import pudb; pudb.set_trace(). [i] pdb에 비해 가장 큰 장점은 PuDB (80 년대를 보는 동안)가 사용자 지정 시계 식을 쉽게 설정할 수 있다는 것입니다. GUI를 사용하면 여러 중첩 루프를 디버깅하는 것이 훨씬 간단합니다.

아, 네, 템플릿의 비애. 가장 흔한 (저와 제 동료들에게) 문제는 잘못된 컨텍스트입니다. 변수가 없거나 변수에 속성이 없습니다. 디버그 툴바를 사용 하는 경우 '템플릿'섹션에서 컨텍스트를 검사하거나 충분하지 않은 경우 컨텍스트가 채워진 직후 뷰 코드에서 중단을 설정하세요.

그래서 간다.


epdb (Extended Python Debugger)를 적극 권장합니다.

https://bitbucket.org/dugan/epdb

Django 또는 다른 Python 웹 서버를 디버깅하기 위해 epdb에 대해 내가 좋아하는 한 가지는 epdb.serve () 명령입니다. 이는 추적을 설정하고 연결할 수있는 로컬 포트에서이를 제공합니다. 일반적인 사용 사례 :

단계별로 살펴보고 싶은 견해가 있습니다. 트레이스를 설정하려는 지점에 다음을 삽입합니다.

import epdb; epdb.serve()

이 코드가 실행되면 Python 인터프리터를 열고 제공 인스턴스에 연결합니다. n, s 등과 같은 표준 pdb 명령을 사용하여 모든 값을 분석하고 코드를 단계별로 실행할 수 있습니다.

In [2]: import epdb; epdb.connect()
(Epdb) request
<WSGIRequest
path:/foo,
GET:<QueryDict: {}>, 
POST:<QuestDict: {}>,
...
>
(Epdb) request.session.session_key
'i31kq7lljj3up5v7hbw9cff0rga2vlq5'
(Epdb) list
 85         raise some_error.CustomError()
 86 
 87     # Example login view
 88     def login(request, username, password):
 89         import epdb; epdb.serve()
 90  ->     return my_login_method(username, password)
 91
 92     # Example view to show session key
 93     def get_session_key(request):
 94         return request.session.session_key
 95

그리고 언제든지 epdb help를 입력하는 방법에 대해 배울 수 있습니다.

동시에 여러 epdb 인스턴스를 제공하거나 연결하려는 경우 수신 대기 할 포트를 지정할 수 있습니다 (기본값은 8080).

import epdb; epdb.serve(4242)

>> import epdb; epdb.connect(host='192.168.3.2', port=4242)

호스트는 지정되지 않은 경우 'localhost'로 기본 설정됩니다. 나는 이것을 사용하여 로컬 LAN의 개발 서버와 같은 로컬 인스턴스 이외의 것을 디버깅하는 방법을 보여주기 위해 여기에 던졌습니다. 분명히 이렇게하면 세트 트레이스가 프로덕션 서버에 도달하지 않도록주의하십시오!

빠른 메모로 epdb ( import epdb; epdb.set_trace()) 를 사용하여 수락 된 답변과 동일한 작업을 수행 할 수 있지만 매우 유용하다는 것을 알았 기 때문에 서브 기능을 강조하고 싶었습니다.


방금 wdb ( http://www.rkblog.rk.edu.pl/w/p/debugging-python-code-browser-wdb-debugger/?goback=%2Egde_25827_member_255996401 )를 찾았습니다 . 그것은 모든 종소리와 휘파람이있는 꽤 멋진 사용자 인터페이스 / GUI를 가지고 있습니다. 저자는 wdb에 대해 이렇게 말합니다-

"자체 디버거가있는 PyCharm과 같은 IDE가 있습니다.이 IDE는 유사하거나 동일한 기능 세트를 제공합니다. 그러나 이러한 IDE를 사용하려면 특정 IDE를 사용해야합니다 (그 중 일부는 무료가 아니거나 모두에게 제공되지 않을 수 있음). 플랫폼). 필요에 맞는 도구를 선택하십시오. "

그냥 전달하겠다고 생각 했어요.

또한 파이썬 디버거에 대한 매우 유용한 기사 : https://zapier.com/engineering/debugging-python-boss/

마지막으로 Django에서 호출 스택의 멋진 그래픽 출력물을보고 싶다면 https://github.com/joerick/pyinstrument를 확인 하세요 . MIDDLEWARE_CLASSES에 pyinstrument.middleware.ProfilerMiddleware를 추가 한 다음 요청 URL 끝에? profile을 추가하여 프로파일 러를 활성화하십시오.

명령 줄에서 또는 모듈로 가져 와서 pyinstrument를 실행할 수도 있습니다.


I use PyCharm and different debug tools. Also have a nice articles set about easy set up those things for novices. You may start here. It tells about PDB and GUI debugging in general with Django projects. Hope someone would benefit from them.


One of your best option to debug Django code is via wdb: https://github.com/Kozea/wdb

wdb works with python 2 (2.6, 2.7), python 3 (3.2, 3.3, 3.4, 3.5) and pypy. Even better, it is possible to debug a python 2 program with a wdb server running on python 3 and vice-versa or debug a program running on a computer with a debugging server running on another computer inside a web page on a third computer! Even betterer, it is now possible to pause a currently running python process/thread using code injection from the web interface. (This requires gdb and ptrace enabled) In other words it's a very enhanced version of pdb directly in your browser with nice features.

Install and run the server, and in your code add:

import wdb
wdb.set_trace()

According to the author, main differences with respect to pdb are:

For those who don’t know the project, wdb is a python debugger like pdb, but with a slick web front-end and a lot of additional features, such as:

  • Source syntax highlighting
  • Visual breakpoints
  • Interactive code completion using jedi
  • Persistent breakpoints
  • Deep objects inspection using mouse Multithreading / Multiprocessing support
  • Remote debugging
  • Watch expressions
  • In debugger code edition
  • Popular web servers integration to break on error
  • In exception breaking during trace (not post-mortem) in contrary to the werkzeug debugger for instance
  • Breaking in currently running programs through code injection (on supported systems)

It has a great browser-based user interface. A joy to use! :)


Add import pdb; pdb.set_trace() or breakpoint() (form python3.7) at the corresponding line in the Python code and execute it. The execution will stop with an interactive shell. In the shell you can execute Python code (i.e. print variables) or use commands such as:

  • c continue execution
  • n step to the next line within the same function
  • s step to the next line in this function or a called function
  • q quit the debugger/execution

Also see: https://poweruser.blog/setting-a-breakpoint-in-python-438e23fe6b28


If using Aptana for django development, watch this: http://www.youtube.com/watch?v=qQh-UQFltJQ

If not, consider using it.


Most options are alredy mentioned. To print template context, I've created a simple library for that. See https://github.com/edoburu/django-debugtools

You can use it to print template context without any {% load %} construct:

{% print var %}   prints variable
{% print %}       prints all

It uses a customized pprint format to display the variables in a <pre> tag.


I find Visual Studio Code is awesome for debugging Django apps. The standard python launch.json parameters run python manage.py with the debugger attached, so you can set breakpoints and step through your code as you like.


For those that can accidentally add pdb into live commits, I can suggest this extension of #Koobz answer:

@register.filter 
def pdb(element):
    from django.conf import settings
    if settings.DEBUG:    
        import pdb
        pdb.set_trace()
    return element

i highly suggest to use PDB.

import pdb
pdb.set_trace()

You can inspect all the variables values, step in to the function and much more. https://docs.python.org/2/library/pdb.html

for checking out the all kind of request,response and hits to database.i am using django-debug-toolbar https://github.com/django-debug-toolbar/django-debug-toolbar


As mentioned in other posts here - setting breakpoints in your code and walking thru the code to see if it behaves as you expected is a great way to learn something like Django until you have a good sense of how it all behaves - and what your code is doing.

To do this I would recommend using WingIde. Just like other mentioned IDEs nice and easy to use, nice layout and also easy to set breakpoints evaluate / modify the stack etc. Perfect for visualizing what your code is doing as you step through it. I'm a big fan of it.

Also I use PyCharm - it has excellent static code analysis and can help sometimes spot problems before you realize they are there.

As mentioned already django-debug-toolbar is essential - https://github.com/django-debug-toolbar/django-debug-toolbar

And while not explicitly a debug or analysis tool - one of my favorites is SQL Printing Middleware available from Django Snippets at https://djangosnippets.org/snippets/290/

This will display the SQL queries that your view has generated. This will give you a good sense of what the ORM is doing and if your queries are efficient or you need to rework your code (or add caching).

I find it invaluable for keeping an eye on query performance while developing and debugging my application.

Just one other tip - I modified it slightly for my own use to only show the summary and not the SQL statement.... So I always use it while developing and testing. I also added that if the len(connection.queries) is greater than a pre-defined threshold it displays an extra warning.

Then if I spot something bad (from a performance or number of queries perspective) is happening I turn back on the full display of the SQL statements to see exactly what is going on. Very handy when you are working on a large Django project with multiple developers.


use pdb or ipdb. Diffrence between these two is ipdb supports auto complete.

for pdb

import pdb
pdb.set_trace()

for ipdb

import ipdb
ipdb.set_trace()

For executing new line hit n key, for continue hit c key. check more options by using help(pdb)


From my own experience , there are two way:

  1. use ipdb,which is a enhanced debugger likes pdb.

    import ipdb;ipdb.set_trace() or breakpoint() (from python3.7)

  2. use django shell ,just use the command below. This is very helpfull when you are developing a new view.

    python manage.py shell


An additional suggestion.

You can leverage nosetests and pdb together, rather injecting pdb.set_trace() in your views manually. The advantage is that you can observe error conditions when they first start, potentially in 3rd party code.

Here's an error for me today.

TypeError at /db/hcm91dmo/catalog/records/

render_option() argument after * must be a sequence, not int

....


Error during template rendering

In template /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/crispy_forms/templates/bootstrap3/field.html, error at line 28
render_option() argument after * must be a sequence, not int
18  
19          {% if field|is_checkboxselectmultiple %}
20              {% include 'bootstrap3/layout/checkboxselectmultiple.html' %}
21          {% endif %}
22  
23          {% if field|is_radioselect %}
24              {% include 'bootstrap3/layout/radioselect.html' %}
25          {% endif %}
26  
27          {% if not field|is_checkboxselectmultiple and not field|is_radioselect %}
28  

      {% if field|is_checkbox and form_show_labels %}

Now, I know this means that I goofed the constructor for the form, and I even have good idea of which field is a problem. But, can I use pdb to see what crispy forms is complaining about, within a template?

예, 저는 할수 있습니다. nosetests 에서 --pdb 옵션 사용 :

tests$ nosetests test_urls_catalog.py --pdb

예외 (정상적으로 처리 된 예외 포함)가 발생하자마자 pdb는 발생하는 곳에서 멈추고 주위를 둘러 볼 수 있습니다.

  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 537, in __str__
    return self.as_widget()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py", line 593, in as_widget
    return force_text(widget.render(name, self.value(), attrs=attrs))
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 513, in render
    options = self.render_options(choices, [value])
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py", line 543, in render_options
    output.append(self.render_option(selected_choices, *option))
TypeError: render_option() argument after * must be a sequence, not int
INFO lib.capture_middleware log write_to_index(http://localhost:8082/db/hcm91dmo/catalog/records.html)
INFO lib.capture_middleware log write_to_index:end
> /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py(543)render_options()
-> output.append(self.render_option(selected_choices, *option))
(Pdb) import pprint
(Pdb) pprint.PrettyPrinter(indent=4).pprint(self)
<django.forms.widgets.Select object at 0x115fe7d10>
(Pdb) pprint.PrettyPrinter(indent=4).pprint(vars(self))
{   'attrs': {   'class': 'select form-control'},
    'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]],
    'is_required': False}
(Pdb)         

이제 파삭 파삭 한 필드 생성자에 대한 내 선택 인수가 튜플의 목록 / 튜플이 아니라 목록 내의 목록 인 것이 분명합니다.

 'choices': [[('_', 'any type'), (7, (7, 'type 7', 'RECTYPE_TABLE'))]]

깔끔한 점은이 pdb가 내 것이 아닌 crispy의 코드 내에서 발생하고 수동으로 삽입 할 필요가 없다는 것입니다.


개발 중에 빠른 추가

assert False, value

디버거를 사용할 필요없이 뷰 또는 다른 곳에서 문제를 진단하는 데 도움이 될 수 있습니다.

참고 URL : https://stackoverflow.com/questions/1118183/how-to-debug-in-django-the-good-way

반응형