django之setup()
#django包的__init__.py包含setup函数
def setup():
"""
Configure the settings (this happens as a side effect of accessing the
first setting), configure logging and populate the app registry.
"""
from django.apps import apps
from django.conf import settings
from django.utils.log import configure_logging configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
apps.populate(settings.INSTALLED_APPS)#apps对象安装app
def populate(self, installed_apps=None):
"""
Loads application configurations and models. This method imports each application module and then each model module. It is thread safe and idempotent, but not reentrant.
"""
if self.ready:
return # populate() might be called by two threads in parallel on servers
# that create threads before initializing the WSGI callable.
with self._lock:
if self.ready:
return # app_config should be pristine, otherwise the code below won't
# guarantee that the order matches the order in INSTALLED_APPS.
if self.app_configs:
raise RuntimeError("populate() isn't reentrant") # Load app configs and app modules.
for entry in installed_apps:
if isinstance(entry, AppConfig):
app_config = entry
else:
app_config = AppConfig.create(entry)#创建一个AppConfig对象
if app_config.label in self.app_configs:
raise ImproperlyConfigured(
"Application labels aren't unique, "
"duplicates: %s" % app_config.label) self.app_configs[app_config.label] = app_config # Check for duplicate app names.
counts = Counter( #判断有无重复的AppConfig对象对象
app_config.name for app_config in self.app_configs.values())
duplicates = [
name for name, count in counts.most_common() if count > 1]
if duplicates:
raise ImproperlyConfigured(
"Application names aren't unique, "
"duplicates: %s" % ", ".join(duplicates)) self.apps_ready = True # Load models.
for app_config in self.app_configs.values():#为每个app导入models_module
all_models = self.all_models[app_config.label]
app_config.import_models(all_models) self.clear_cache() self.models_ready = True for app_config in self.get_app_configs():
app_config.ready() self.ready = True #以django.contrib.admin为例说明create过程
default_app_config = 'django.contrib.admin.apps.AdminConfig' class SimpleAdminConfig(AppConfig):
"""Simple AppConfig which does not do automatic discovery.""" name = 'django.contrib.admin' #作为app_name
verbose_name = _("Administration") def ready(self):
checks.register(check_admin_app, checks.Tags.admin) class AdminConfig(SimpleAdminConfig):
"""The default AppConfig for admin which does autodiscovery.""" def ready(self):
super(AdminConfig, self).ready()
self.module.autodiscover()
@classmethod #AppConfig类的创建方法
def create(cls, entry):
"""
Factory that creates an app config from an entry in INSTALLED_APPS.
"""
try:
# If import_module succeeds, entry is a path to an app module,
# which may specify an app config class with default_app_config.
# Otherwise, entry is a path to an app config class or an error.
module = import_module(entry)#会导入包的__init__.py except ImportError:
# Track that importing as an app module failed. If importing as an
# app config class fails too, we'll trigger the ImportError again.
module = None mod_path, _, cls_name = entry.rpartition('.') # Raise the original exception when entry cannot be a path to an
# app config class.
if not mod_path:
raise else:
try:
# If this works, the app module specifies an app config class.
entry = module.default_app_config#从模块对象中取得默认配置文件类
except AttributeError:
# Otherwise, it simply uses the default app config class.
return cls(entry, module)
else:
mod_path, _, cls_name = entry.rpartition('.')#分解成路径和类名 # If we're reaching this point, we must attempt to load the app config
# class located at <mod_path>.<cls_name>
mod = import_module(mod_path)#导入apps模块
try:
cls = getattr(mod, cls_name)#取得类对象,比如在admin中为AdminConfig
except AttributeError:
if module is None:
# If importing as an app module failed, that error probably
# contains the most informative traceback. Trigger it again.
import_module(entry)
else:
raise # Check for obvious errors. (This check prevents duck typing, but
# it could be removed if it became a problem in practice.)
if not issubclass(cls, AppConfig):
raise ImproperlyConfigured(
"'%s' isn't a subclass of AppConfig." % entry) # Obtain app name here rather than in AppClass.__init__ to keep
# all error checking for entries in INSTALLED_APPS in one place.
try:
app_name = cls.name#类对象中指定的name,比如name = 'django.contrib.admin'可以有'.'。
except AttributeError:
raise ImproperlyConfigured(
"'%s' must supply a name attribute." % entry) # Ensure app_name points to a valid module.
app_module = import_module(app_name)#再次导入模块 # Entry is a path to an app config class.
return cls(app_name, app_module)
现在的问题是什么时候导入models。
django之setup()的更多相关文章
- Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 httplib模块 django和web服务器整合 wsgi模块 gunicorn模块
Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 ...
- Python-Django 第一个Django app
第一个Django app by:授客 QQ:1033553122 测试环境: Python版本:python-3.4.0.amd64 下载地址:https://www.python.org/do ...
- django linux环境部署
一.操作环境: 1操作系统:Ctrip-CentOS-7.1-x86_64-R3 Python版本:2.7.5 Django版本: Django 1.8.19 (LTS) 二.部署流程 pip ins ...
- django创建第一个子文件夹
1.首先安装python, 我安装了Python2.7的版本,安装在了D:\Python25\2.接着安装django,我下载了django 1.6的版本.3. 安装完了之后,打开cmd,然后可以检验 ...
- python web django base skill
web框架本质 socket + 业务逻辑 框架实现socket tonado node.js 使用WSGI实现socket django flask 自己实现框架思路 wsgiref socket ...
- s11 day 101 python Linux环境安装 与路飞项目支付功能
from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = ...
- Python-Django的windows环境
下载安装python2.7 : 最好是安装win32的,64bit的很多的lib都不支持.python-2.7.3 http://python.org/getit/releases/2.7.3/ 下载 ...
- 用django创建一个项目
首先你得安装好python和django,然后配置好环境变量,安装python就不说了,从配置环境变量开始 1.配置环境变量 在我的电脑处点击右键,或者打开 控制面板\系统和安全\系统 -> 左 ...
- [DJANGO] excel十几万行数据快速导入数据库研究
先贴原来的导入数据代码: 8 import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "www.setting ...
随机推荐
- 《Java并发编程实战》笔记-synchronized和ReentrantLock
在一些内置锁无法满足需求的情况下,ReentrantLock可以作为一种高级工具.当震要一些高级功能时才应该使用ReentrantLock,这些功能包括:可定时的.可轮询的与可中断的锁获取操作,公平队 ...
- 新建本地仓库,同步远程仓场景,出现git branch --set-upstream-to=origin/master master 解决方法
1.本地创建一个本地仓库 2.关联远程端:git remote add origin git@github.com:用户名/远程库名.git3.同步远程仓库到本地git pull这个时候会报错If y ...
- MySQL锁之三:MySQL的共享锁与排它锁编码演示
一.行锁之MySQL 使用SELECT ... FOR UPDATE 做事务写入前的确认 以MySQL 的InnoDB 为例,预设的Tansaction isolation level 为REPEA ...
- [UE4]点积、余弦和急停
急停控制:
- Java中的Future相关
先上一个场景:假如你突然想做饭,但是没有厨具,也没有食材.网上购买厨具比较方便,食材去超市买更放心. 实现分析:在快递员送厨具的期间,我们肯定不会闲着,可以去超市买食材.所以,在主线程里面另起一个子线 ...
- 如何用MAT分析Android程序的内存泄露
本文结合<Android开发艺术探索>书籍中的内存分析例子来讲解如何利用MAT工具来查找内存泄漏(以AndroidStudio开发工具为例). 1.下载MAT(Eclipse Memory ...
- 搭建postgresql集群的问题汇总
问题一:如何配置pg远程访问 修改postgresql.conf-->listen_addresses = '*' 修改pg_hba.conf-->添加 ...
- 初始Golang
Golang初识 字节跳动也就是我们常说的今日头条 1.今日头条基于Go语言构建千亿级微服务的实践 今日头条当前后端服务超过80%的流量是跑在Go构建的服务上 微服务数量超过100个 高峰QPS超过7 ...
- (转)CS域和PS域
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/u013485792/article/details/50818356 CS域和PS域的区别: 1.基 ...
- 03-String常用方法
1.获取方法 /* * 编辑:刘诗华 int length() 获取字符串的长度 char charAt(int index) 获取特定位置的字符 (角标越界) int indexOf(String ...