简体   繁体   English

如何抑制 Django 中的弃用警告?

[英]How to suppress the deprecation warnings in Django?

Every time I'm using the django-admin command — even on TAB–completion — it throws a RemovedInDjango19Warning (and a lot more if I use the test command).每次我使用django-admin命令时——即使是在 TAB 完成时——它都会抛出一个RemovedInDjango19Warning (如果我使用测试命令,还会抛出更多警告)。 How can I suppress those warnings?我怎样才能抑制这些警告?

I'm using Django 1.8 with Python 3.4 (in a virtual environment).我正在使用 Django 1.8 和 Python 3.4(在虚拟环境中)。 As far as I can tell, all those warnings come from libraries not from my code.据我所知,所有这些警告都来自库而不是我的代码。

Examples例子

Here are some examples:这里有些例子:

  • …/lib/python3.4/importlib/_bootstrap.py:321: RemovedInDjango19Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django 1.9. Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes. return f(*args, **kwds)

  • …/lib/python3.4/site-packages/django/contrib/admin/util.py:7: RemovedInDjango19Warning: The django.contrib.admin.util module has been renamed. Use django.contrib.admin.utils instead. "Use django.contrib.admin.utils instead.", RemovedInDjango19Warning)

  • …/lib/python3.4/site-packages/django/templatetags/future.py:25: RemovedInDjango19Warning: Loading the ``url`` tag from the ``future`` library is deprecated and will be removed in Django 1.9. Use the default ``url`` tag instead. RemovedInDjango19Warning)

Update更新

Since Django version 1.11 ( release notes ) deprecating warnings are no longer loud by default.自 Django 版本 1.11( 发行说明)以来,默认情况下弃用警告不再响亮。 So I guess this won't be an issue anymore, since 1.11 is the last version to support Python 2 and also features long-term support.所以我想这不再是问题,因为 1.11 是支持 Python 2 的最后一个版本,并且还提供长期支持。

Adding a logging filter to settings.py can suppress these console warnings (at least for manage.py commands in Django 1.7, Python 3.4). 在settings.py中添加日志记录过滤器可以抑制这些控制台警告(至少对于Django 1.7,Python 3.4中的manage.py命令而言)。

A filter can selectively suppress warnings. 筛选器可以有选择地抑制警告。 The following code creates a new "suppress_deprecated" filter for the console and appends it to the default logging filters. 以下代码为控制台创建一个新的“ suppress_deprecated”过滤器,并将其附加到默认的日志过滤器中。 Add this block to settings.py to configure the LOGGING variable: 将此块添加到settings.py以配置LOGGING变量:

import logging, copy
from django.utils.log import DEFAULT_LOGGING

LOGGING = copy.deepcopy(DEFAULT_LOGGING)
LOGGING['filters']['suppress_deprecated'] = {
    '()': 'mysite.settings.SuppressDeprecated'  
}
LOGGING['handlers']['console']['filters'].append('suppress_deprecated')

class SuppressDeprecated(logging.Filter):
    def filter(self, record):
        WARNINGS_TO_SUPPRESS = [
            'RemovedInDjango18Warning',
            'RemovedInDjango19Warning'
        ]
        # Return false to suppress message.
        return not any([warn in record.getMessage() for warn in WARNINGS_TO_SUPPRESS])

The 'mysite.settings.SuppressDeprecated' string needs to change if the root website module (or filter location and/or name) is different. 如果根网站模块(或过滤器位置和/或名称)不同,则需要更改“ mysite.settings.SuppressDeprecated”字符串。

I'll leave this for newcomers: 我将其留给新来者:

As for django 1.11 deprecating warnings are no longer loud by default. 至于django 1.11 ,默认情况下,不再提倡过时的警告。 To activate them run python -Wd manage.py runserver for example. 要激活它们,请运行python -Wd manage.py runserver

source 资源

