Moment For Technology

Keeping up with the django - plug type design | Python theme

Posted on Dec. 2, 2022, 6:20 p.m. by Melissa Evans
Category: The back-end Tag: python The back-end

This article is participating in Python Theme Month. See the link to the event for more details

No road taken in vain, every step counts

preface

In a django full-stack project, the front end of a post request is required to comment the CSRF validation when submitting a post request to the back end. After you comment the code, you don't need to check it. How can you comment out the entire function with just one line of code? This article will describe how plug-and-plug design is implemented.

Plug-and-plug design

The pluggable design implementation requires the use of a module, importlib, which converts string paths into the syntax format of the imported module.

# Import module's normal writing
from module import object

# use importlib
import importlib
res = 'myfile.test'
ret = importlib.import_module(res)  # from myfile import b
Copy the code

You can simulate the notification message through this code design, simple version of wechat QQ SMS and other messages sent at the same time, and can be very convenient to close a notification channel.

Method 1: conventional thinking

Create a py file, define each function as a function, and create a startup file, import the defined function, and run it in the startup file.

Myfile folder - notify.pydef wechat(content) :
    print(F 'wechat Notification:{content}')


def message(content) :
    print(F 'SMS Notification:{content}')

def qq(content) :
    print(F 'qq notification{content}')
    
    
- start.py
import notify

def send(content) :
    notify.wechat(content)
    notify.message(content)
    notify.qq(content)

if __name__ == '__main__':
    send('Class dismissed')
Copy the code

Method two: object-oriented

  • Taking a page from the Django middleware idea, each feature has its own py file, all in one directory.
  • Create a settings.py configuration file and write the path of the specific object in the module that needs to be imported as a string to the list.
  • Each PY file in the function folder is a function module, so the folder is a package, so it needs to be created in that folder__init__.pyFile, put the name of each function module under the py file
  • in__init__.pyIn this file, a for loop + duck type + string method + reflection enables djangosettings. Py to add or remove certain functions by simply commenting or uncommenting them
The # notify folder is the package
- email.py

class Email() :
    def __init__(self) :
        # Call the application interface
        pass
    def send(self,content) :
        print(f'email{content}')
        
- qq.py
class QQ() :
    def __init__(self) :
        # Call the application interface
        pass
    def send(self,content) :
        print(f'qq{content}')
        
-wechat.py
class Wechat() :
    def __init__(self) :
        # Call the application interface
        pass
    def send(self,content) :
        print(f'wechat{content}')
    

- settings.py

NOTIFY_LIST = [
    'notify.email.Email'.'notify.qq.QQ'.'notify.wechat.Wechat'
]

- __init__.py

import settings
import importlib


def send_all(content) :
    for path_str in settings.NOTIFY_LIST:  #'notify.email.Email'
        module_path,class_name = path_str.rsplit('. ',maxsplit=1)
        # module_path = 'notify.email' class_name = 'Email'
        # 1 Import modules using strings
        module = importlib.import_module(module_path)  # from notify import email
        # 2 Uses reflection to get the class name
        cls = getattr(module,class_name)  # Email, QQ, Wechat
        # 3 Generate the object of the class
        obj = cls()
        # 4 Call send directly with the duck type
        obj.send(content)
        
        
- start.py

import notify
if __name__ == '__main__':
    notify.send_all('haha')
Copy the code

conclusion

The article was first published in the wechat public account program Yuan Xiaozhuang, synchronized with nuggets.

Please explain where it came from. If you pass by, please put out your cute little finger and click like before you go (╹▽╹)

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.