当前位置: 移动技术网 > IT编程>脚本编程>Python > python Django中的apps.py的目的是什么

python Django中的apps.py的目的是什么

2018年11月09日  | 移动技术网IT编程  | 我要评论

武汉电影网,兴宁市人民医院,上虞论坛

this question has been asked earlier: 07000

application configuration objects store metadata for an application. some attributes can be configured in appconfig subclasses. others are set by django and read-only.

但是,应用程序的元数据是什么意思?只限于 appconfig  : , , , , , 吗?

或者扩展超出预定义的元数据,特别是对于特定于应用程序的元数据,例如在博客应用程序中,我们有一个日期格式配置,通常定义如下:

# file: settings.py
blog = {
  'date_format': 'ddmmyyy',
}

正在使用如下:

# file: blog/<...>.py
from django.conf import settings
date_format = settings.blog['date_format']

相反,我们可以将此配置移动到blog / apps.py作为blogconfig?

class blogconfig(appconfig):
  name = 'blog'
  verbose_name = 'awesome blog'
  date_format = 'ddmmyyyy'

所以在应用程序的整个代码中,date_format正在被使用:

# file: blog/<...>.py
from django.apps import apps
date_format = apps.get_app_config('blog').date_format

对我来说,settings.py是项目设置,但不是应用程序设置.因此,将所有应用程序设置放在apps.py中,然后将settings.py放在更多的位置.那么,这是一个有效的假设/参数/惯例,将应用程序配置放在apps.py而不是settings.py中?

一个项目是唯一的django安装,而一个应用程序应该是可重用的.

如果您将自定义应用设置放在项目的settings.py中,那么它们应该是可修改的,特别是如果您(或其他人)将该应用重新用于另一个项目.

现在,如果您将这些自定义设置放在应用程序的apps.py中,这意味着它们将不会在每个项目的基础上进行修改.在这种情况下,没有理由将它们放在apps.py中,而不是在常量子模块中.除非你想提供一组有限的可能的配置:

class blogconfig(appconfig):
  name = 'blog'
  verbose_name = "blog"
  date_format = 'ddmmyyyy'
class customizabledateformatblogconfig(blogconfig):
  date_format = getattr(settings, 'blog_date_format', blogconfig.date_format)
class i18nblogconfig(blogconfig)
  verbose_name = _("blog")

default_app_config将是blogconfig,但使用该应用程序的项目也可以选择customizabledateformatblogconfig或i18nblogconfig.

然而,这使得非常可定制的应用程序.在上面的示例中,如果要让应用程序用户同时使用customizabledateformatblogconfig和i18nblogconfig,则需要执行以下操作:

class blogconfig(appconfig):
  name = 'blog'
  verbose_name = "blog"
  date_format = 'ddmmyyyy'
class customizabledateformatmixin:
  date_format = getattr(settings, 'blog_date_format', blogconfig.date_format)
class i18nmixin:
  verbose_name = _("blog")
class customizabledateformatblogconfig(customizabledateformatmixin, blogconfig):
  pass
class i18nblogconfig(i18nmixin, blogconfig):
  pass
class i18ncustomizabledateformatblogconfig(i18nmixin, customizabledateformatmixin, blogconfig):
  pass

因此,除了需要提供一组不同的应用配置的具体情况外,您最好将自定义应用设置放在项目的settings.py中.

总结

以上所述是小编给大家介绍的python  django中的apps.py的目的是什么,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网