简体   繁体   中英

Disabling Django Silk for specific URLs

I have an API endpoint on which I can upload a photo using a multipart request. When Silk is trying to parse the request, I get a decoding error.

I now want to disable Silk for certain URL endpoints. Is this already possible? If so, how should I configure this? If not, what is the easiest way of temporarily disabling Silk altogether?

Link to Github issue: https://github.com/jazzband/django-silk/issues/292

It is not possible yet, but you can inherit from the Silk middleware and exclude some views from being silked using process_view django middleware method. Eg class-based views in django has view_class attribute so you can figure out view class in middleware:

def process_view(request, view_func, view_args, view_kwargs):
    if view_func.view_class == SomeClassBasedView:
        # ignore it
    else:
        return super().process_view(request, view_func, view_args, view_kwargs)

The easiest way of temporarily disabling Silk altogether is removing it from middleware list.

An improvement on milad's solution is to set SILKY_IGNORE_PATHS to a custom class with a containment method. This allows ignoring urls that include path arguments.

In urls.py:

from silk.config import SilkyConfig

urlpatterns = [
    ...
]

class PathMatcher:
    def __init__(self, url_patterns):
        self.url_patterns = url_patterns

    def __contains__(self, item):
        item = item.lstrip('/')
        return any(p.pattern.match(item) for p in self.url_patterns)


SilkyConfig().SILKY_IGNORE_PATHS = PathMatcher(
    urlpatterns[5:10] +  # a subset of the patterns specified in urlpatterns
    [u for u in router.urls if u.name.startswith('analytics-event')] +  # a subset of DRF router urls
    [re_path('^admin/analytics/event/(.*)', lambda: None)]  # hardcoded path
)

我使用 django-silk==4.2.0 并且它具有 SILKY_IGNORE_PATHS 配置,您可以在 django 设置中进行设置

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM