跳转到主要内容

上下文管理器,用于将查询计划上传到https://explain.dalibo.com/

项目描述

Django Postgres Explain Visualizer (Django-PEV)

PyPI version versions Lint

此工具捕获SQL查询并将查询计划上传到由dalibo提供的PostgreSQL Explain Visualizer (PEV)。这对于调试慢查询特别有帮助。

此工具还导出类似于pghero的图形用户界面,但嵌入到您的Django应用程序中。

安装

  1. pip安装django-pev

  2. 添加到您的urls

# urls.py
from django.urls import include, path

urlpatterns = [
    # ....

    path('django-pev/', include(('django_pev.urls', 'django_pev'), namespace='django_pev')),
]
  1. 添加到您的已安装应用程序
# settings.py

INSTALLED_APPS = [
    # ...
    "django_pev"
]

使用

使用explain上下文管理器包裹一些代码。所有SQL查询都会捕获堆栈跟踪(以定位调用位置)。最慢的查询可通过.slowest访问。

import django_pev
from django.contrib.auth.models import User

with django_pev.explain() as e:
    # Every SQL query is captured
    list(User.objects.filter(email='test@test.com').all())

# Rerun the slowest query with `EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON)`
pev_response = e.slowest.visualize(
    # By default the text of the query is not uploaded for security reasons
    upload_query=True,
    # Set to false if the query is slow and you want only an explain
    analyze=True,
    # Give a helpful title for the uploaded query plan
    title="Measuring email filter",
)
print(pev_response.url)

# View the postgres explain visualization
e.slowest.visualize_in_browser()

# View the stack trace of the slowest query
print(e.slowest.stacktrace)

# Delete the plan hosted on https://explain.dalibo.com
pev_response.delete()

可选配置其他设置

# Replace the default test client used during explain with a custom class
DJANGO_PEV_EXPLAIN_TEST_CLIENT = 'django.test.Client'

如何在生产中调试慢端点

如果您可以访问生产服务器上的python manage.py shell;您可以运行以下代码片段以获取上传的explain计划。通常这种技术是一种类型的分析。

import django_pev

from django.contrib.auth.models import User
from django.test import Client as TestClient

client = TestClient()
# Authentication
client.force_login(User.objects.get(id=1))
url = "/some_slow_url"

with django_pev.explain() as e:
    response = client.get(url)

print(e.slowest.visualize(title=f"Fetching {url}"))

待办事项

  • 添加迁移以确保pg_stats_statement_info正确
  • 当不可用时不崩溃
  • 添加explain标签
  • 添加索引建议器

免责声明

感谢Pierre Giraud (@pgiraud) 为PEV2和Alex Tatiyants (@AlexTatiyants) 为原始pev工具做出的贡献。

在任何情况下,DALIBO不对任何当事人因使用本软件及其文档而直接、间接、特殊、偶然或后果性损害(包括利润损失)承担责任,即使DALIBO已被告知此类损害的可能性。

DALIBO明确排除任何保证,包括但不限于对商品性和特定用途的默示保证。在本协议下提供的软件是基于“现状”提供的,DALIBO没有义务提供维护、支持、更新、增强或修改。

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

django_pev-0.2.0.tar.gz (20.9 kB 查看哈希值)

上传时间

构建分发

django_pev-0.2.0-py3-none-any.whl (28.5 kB 查看哈希值)

上传时间 Python 3

支持者