The following describes how to use and extend manage commands in the Python Django framework: pythondjango

Source: Internet
Author: User
Tags install django

The following describes how to use and extend manage commands in the Python Django framework: pythondjango

[Overview]

Django-admin.py is a command line tool for Django to manage tasks. This article describes its general usage.

In addition, there is a manage. py in each Django project. Manage. py is a simple package for the django-admin.py, which extra helps us do two things:

It places the package of your project in sys. path.
It sets the DJANGO_SETTINGS_MODULE environment variable to the location of the setting. py file of your project.
If you install Django using the setup. py tool, the django-admin.py script should be in your system directory. If not, go to the site-package/django/bin directory of Your python installation directory.

Generally, If you often work in an independent Django project, it is easier to use manage. py. But if you have many Django projects, you can use the django-admin.py, and you need to change DJANGO_SETTINGS_MODULE frequently or use the-settings option to set different setting. py.

The django-admin.py will be used in this article for demonstration, but all examples can also be implemented using manage. py.

[Usage]

The syntax of the djang-admin.py is:

django-admin.py <subcommand> [options]
manage.py <subcommand> [options]

Among them, subcommand is a sub-command; options is optional, and there can be 0 to multiple options.

You can use the help command to obtain help. There are two methods:

1 run django-admin.py help to display usage information and give a list of all available subcommands

2 running the django-admin.py help <subcommand> displays the description of a specific subcommand and all available options

Running django-admin.py-version displays the version number of django.

If you add-verbosity when using a django-admin.py, a large amount of notification and debugging information is displayed.

[Runfcgi]-subcommand

Start a process that supports the FastCGI protocol to receive requests from WebServer. You can use flup as the Python FastCGI module.

The runfcgi options are as follows:

  • Protocol: used to set the cgi protocol used, including fcgi, scgi, and ajp. The default value is fcgi.
  • Host: used to set the host Name of the listener
  • Port: used to set the listening port
  • Socket: the UNIX socket used to set the listener
  • Method: it can be set to prefork or threaded. The default value is prefork.
  • Maxrequests: Maximum number of requests that a sub-process can process. If the number of sub-processes exceeds this limit, the sub-processes are killed and a new process is created. If it is set to 0, there are no restrictions on sub-processes.
  • Maxspare: Maximum number of idle processes/threads
  • Minspare: Minimum number of idle processes/threads
  • Maxchildren: Hard limit on the number of processes/threads
  • Daemonize: boolean value, indicating whether to put it in the background for running.
  • Pidfile: Set a file to write the generated PID information.
  • Workdir: used to set the working directory
  • Debug: boolean value, used to set whether to enable flup Information Tracking
  • Outlog: used to set the file to which standard output is written.
  • Errlog: used to set the file to which standard error output is written.
  • Umask: used to set the umask used during the process. The default value is 022.

For example:

django-admin.py runfcgi socket=/tmp/fcgi.sock method=prefork daemonize=true \  pidfile=/var/run/django-fcgi.pid

This command is used to start fastCGI in the background and write the pid into the file.

[Runserver]-subcommand

It is used to start a lightweight Web server on the local machine. By default, this server listens to port 8000 on 127.0.0.1. You can also input parameters to change the default configuration.

If you are not a privileged user, the port number you set cannot be lower than 1024, because the port number smaller than 1024 has been reserved by the system.

Do not use this lightweight Server as the Server in your production environment, because it can only be used in the development test phase. It neither has the security audit function, nor is it single-threaded.

In addition, every time a request is sent, the Web Server loads the Python code again. Therefore, if your code is changed, you do not need to restart the Web Server to take effect.

You can start multiple fastcgi servers in a project. You only need to set different ports.

If the IP address you set is 127.0.0.1 by default, you can only log on to and browse from the local browser, but cannot access from other machines. To allow other machines to browse the local machine, set the IP address to the IP address of the target machine, which is 0.0.0.0 (IPv4 address) or: (IPv6 address ).

