A, FBV and CBV
Function does not only refer to the view function may be based
FBV: view function based on, for similar functional programming
CBV: view class-based, object-oriented programming similar
On the analytical render Source:
render: Returns html page; and able to pass the page value
Analysis: FBV view principle
from django.shortcuts import render,HttpResponse # Create your views here. from django.template import Template,Context # FBV解析 def index(request): temp = Template('<h1>{{ user }}</h1>') con = Context({"user":{"name":'gets','password':'123456'}}) res =temp.render(con) print(res) return HttpResponse(res)
print results:
Can be analyzed to obtain the data format, by CON = the Context ({ " User " : { " name " : ' the gets ' , ' password ' : ' 123456 ' }}) turn pass into a dictionary in the form of front-end display
Analysis CBV view principle: class method
Question: Based on CBV view function, get requests will go inside the class get method, post the request will go to class inside the post method Why ???
Why is automatically distributed get / post requests class method in it? What is automatic identification?
#CBV视图 from django.views import View from django.conf import settings class MyLogin(View): def get(self,request): print("from MyLogin get方法") 为什么会走get/post return render(request,'login.html') def post(self,request): return HttpResponse("from MyLogin post方法")
CBV routing layer: url
Since the function name in parentheses implementation of the highest priority, so this sentence will execute a written as_view immediately () method
1, starting from the url analyzed for the presence of this phenomenon: analysis as_view source analytical results:
Source Analysis:
@classonlymethod DEF as_view (CLS, ** initkwargs): # CLS is our own writing class MyLogin DEF View (Request, * args, ** kwargs): Self = CLS (** initkwargs) # instantiated objects produced MyLogin = mylogin Self (** ininkwargs) IF the hasattr (Self, ' GET ' ) and Not the hasattr (Self, ' head ' ): self.head = self.get self.request = Request self.args = args self.kwargs = kwargs # the above are just a few words in a new attribute to the object return self.dispatch (Request, * args, ** kwargs) # dispatch to return what the browser will receive what # object lookup property or method when you have to start with the object of meditation find yourself here then generated from the class object inside to find the last class of the parent class turn back return View
Source found by matching relation can be deformed url
url (R & lt ' ^ Login / ' , views.view) # the FBV and CBV are matched on the route are consistent with the memory address of a function behind the url
2, when the browser, enter login, will immediately trigger the run view function
The second part analyzes the source code:
DEF dispatch (Self, Request, * args, ** kwargs): # the Try to dispatch to Method, at The right; IF A Method, does not exist, # the defer to the defer Also at The Handler error to error Handler at The IF at The. # Request Method, . iS not oN at the Approved List # 's start with an example gET iF request.method.lower () in self.http_method_names: # judge whether the current request method within eight default method # reflex get to write our own class produce the object's property or method # to Example GET handler = getattr (self, 'get ', ' not being given the information acquisition') # Handler = GET (Request) Handler = getattr (Self, request.method.lower () , self.http_method_not_allowed) the else : Handler = self.http_method_not_allowed return Handler (Request, * args, ** kwargs) # direct call to get the class to write our own method inside # source code to the request by way of judgment whether the default method then get to eight requests by reflecting custom class corresponding method for performing
By .re_view method of routing layer url parsing source code analysis results to achieve the principle of get / post requests distribution, what is left of what request method
Django settings source code analysis:
premise:
1, diango in addition exposed to a settings.py configuration file in the user's own internal as well as a global configuration file (just shows settnigs partial information).
2, when we use the configuration file that can be imported directly exposed to the user can also use django settings.py global configuration file to ask
Import module requires: from django.conf Import Settings
Click to view the source code configuration settings file
3, is started inlet django manage.py
Analyze why the variable name in the configuration file settings are in uppercase? Why would not it written in lower case?
Based on the above analysis of the source code, to achieve seettings analysis functions, limited variable names must be written in uppercase
Import os Import SYS IF __name__ == " __main__ " : # Django will set a key to global large dictionary when you start the path string value is exposed to the user's profile os.environ.setdefault ( " DJANGO_SETTINGS_MODULE " , " day54.settings " ) class Settings (Object): DEF __init__ (Self, settings_module): # settings_module = 'day54.settings' # Update from the this dict, Ltd. Free Join Settings (But only for ALL_CAPS Settings) or Setting in dir ( global_settings): #django global configuration file # dir get all variable names django global configuration file IF setting.isupper (): # whether the variable name in uppercase file to determine if it is in uppercase will be performed / take effect setattr (self, setting, getattr ( global_settings , setting)) # to the settings of the target setting key # to the settings of the object variable name setting key settings [uppercase profile variable name] = uppercase profile corresponding value # Store Case the settings in someone later Module1 CARES self.SETTINGS_MODULE settings_module = # 'day54.settings' MOD = importlib.import_module (self.SETTINGS_MODULE) # MOD = Settings module (exposed to the user's profile) for Setting in the dir (MOD): # for obtaining loop exposed to the user All of the configuration file variable names ifsetting.isupper (): # determines whether or not the variable name is capitalized setting_value = getattr (MOD, Setting) # Get the value of the variable name uppercase corresponding setattr (Self, Setting, setting_value) # to the settings of the setting key objects "" " D = {} D [ 'username'] = 'Jason' D [ 'username'] = 'Egon' if the user is configured to use the user is not configured to default by system users actually essentially using the dictionary keys exist is replaced the realization of the principle of user profiles on a user's user is not configured to use the default "" "
Inherited class analysis:
class LazySettings (LazyObject): DEF _setup (Self, name = None): # os.environ you can think of it as a big global dictionary settings_module = os.environ.get (ENVIRONMENT_VARIABLE) # from a large dictionary key value the corresponding value DJANGO_SETTINGS_MODULE: day54.settings # settings_module = 'day54.settings' self._wrapped = Settings (settings_module) # Settings ( 'day54.settings')
Settings = LazySettings () # singleton
Job:
Reference django settings source implementation of their projects can be done on a user profile with the user's user is not configured to use global
__init__.py file:
Import os Import importlib from lib.conf Import global_settings class Settings (Object): DEF __init__ (Self): # first loop to get global configuration file for all of the variable names for name in dir (global_settings): # determine whether the capital IF name .isupper (): # to the settings of the setting key objects setattr (Self, name, getattr (global_settings, name)) path = os.environ.get ( ' XXX ' ) Module1 =importlib.import_module (path) # recirculation file to the user's exposure to all of the variable names for name in dir (Module): IF name.isupper (): k = name v = getattr (Module, name) setattr (Self, k , v) Settings = Settings ()
start.py file
Import OS Import SYS base_dir = os.path.dirname ( __FILE__ ) sys.path.append (base_dir) IF the __name__ == ' __main__ ' : # in the project a large global dictionary os.environ.setdefault ( ' XXX ' , ' conf.settings ' ) from lib.conf Import Settings Print (settings.NAME)
Django template layer
Template syntax
Only need to remember two special symbols: {} {} and { %% } variable associated with {{}}, {logic associated with %%}.