Patch Django Management to allow pyc, so and pyd modules

So you have an "embeddded" Django instance where you want to strip the thing down to the minimum required files.  You run compileall on your site-packages, then strip/delete all of the .py files... and your Django becomes pretty useless, because it no longer recognizes any of your management plugins (not even the built-in ones).

This little patch makes the management system accept any of py, pyc, so or pyd files as management plugins.

*** __init__.py-orig	2012-05-22 12:02:19.000000000 -0400
--- __init__.py 2012-07-05 18:04:23.000000000 -0400
***************
*** 15,21 ****
# A cache of loaded commands, so that call_command
# doesn't have to reload every time it's called.
_commands = None
!
def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
--- 15,21 ----
# A cache of loaded commands, so that call_command
# doesn't have to reload every time it's called.
_commands = None
! module_suffixes = ['.py','.pyc','.so','.pyd']
def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
***************
*** 25,32 ****
"""
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 []

--- 25,36 ----
"""
command_dir = os.path.join(management_dir, 'commands')
try:
! return [
! file for (file,ext) in [
! os.path.splitext( fullname )
! for fullname in os.listdir(command_dir)
! ] if ext in module_suffixes
! ]
except OSError:
return []

Patching django/core/management/__init__.py (Django 1.4).

Comments

  1. Malcolm Tredinnick

    Malcolm Tredinnick on 07/05/2012 7:30 p.m. #

    One thing that jumps out: You've inadvertently changed the behaviour. The current code allows for files to be ignored from processing by this path if they start with an underscore. This allows for creating utility files that aren't processed as commands, or other file separation. You're now processing every file, regardless of initial character.

    You're also now returning duplicate names from find_commands(), since .py and .pyc files for the same basename will be returned. Fortunately, those are then used as keys into a dictionary later on, so are collapsed, but you could replace the outer list there with a set to keep things unique along the way.

  2. Mike Fletcher

    Mike Fletcher on 07/05/2012 9:09 p.m. #

    Good catch on the _ character. I reworked it before posting and managed to drop that if clause. The duplication was known, the code passes the results into dict() after each call.

Comments are closed.

Pingbacks

Pingbacks are closed.