Home >Backend Development >Python Tutorial >Analysis of Django admin source code (with examples)

Analysis of Django admin source code (with examples)

不言
不言forward
2018-10-08 15:56:082135browse

The content of this article is about the analysis of Django admin source code (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Singleton Pattern

Singleton Pattern is a commonly used software design pattern. The main purpose of this pattern is to ensure that only one instance of a certain class exists. Singleton objects come in handy when you want only one instance of a certain class to appear in the entire system.

For example, the configuration information of a server program is stored in a file, and the client reads the configuration file information through an AppConfig class. If the contents of the configuration file need to be used in many places during the running of the program, that is to say, instances of the AppConfig object need to be created in many places, which will lead to the existence of multiple AppConfig instance objects in the system, which will seriously waste memory resources. , especially when the configuration file contains a lot of content. In fact, for a class like AppConfig, we hope that only one instance object exists while the program is running.

In Python, we can use a variety of methods to implement the singleton pattern:

  • Use __new__()

  • Use module

  • Use decorator

  • Use metaclass

1. Use __new__() method

In order to make only one instance of the class appear, we can use __new__() to control the creation process of the instance. The code is as follows:

__new__() method is used to create instance objects

__init__() method is used to initialize instance objects

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
class Singleton(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        print(1)
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

    def __init__(self, name, age):
        print(2)
        self.name = name
        self.age = age
if __name__ == '__main__':
    p1 = Person("djb", 18)
    p2 = Person("djb", 18)

    print(p1 == p2)
    print(id(p1), id(p2))

    print("=" * 120)

    s1 = Singleton("djb", 18)
    s2 = Singleton("djb", 18)
    print(s1 == s2)
    print(id(s1), id(s2))

2. Use module method

In fact, Python modules are Natural singleton mode, because when the module is imported for the first time, a .pyc file will be generated. When it is imported for the second time, the .pyc file will be loaded directly without executing the module code again. Therefore, we only need to define the relevant functions and data in a module to get a singleton object.

If we really want a singleton class, we can consider doing this:

class Singleton(object):    
def __init__(self, name, age):
        self.name = name
        self.age = age
p1 = Singleton("djb", 18)

Use the following code to test it:

from singleton import p1

print(id(p1))
print(p1.name)
p1.name = "Bob"

from singleton import p1

print(id(p1))
print(p1.name)

Check the remaining two types yourself Information...

admin execution process

f35d6e602fd7d0f0edfa6f7d103c1b57Cycle loading and execution of the admin.py files in all registered apps

def autodiscover():
    autodiscover_modules('admin', register_to=site)

2cc198a1d5eb0d3eb508d858c9f5cbdbExecution Code

#admin.py
class BookAdmin(admin.ModelAdmin):
    list_display = ("title",'publishDate', 'price')
admin.site.register(Book, BookAdmin) 
admin.site.register(Publish)

5bdf4c78156c7953567bb5a0aef2fc53 admin.site

##What is applied here is a singleton mode. For a singleton mode of the AdminSite class, the execution Each admin.site in each app is an object

23889872c2e8594e0f446a471a78ec4c Execute the register method

admin.site.register(Book, BookAdmin) 
admin.site.register(Publish)
class ModelAdmin(BaseModelAdmin):pass
def register(self, model_or_iterable, admin_class=None, **options):
    if not admin_class:
            admin_class = ModelAdmin
    # Instantiate the admin class to save in the registry
    self._registry[model] = admin_class(model, self)

Here, registration is over!

43ad812d3a971134e40facaca816c822 Admin’s URL configuration

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]
class AdminSite(object):
    
     def get_urls(self):
        from django.conf.urls import url, include
        urlpatterns = []
        # Add in each model's views, and create a list of valid URLS for the
        # app_index
        valid_app_labels = []
        for model, model_admin in self._registry.items():
            urlpatterns += [
                url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
            ]
            if model._meta.app_label not in valid_app_labels:
                valid_app_labels.append(model._meta.app_label)
        return urlpatterns
    @property
    def urls(self):
        return self.get_urls(), 'admin', self.name

efbfa0de8737dc86eae413541a49df20 Extension application of url() method

from django.shortcuts import HttpResponse
def test01(request):
    return HttpResponse("test01")
def test02(request):
    return HttpResponse("test02")
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^Xadmin/', ([
                    url(r'^test01/', test01),
                    url(r'^test02/', test02),

                    ],None,None)),
]

Extension optimization

from django.conf.urls import url,include
from django.contrib import admin
from django.shortcuts import HttpResponse
def change_list_view(request):
    return HttpResponse("change_list_view")
def add_view(request):
    return HttpResponse("add_view")
def delete_view(request):
    return HttpResponse("delete_view")
def change_view(request):
    return HttpResponse("change_view")
def get_urls():
    temp=[
        url(r"^$".format(app_name,model_name),change_list_view),
        url(r"^add/$".format(app_name,model_name),add_view),
        url(r"^\d+/del/$".format(app_name,model_name),delete_view),
        url(r"^\d+/change/$".format(app_name,model_name),change_view),
    ]
    return temp
url_list=[]

for model_class,obj in admin.site._registry.items():
    model_name=model_class._meta.model_name
    app_name=model_class._meta.app_label

    # temp=url(r"{0}/{1}/".format(app_name,model_name),(get_urls(),None,None))
    temp=url(r"{0}/{1}/".format(app_name,model_name),include(get_urls()))
    url_list.append(temp)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^Xadmin/', (url_list,None,None)),
]

The above is the detailed content of Analysis of Django admin source code (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete