How does "Django" Customize the manage.py command? Achieve the purpose of starting a background process?

Source: Internet
Author: User

Code:

#-*-coding:utf-8-*-"""The handle active user mail send""" fromDjango.core.management.Baseimport Basecommand, CommandError fromdjango.db Import models# fromPlaceholders Import *import osimport timeimport logginglogger= Logging.getlogger ("File_protect.alarm_handler") Logger= Logging.getlogger ("file_protect.views")classCommand (basecommand): def handle (self,*args, * *options): Print'Hello, django!.'         while(True): Logger.debug ("Hello, Django") Time.sleep (5)

Start

################### #系统软件安装-Use apt-Get installation ################### #apt-GetUPDATE-QQ-yapt-GetInstall Libmysqlclient-dev PYTHON-DEV-QQ-yapt-GetInstall Libmysqlclient-dev Python-dev DAEMON-QQ-y################ #启动日志处理Daemon #############################ifDaemon-n Alarm_handler_daemon--running; then daemon.-N Alarm_handler_daemon--STOPFI whileDaemon-n Alarm_handler_daemon--running; DoSleep1Donedaemon-N alarm_handler_daemon-r/opt/env/ubuntu1227/bin/python $API _project_dir/manage.py Alarm_handlerecho"Alarm_handler_daemon is running"

We've all used Django's django-admin.py and manage.py. django-admin.py is a command-line tool that can perform some administrative tasks, such as creating a Django project. And manage.py is automatically added to the project directory when each Django project is created, just a simple wrapper for manage.py, with the ability to put Django project into the Sys.path directory while setting the Django_ The SETTINGS_MODULE environment variable is the setting.py file for the current project.


django-admin.py calls Django.core.management to execute the command:

#!/usr/bin/env python
From Django.core Import Management

if __name__ = = "__main__":
Management.execute_from_command_line ()

The excute_from_command_line () function resolves the name of the command based on the command line arguments and invokes the command execution commands according to the command name. The command is located under the commands module of each management module.

The so-called management module refers to the module named management under the app module. Django discovers the "management module" through the Django.core.management.find_management_module function:

Django.core.management.find_management_module ()
def find_management_module (app_name):
"""
Determines the path to the management module for the given App_name,
Without actually importing the application or the management module.

Raises importerror if the management module cannot is found for any reason.
"""
Parts = App_name.split ('. ')
Parts.append (' management ')
Parts.reverse ()
Part = Parts.pop ()
Path = None


The command class is then found through the Django.core.management.find_commands function. The Find_commands function looks for the. py file under the Management module and matches the name of the. py file to the command name:

def find_commands (Management_dir):
"""
Given a path to a management directory, returns a list of all the command
Names that is available.

Returns an empty list if no commands is defined.
"""
Command_dir = Os.path.join (management_dir, ' commands ')
Try
return [f[:-3] for F in Os.listdir (Command_dir)
If not F.startswith ('_') and F.endswith ('. Py ')]
Except OSError:
return []

Finally, the command class in the. py file is loaded with the Django.core.management.load_command_class function:

def load_command_class (app_name, name):
"""
Given a command name and an application name, returns the command
class instance. All errors raised by the import process
(Importerror, Attributeerror) is allowed to propagate.
"""
module = import_module ('%s.management.commands.%s '% (app_name, name))
Return Module.command ()

When executing the command, the handle method of the corresponding command class is executed. All command classes should be direct or indirect subclasses of the Django.core.management.base.BaseCommand.

The principle is clear, it is easy to extend the Manage command. Create an app and add it to Settings's Installed_apps, create a management.commands module under the app, and create a hello.py file:

From django.core.management.base import Basecommand, CommandError
From django.db import Models
#from Placeholders Import *
Import OS

Class Command (Basecommand):
def handle (self, *args, **options):
print ' Hello, django! '

You can use the Hello command:

$ python manage.py Hello
Hello, django!.

Resources:

Extension: http://www.cnblogs.com/holbrook/archive/2012/03/09/2387679.html

https://www.v2ex.com/t/58381

Http://janetriley.net/2014/11/quick-how-to-custom-django-management-commands.html

Http://www.cnblogs.com/linjiqin/p/3965046.html

https://www.v2ex.com/t/58381

https://github.com/mitnk/tengtweets/blob/master/manage.py

How does "Django" Customize the manage.py command? Achieve the purpose of starting a background process?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.