render
render返回一个HTML页面 而且还能给该页面传数据
render内部原理
from django.shortcuts import render,HttpResponse # Create your views here. from django.template import Template,Context def index(request): temp = Template('<h1>{{ user }}</h1>') con = Context({'user':{'name':'baobo','age':'18'}}) res = temp.render(con) print(res) return HttpResponse(res)
理论:
先将所有的内容读取字符串,在用Context将信息传进去,然后将数据返回给前端.
FBV与CBV
视图函数并不只是函数,也可以是类.
FBV:面向函数式编程,基于函数的视图.
CBV:面向对象式编程,基于类的视图.
基于cbv的视图
from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r'^login/', views.Login.as_view()), ]
from django.shortcuts import render,HttpResponse from django.views import View class Login(View): def get(self,request): print('login的get') return render(request,'login.html') def post(self,request): return HttpResponse('from post')
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form action="" method="post"> <input type="text" name="username"> <input type="submit"> </form> </body> </html>
页面
由此得到了一个问题:为什么get请求来就会走类里面的get方法,post请求来就会走类里面的post方法
分析:
从源头开始分析:
函数名加括号时,执行优先级最高,所以程序会先执行as_view()方法.
点进View查看源码,去查看as_view()
@classonlymethod def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): self.head = self.get self.request = request self.args = args self.kwargs = kwargs return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs)
@classonlymethod def as_view(cls, **initkwargs): #cls是自己写的类Login def view(request, *args, **kwargs): self = cls(**initkwargs) #实例化产生Login的对象 即self=Login(**initkwargs) if hasattr(self, 'get') and not hasattr(self, 'head'): #判断 self.head = self.get self.request = request self.args = args self.kwargs = kwargs #为对象新增属性 return self.dispatch(request, *args, **kwargs) #返回信息 #diapatch返回什么,浏览器就收到什么 #涉及到了一个对象的查找属性或方法的顺序 -- 先在对象本身找,然后从产生对象的类里面找,再到产生对象的类的父类中进行查找,依次往后. return view
通过源码发现url匹配条件可以变形为 url('^login/',views.view)
得出结论
FBV 和 CBV 在 路由匹配上是一致的,都是url + 函数的内存地址
当浏览器在输入login会立刻触发view函数的运行:
def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. #判断请求方式是否在默认的八个方法中 if request.method.lower() in self.http_method_names: # http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] #getattr 反射获取类产生的属性或方法 #以GET为例, handler = getattr(self,'get','取不到报错信息') #handler = get(request) handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs) #直接调用我们自己的写的类里面的get方法 #源码中先通过判断请求方法是否符合默认的八个方法,然后通过反射获取到自定义类中的对应方法执行
django之settings源码
前提:
1.django除了暴露给用户一个settings.py配置文件之外 自己内部还有一个全局的配置文件
2.我们在使用配置文件的时候 可以直接直接导入暴露给用户的settings.py也可以使用django全局的配置文件 并且后者居多
from django.conf import settings
3.django的启动入口是manage.py
问题
为什么settings的常量都是大写
import os import sys if __name__ == "__main__": # django在启动的时候 就会往全局的大字典中设置一个键值对 值是暴露给用户的配置文件的路径字符串 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "day54.settings")
settings = LazySettings()
重复导入一个文件,单例模式
class LazySettings(LazyObject): def _setup(self, name=None): # os.environ你可以把它看成是一个全局的大字典 # 从大字典中取值 键为DJANGO_SETTINGS_MODULE 值为day54.settings #settings_mode = 'day54.settings' settings_module = os.environ.get(ENVIRONMENT_VARIABLE) # Settings('day54.settings') self._wrapped = Settings(settings_module)