question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Django performance integration suggestions

See original GitHub issue

Hello,

To have better view in performance with django I added myself a few extra tools in my project.

I feel like they answer common needs, here I propose them as is.

Not sure any of these tools would be of interest to you add to this lib.

#!/usr/bin/env python

import sentry_sdk

################### A template tag to see the cost of a block before thinking about caching.
from django.template import Node
from django.template.base import token_kwargs
from django.template.loader_tags import register

class SentrySpanNode(Node):
    def __init__(self, var, name, nodelist,  description, data, op):
        self.nodelist = nodelist
        self.description = description
        self.op = op
        self.data = data

    def __repr__(self):
        return '<%s>' % self.__class__.__name__

    def render(self, context):
        with sentry_sdk.start_span(
                op=self.op,
                description=self.description
        ) as span:
            span.set_data("data", self.data)
            return self.nodelist.render(context)


@register.tag('sentryspan')
def do_start_span(parser, token):
    bits = token.split_contents()
    remaining_bits = bits[1:]
    kwargs = token_kwargs(remaining_bits, parser)
    nodelist = parser.parse(('endsentryspan',))
    description = str(kwargs.get("description", "unnamed"))
    data = kwargs.get("data", {})
    op = str(kwargs.get("op", "render_node"))
    parser.delete_first_token()
    return SentrySpanNode(None, None, nodelist, description=description, data=data, op=op)
############################################################################
############## A simple decorator
from functools import wraps


def sentry_timeit(op="function", description=None):
    def decorator(method):
        @wraps(method)
        def timed(*args, **kw):
            with sentry_sdk.start_span(
                op=op,
                description=description or ".".join(
                    method.__code__.co_filename[:-3].split("/")[-1:] +
                    [method.__name__])
            ) as span:
                kwargs = kw.copy()
                for i, arg in enumerate(args):
                    kwargs[i] = arg
                span.set_tag("func_name", method.__name__)
                span.set_data("args", kwargs)
                return method(*args, **kw)
        return timed
    return decorator

###################### Monkeypatch django template processing most common entries
###### edit: This feature as been implemented more expensively in PR #957 ######
# note: monkeypatching the Template.render method seems overkill as the call often cascade.
import django.shortcuts
from django.template.response import SimpleTemplateResponse
django.shortcuts.render = sentry_timeit("render")(django.shortcuts.render)
_original = SimpleTemplateResponse.rendered_content


@property
@sentry_timeit("render")
def rendered_content(self):
    return _original.fget(self)


SimpleTemplateResponse.rendered_content = rendered_content
########################################

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:23 (22 by maintainers)

github_iconTop GitHub Comments

1reaction
antonpirkercommented, Feb 22, 2022

Hey @Christophe31 ! First thanks for the great work so far! Just a little update: We will do an update of the DjangoIntegration to support Django 4.0 and we keep this in mind. Maybe we can also add the two features you did for this update to make it a really great Django update.

For the record the two features are:

  • the decorator feature (which is not django specific but would ease the way we add span)
  • the template tag (which don’t seems nice to monkey patch and should require explicit configuration or at least explicit import in the template which would break if you remove sentry)

We will keep you posted!

0reactions
github-actions[bot]commented, Dec 23, 2021

This issue has gone three weeks without activity. In another week, I will close it.

But! If you comment or otherwise update it, I will reset the clock, and if you label it Status: Backlog or Status: In Progress, I will leave it alone … forever!


“A weed is but an unloved flower.” ― Ella Wheeler Wilcox 🥀

Read more comments on GitHub >

github_iconTop Results From Across the Web

Performance and optimization - Django documentation
Using cached sessions may be a way to increase performance by eliminating the need to load session data from a slower storage source...
Read more >
Django Performance Improvements - Part 2: Code Optimization
The following guest post addresses how to improve your services's performance with Sentry and other application profilers for Python.
Read more >
Tips for Building High-Quality Django Apps at Scale - Medium
Tips for Building High-Quality Django Apps at Scale · Be careful about “applications” · Organize your apps inside a package · Explicitly name...
Read more >
Here are your ten tips for Django performance optimization
Here are your ten tips for Django performance optimization · 1. Setting A Persistent Database Connection · 2. Ensure Cached Template Loading ·...
Read more >
Django Optimizations and Performance Tips - Pixabay
Django's cache framework is awesome - make use of it. Determine the pages that are most often served and concentrate primarily on those....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found