When specifying an IP address, you can also use the host name or domain name instead.

Shell-subcommand

Enables a Python interpreter.

Django uses IPython or bpython by default. However, if you have not installed them or want to use the simplified version, you can add the-plain option, that is:

django-admin.py shell --plain

[Startapp]-subcommand

Create a folder structure of the Django app in the current path or specified directory.

By default, the folder contains the module. py file and other necessary files.

Run the following command to create an app in a specific directory:

django-admin.py startapp myapp /Users/jezdez/Code/myapp

[Startproject]-subcommand

In Django, Projects can have installed apps. Apps can be shared among hosted projects.

Create a Django project folder structure in the current directory or specified location.

By default, the new folder contains manage. py and a series of necessary files.

The target location parameter is an optional parameter. You can set the path created by the project.

For example, the following command creates a project at a specified position:

django-admin.py startproject myproject /Users/jezdez/Code/myproject_repo

Like the startapp command, the -- template command allows you to specify a folder, file path, or a link to a custom project template. For project template support, you can view the startapp documentation.

In the following example, when creating a myproject project, the template is searched in the specified path.

django-admin.py startproject --template=/users/jezdez/code/my_project_template myproject

When Django copies the project template files, it also renders certain files through the template engine: the files whose extensions match the -- extension option (py by default) and the files whose names are passed with the -- name option. the template context used is:

Any option passed to the startproject command
Project_name -- the project name as passed to the command
Project_directory -- the full path of the newly created project
Secret_key -- a random key for the SECRET_KEY setting
Please also see the rendering warning as mentioned for startapp.

Syncdb

django-admin.py syncdb

This command will create a data table for the installed (INSTALLED_APPS) apps, if the data table has not been created.

[Extended manage command]
We have used Django's django-admin.py and manage. py. A django-admin.py is a command line tool that can execute some administrative tasks, such as creating a Django project. Manage. py is automatically added to the project directory when each Django project is created, only for manage. A simple package of py, its function is to put the Django project in sys. in the path directory, set the DJANGO_SETTINGS_MODULE environment variable to the setting of the current project. py file.


The 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 parses the Command name based on the Command line parameters and calls the corresponding Command to execute the Command according to the Command name. Command is located under the commands module of each management module.

The management module refers to the management module under the app module. Django uses the django. core. management. find_management_module function to find the "management Module ":

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 be found for any reason.
  """
  parts = app_name.split('.')
  parts.append('management')
  parts.reverse()
  part = parts.pop()
  path = None

Then find the command class through the django. core. management. find_commands function. The find_commands function searches for the. py file in the management module and matches the name of The. py file with the command name:

def find_commands(management_dir):
  """
  Given a path to a management directory, returns a list of all the command
  names that are available.

  Returns an empty list if no commands are 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, use the django. core. management. load_command_class function to load the Command class in the. py file:

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) are allowed to propagate.
  """
  module = import_module('%s.management.commands.%s' % (app_name, name))
  return module.Command()

When executing a Command, the handle method of the corresponding Command class is executed. All Command classes should be directly or indirectly sub-classes of django. core. management. base. BaseCommand.

The principle is clear, and it is easy to extend the manage command. Create an app and add it to INSTALLED_APPS of settings. Create the management. commands module under the app and create the 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!


Articles you may be interested in:
  • How to perform unit tests on projects in the Python Django framework
  • Use the Python Django framework and jQuery to implement the AJAX shopping cart page
  • Serialization, request, and return in the Django REST framework of Python
  • Details about the templates settings in the Python Django framework
  • How to obtain the IP address of a user using django in Python
  • Analyze the running mode and processing process of the Python Django framework
  • How to configure mysql database in Django1.7 + python 2.78 + pycharm
  • Share the simple Performance Test Results of common python web frameworks (including django, flask, bottle, tornado)
  • Python django integrated cas Verification System
  • How to Make Sublime 3 a powerful tool for Python/Django IDE development


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.