In django 1.7, a new setting was introduced SILENCED_SYSTEM_CHECKS to suppress warnings 在Django 1.7中,引入了新设置SILENCED_SYSTEM_CHECKS以禁止显示警告

A list of identifiers of messages generated by the system check framework (ie ["models.W001"]) that you wish to permanently acknowledge and ignore. 您希望永久确认和忽略的由系统检查框架(即[“ models.W001”])生成的消息的标识符列表。 Silenced warnings will no longer be output to the console; 沉默的警告将不再输出到控制台; silenced errors will still be printed, but will not prevent management commands from running. 静默错误仍然会打印,但不会阻止管理命令运行。

Documentation could be found here 文档可以在这里找到

Here is a list of all the checks to suppress Example: 这是所有禁止显示示例的检查列表

If you wish to suppress the TEMPLATES_ warning, 如果您希望取消TEMPLATES_警告,

The standalone TEMPLATE_* settings were deprecated in Django 1.8 独立的TEMPLATE_ *设置在Django 1.8中已弃用

your settings would be: 您的设置为:

SILENCED_SYSTEM_CHECKS = ["1_8.W001"]

In manage.py, add this to the top line -- 在manage.py中,将其添加到第一行-

#!/usr/bin/env PYTHONWARNINGS=ignore python

This will suppress all warnings, which I agree can in some situations be undesirable if you're using a lot of third party libraries. 这将禁止所有警告,如果您使用大量的第三方库,在某些情况下我不希望这样做。

Disclaimer: Recommended only after you've already seen the warnings at least 1,000 too many times already, and should be removed when you upgrade Django. 免责声明:仅当您已经至少看到1000次警告后才建议使用,并且在升级Django时应将其删除。

Note: this may have some undesirable effects on some platforms, eg swallowing more output than just warnings. 注意:这在某些平台上可能会产生一些不良影响,例如吞下比警告更多的输出。

Nothing of the above have worked for me, django 1.9. django 1.9对我没有任何帮助。 I fixed this by adding the following lines to settings.py: 我通过在settings.py中添加以下几行来解决此问题:

import logging

def filter_deprecation_warnings(record):
     warnings_to_suppress = [
        'RemovedInDjango110Warning'
    ]

    # Return false to suppress message.
    return not any([warn in record.getMessage() 
         for warn in warnings_to_suppress])

warn_logger = logging.getLogger('py.warnings')
warn_logger.addFilter(filter_deprecation_warnings)

While reviewing deprecation warnings in other dependencies of my Django 1.8 project, using 在查看Django 1.8项目其他依赖项中的弃用警告时,请使用

python -Wd manage.py runserver

, I was able to filter out Django deprecation warnings by temporarily adding ,我可以通过临时添加来过滤掉Django弃用警告

import warnings
from django.utils.deprecation import RemovedInDjango110Warning
warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning)

