补充:
一、django中间件之路由斜杠的自动添加源码
其实我们每次在写路由的时候,如果在路由层给他设置的是加/,但实际上我们在浏览器中输入的时候并没有加/发现也能调用,前面说了是浏览器内部走了重定向,所以会自动的给我们加上/匹配,但是难道我们就不好奇究竟是谁让他内部走了重定向吗?
想想,它在第一次来的时候没有匹配上路由就会直接重定向,那他肯定是还没走到视图层,在想一想django的请求生命周期,来了请求之后,进入django内部是不是要先经过什么?好像是中间件!!那就必然和中间件有某种关系,然后我们在去查看中间件的源码的时候,发现了果然如此!
# 查看中间件源码的方式 from django.middleware.common import CommonMiddleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # 内部重定向,刚开始没有斜杠会自动加斜杠,内部走了301重定向 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
我们看了一下是CommonMiddleware这个中间件做的鬼,那我们就点进去看看!
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class CommonMiddleware(MiddlewareMixin): """ "Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, this middleware appends missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the initial URL doesn't end with a slash, and it is not found in urlpatterns, a new URL is formed by appending a slash at the end. If this new URL is found in urlpatterns, then an HTTP-redirect is returned to this new URL; otherwise the initial URL is processed as usual. This behavior can be customized by subclassing CommonMiddleware and overriding the response_redirect_class attribute. - ETags: If the USE_ETAGS setting is set, ETags will be calculated from the entire page content and Not Modified responses will be returned appropriately. USE_ETAGS is deprecated in favor of ConditionalGetMiddleware. """ response_redirect_class = http.HttpResponsePermanentRedirect # 点进去看看,发现内部走了重定向 class HttpResponsePermanentRedirect(HttpResponseRedirectBase): status_code = 301
发现在内部其实是走了301重定向
二、django模型表之一对一关系源码
入口
class Book(models.Model): title = models.CharField(max_length=32) price = models.IntegerField() # 就是它