【Django】一、Django技巧
阿新 • • 發佈:2021-01-07
Django技巧
一、Django自定義變數初始化
1、自定義初始化【lower】
自定義在app下建立‘app_initialize.py
'檔案,檔案下建立’def initialize()‘
方法,只需將需要初始化的內容寫入到該方法中即可。當然也可以寫到方法外。方法內變數初始化儘量以快取的方式進行儲存。
manage.py
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from django.apps.config import AppConfig
from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured
from importlib import import_module
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'medicine_structure.settings')
try:
from django. core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
def load_initialize():
"""
This initialize can not operate Model, Urls, Views
:return:
"""
from django.apps import apps
from django.conf import settings
from django.utils.module_loading import module_has_submodule
print('settings.INSTALLED_APPS:', settings.INSTALLED_APPS)
installed_apps = settings.INSTALLED_APPS
app_configs = {}
for entry in installed_apps:
if isinstance(entry, AppConfig):
app_config = entry
else:
app_config = AppConfig.create(entry)
if app_config.label in app_configs:
raise ImproperlyConfigured(
"Application labels aren't unique, "
"duplicates: %s" % app_config.label)
app_configs[app_config.label] = app_config
# loading app_initialize.py
for label, app_config in app_configs.items():
if module_has_submodule(app_config.module, 'app_initialize'):
models_module_name = '%s.%s' % (app_config.name, 'app_initialize')
initialize_module = import_module(models_module_name)
initialize_module.initialize()
print('App %s initialize complete.' % str(initialize_module))
if __name__ == '__main__':
load_initialize() # 用於初始化載入app下的app_initialize.py檔案,以及檔案下的initialize方法。
main()
app_initialize.py
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :app_initialize.py
# @Time :2021/1/6 0006 12:07
# @Author :gaofei
# @Note : Can not import Model
"""
Update method for rewrite method of apps.ready.
This has been destroyed.
"""
def initialize():
pass
if __name__ == "__main__":
pass
2、藉助APP初始化
在每個app目錄下都有apps.py
檔案,檔案中註冊了當前app的類,該類下可以重寫ready()
方法,用於在django內該APP所有其他配置初始化後的載入方式。
當然很多人說,可以直接寫入到專案下的settings.py檔案中,但是,如果在寫入的時候,你需要匯入專案的model【即models.py下的模型】,那麼django會報錯,不允許在註冊model之前使用該model。所以,應該在model註冊時候使用。
正好ready()方法就是用於model註冊後給到的重寫方法。
如下為app下的apps.py檔案。