to my settings.py (can presumably be in any module that's loaded at startup). 到我的settings.py (大概可以在启动时加载的任何模块中)。 I couldn't figure out how to include the filter as an extra -W option, ie 我不知道如何将过滤器作为额外的-W选项包括,即

python -Wd -Wi::RemovedInDjango110Warning manage.py runserver

resulted in Invalid -W option ignored: unknown warning category: 'RemovedInDjango110Warning' . 导致Invalid -W option ignored: unknown warning category: 'RemovedInDjango110Warning'

For some reason the solution provided by Fred Schleifer didn't work for me in Django 1.9, so I had to find a different solution. 由于某种原因,Fred Schleifer提供的解决方案在Django 1.9中对我不起作用,因此我不得不找到其他解决方案。

In settings.py , I set up a custom LOGGING_CONFIG function: settings.py ,我设置了一个自定义LOGGING_CONFIG函数:

LOGGING_CONFIG = 'my_project.logging_utils.configure'

Then I defined my custom my_project.logging_utils module like so: 然后,我定义了自定义my_project.logging_utils模块,如下所示:

from logging.config import dictConfig
import warnings
from django.utils.deprecation import RemovedInDjango110Warning

IGNORE_DJANGO_110_WARNINGS = {
    # This is a specific warning raised by a third-party library.
    r'rest_framework_swagger\.urls': r'django\.conf\.urls\.patterns\(\) is deprecated.*'
}

def configure(settings):
    dictConfig(settings)
    for module, message in IGNORE_DJANGO_110_WARNINGS.items():
        warnings.filterwarnings(
            action='ignore',
            category=RemovedInDjango110Warning,
            module=module,
            message=message
        )

The IGNORE_DJANGO_110_WARNINGS dict contains a mapping from module names to regular expressions of warnings raised by them. IGNORE_DJANGO_110_WARNINGS字典包含从模块名称到它们引发的警告的正则表达式的映射。 I chose to be very specific in the kinds of warnings I suppressed, as I still wanted to see ones that I didn't expect. 我选择在所压制的警告中非常具体,因为我仍然想看到意想不到的警告。 As individual third-party libraries are updated, I'll remove their associated entries from the dict. 随着各个第三方库的更新,我将从dict中删除它们的关联条目。

# in settings.py
import warnings
from django.utils.deprecation import RemovedInDjango20Warning

DEBUG = True

if DEBUG:
    warnings.simplefilter('default')
    warnings.filterwarnings('ignore', category=RemovedInDjango20Warning)
    # use it if you annoyed by DeprecationWarning
    warnings.filterwarnings('ignore', category=DeprecationWarning)

This standart django script add TAB–completion for you bash - https://github.com/django/django/blob/master/extras/django_bash_completion 这个标准的django脚本为您的bash添加了TAB-completion- https://github.com/django/django/blob/master/extras/django_bash_completion

PYTHONWARNINGS is not defined - error in console. 未定义PYTHONWARNINGS-控制台错误。 Add export PYTHONWARNINGS="ignore" and unset PYTHONWARNINGS in _django_completion() 添加导出PYTHONWARNINGS =“ ignore”并在_django_completion()中取消设置PYTHONWARNINGS

Original function: 原始功能:

_django_completion()
{
    COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \
                   COMP_CWORD=$COMP_CWORD \
                   DJANGO_AUTO_COMPLETE=1 $1 ) )
}

My version. 我的版本。 Do not break the basic behavior in other cases. 在其他情况下,请勿破坏基本行为。

_django_completion()
{
    export PYTHONWARNINGS="ignore"
    COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \
                   COMP_CWORD=$COMP_CWORD \
                   DJANGO_AUTO_COMPLETE=1 $1 ) )
    unset PYTHONWARNINGS
}

Django puts warnings through the standard python warnings module. Django通过标准的python warnings模块放置警告。 If your python project throws warnings and they're "acceptable" for the moment, just use warnings.filterwarnings() or warnings.simplefilter() . 如果您的python项目抛出警告,并且暂时是“可接受的”,则只需使用warnings.filterwarnings()warnings.simplefilter() I'm not sure where the "best" place for these are, but I've dropped them into my common_settings.py file (For me, this is a unchanging, checked-in file, that is imported by local_settings.py). 我不确定这些“最佳”位置在哪里,但已将它们放到我的common_settings.py文件中(对我来说,这是一个不变的,已签入的文件,由local_settings.py导入)。

Eg: 例如:

warnings.filterwarnings(action="ignore", category=RemovedInDjango110Warning, module='django.template.utils', lineno=37)

Alas the comment about silencing the system checks won't work, here, since your example isn't throwing a system-check error. 遗憾的是,由于您的示例没有引发系统检查错误,因此有关使系统检查静音的评论将不起作用。

I currently encounter this same issue when using Django 1.8. 我目前在使用Django 1.8时遇到同样的问题。 Instead of completely suppress those warnings, we decide to show them only in DEBUG mode. 我们决定完全以DEBUG模式显示它们,而不是完全禁止显示这些警告。

