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 ...
随机推荐
- google使用的开源的工具类Thumbnailator图像处理
maven依赖 <dependency> <groupId>net.coobird</groupId> <artifactId>thum ...
- 算法:整数与ip地址转换
直接上代码(不要直接拷贝,中间少了一行啊): #include <string> #include <iostream> using namespace std; ...
- noi2017 day2t2
设a[i]为当前方案中第 1..i 天变质的蔬菜有几个,b[i]为前i天至少能卖出几个,方案可行的条件是对任意i有a[i]<=b[i],用线段树维护b[i]-a[i]. 从小到大枚举天数,枚举到 ...
- python接口自动化20-requests获取响应时间(elapsed)与超时(timeout) ok试了 获取响应时间的
前言 requests发请求时,接口的响应时间,也是我们需要关注的一个点,如果响应时间太长,也是不合理的.如果服务端没及时响应,也不能一直等着,可以设置一个timeout超时的时间 关于request ...
- 服务容错保护断路器Hystrix之五:配置
接着<服务容错保护断路器Hystrix之二:Hystrix工作流程解析>中的<2.8.关于配置>再列举重要的配置如下 一.hystrix在生产中的建议 1.保持timeout的 ...
- spring4.0之六:Generic Qualifier(泛型限定)
Spring 4.0已经发布RELEASE版本,不仅支持Java8,而且向下兼容到JavaSE6/JavaEE6,并移出了相关废弃类,新添加如Java8的支持.Groovy式Bean定义DSL.对核心 ...
- mysql查询优化之一:mysql查询优化常用方式
一.为什么查询速度会慢? 一个查询的生命周期大致可以按照顺序来看:从客户端,到服务器,然后在服务器上进行解析,生成执行计划,执行,并返回结果给客户端.其中在“执行”阶段包含了大量为了检索数据到存储引擎 ...
- 改变端口的方法phpstudy
document.ready 一个页面可以用无数次: window.onload 一个页面只能用一次,并且在最顶层: 用户交互:用户在网页上的一些行为: 服务交互:Ajax: 组件:(白话:按照我的规 ...
- google chrome浏览器 程序无法启动并行配置不正确
启动电脑后打开chrome弹出如下信息: 系统:win7 进入chrome的安装路径 C:\Program Files (x86)\Google\Chrome\Application 两个版本文件夹, ...
- Jmeter(四十三)WebSocket Sampler 和 Ajax Request
权利被放出牢笼,就很难再被关入笼中:奴性被唤出来,腰杆和膝盖很难再直起来. ----宅猪<牧神记> websocket: 参考:https://blog.csdn.net/minmint ...