Analysis of Django admin source code (with examples)

不言
Release: 2018-10-08 15:56:08
forward
2109 people have browsed it

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))
Copy after login

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)
Copy after login

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)
Copy after login

Check the remaining two types yourself Information...

admin execution process

<1>Cycle loading and execution of the admin.py files in all registered apps

def autodiscover():
    autodiscover_modules(&#39;admin&#39;, register_to=site)
Copy after login

<2>Execution Code

#admin.py
class BookAdmin(admin.ModelAdmin):
    list_display = ("title",&#39;publishDate&#39;, &#39;price&#39;)
admin.site.register(Book, BookAdmin) 
admin.site.register(Publish)
Copy after login

<3> 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

<4> Execute the register method

admin.site.register(Book, BookAdmin) 
admin.site.register(Publish)
Copy after login
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)
Copy after login

Here, registration is over!

<5> Admin’s URL configuration

urlpatterns = [
    url(r&#39;^admin/&#39;, admin.site.urls),
]
Copy after login
class AdminSite(object):
    
     def get_urls(self):
        from django.conf.urls import url, include
        urlpatterns = []
        # Add in each model&#39;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&#39;^%s/%s/&#39; % (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(), &#39;admin&#39;, self.name
Copy after login

<6> 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&#39;^admin/&#39;, admin.site.urls),
    url(r&#39;^Xadmin/&#39;, ([
                    url(r&#39;^test01/&#39;, test01),
                    url(r&#39;^test02/&#39;, test02),

                    ],None,None)),
]
Copy after login

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&#39;^admin/&#39;, admin.site.urls),
    url(r&#39;^Xadmin/&#39;, (url_list,None,None)),
]
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template