We can add console handler in logging settings and use this handler to catch py.warnings. 我们可以在记录设置中添加控制台处理程序,并使用该处理程序捕获py.warnings。 Here is the code snippet, 这是代码片段,

'filters': {
    'require_debug_true': {
        '()': 'django.utils.log.RequireDebugTrue'
    },
    ...
},
'handlers': {
    'console': {
        'level': 'DEBUG',
        'filters': ['require_debug_true'],
        'class': 'logging.StreamHandler',
        'formatter': 'standard',
    },
    ...
},
'loggers': {
    'py.warnings': {
        'handlers': ['console', ],
        'level': 'INFO',
        'propagate': False
    },
    ...
}

The complete Django settings file: https://github.com/haiwen/seahub/blob/21c827c68047e13700fe102d22a3f5515b22af89/seahub/settings.py#L484 完整的Django设置文件: https : //github.com/haiwen/seahub/blob/21c827c68047e13700fe102d22a3f5515b22af89/seahub/settings.py#L484

For a quick command-line interface only solution, preface manage.py with python -W ignore when executing, as in: 对于仅命令行界面的快速解决方案,在执行时使用python -W ignore开头的manage.py,如下所示:

python -W ignore manage.py runserver

-or- -要么-

python -W ignore manage.py shell_plus

-or- -要么-

python -W ignore manage.py makemigrations

This is working for me now, to suppress all of the Django 1.10 deprecation warnings while running Django 1.9. 这现在对我有用,以在运行Django 1.9时禁止所有Django 1.10弃用警告。

Time to add another one suggestion here, which worked for me.是时候在这里添加另一个对我有用的建议了。 Django 3.2, but should work on any version. Django 3.2,但应该适用于任何版本。

What worked for me is assuming that the developers would be clever enough to output these to python stderr , not stdout .对我有用的是假设开发人员足够聪明,可以将这些 output 转换为 python stderr ,而不是stdout They were!他们是!

So..., just redirect stderr to via a standard bash 2>/dev/null所以...,只需通过标准 bash 2>/dev/null将 stderr 重定向到

django-admin findstatic teststatic.css 2>/dev/null
Found 'teststatic.css' here:
  /Users/me/kds2/py2/bemyerp/websec/static/websec/nodelinks/teststatic.css
  /Users/me/kds2/py2/bemyerp/dist/teststatic.css

Of course, bear in mind your context and what this redirection does: suppressing ANY error message.当然,请记住您的上下文以及此重定向的作用:抑制任何错误消息。 For example, if django-admin is missing, that error message will also disappear (run missing-django-admin findstatic teststatic.css 2>/dev/null to see the effect).例如,如果缺少django-admin ,则该错误消息也会消失(运行missing-django-admin findstatic teststatic.css 2>/dev/null以查看效果)。

what I was trying to filter out...我试图过滤掉的东西......

    HINT: Use django.db.models.JSONField instead.
pssystem.TagType: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
    HINT: Configure the DEFAULT_AUTO_FIELD setting or the AppConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
Found 'teststatic.css' here:
  /Users/me/kds2/py2/bemyerp/websec/static/websec/nodelinks/teststatic.css
  /Users/me/kds2/py2/bemyerp/dist/teststatic.css

Things tried without success:尝试没有成功的事情:

(I am not saying these never work, only that they didn't filter the particular messages I was getting and wanted to avoid, in my environment. (我并不是说这些永远不会起作用,只是它们没有过滤掉我在我的环境中收到并想要避免的特定消息。

python -W ignore  manage.py findstatic teststatic.css
PYTHONWARNINGS=ignore django-admin findstatic teststatic.css
PYTHONWARNINGS=ignore python manage.py findstatic teststatic.css
python -Wd manage.py findstatic teststatic.css

env: Django 3.2, using Python 3.10 with virtualenv环境:Django 3.2,使用 Python 3.10 和 virtualenv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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