Django子目录查看并从__init__.py导入所有文件

时间:2010-10-28 16:26:41

标签: python django

技术上不是django问题,更像是一个python问题。

在urls.py中我有以下内容:

urlpatterns = patterns('locate.views',
    url(r'^',  'index.index'),
)

这样的目录结构:

locate/
  views/
    __init__.py
    index.py      #  where there is "def index(request) : ...."

我想做的是避免说“index.index”,而是让事情变得平淡。因此产生:

urlpatterns = patterns('locate.views',
    url(r'^',  'index'),
)

如果我使__ init __.py包含:

,这当然是很有可能的
from .index import index
...

但是在第99次这样做之后,将它自动化会很不错。我和__ import __之类的东西已经接近了,但是想知道其他人是否有一个工作代码片段和/或更好的方法来处理django中的这种模式。

更新使用的Amit代码版本:

这是在views/__init__.py文件中(很快将被提取到库中):

from glob import glob1
from types import FunctionType
import os

def import_views(dirname, views_prefix='') :
    for filename in glob1(dirname, '*.py'):
        if filename == '__init__.py':    # I assume you don't want that
            continue

        module_name = os.path.basename(filename).split('.py')[0]

        # You might need to change this, depending on where you run the file:
        imported_module = __import__("%s.%s" % (__package__, module_name), fromlist=[module_name,])

        idict = imported_module.__dict__

        for method_name in idict.get('__all__', idict.keys()):
            method = idict[method_name]
            if not isinstance(method, FunctionType):
                continue
            if views_prefix and not method_name.startswith(views_prefix):
                continue
            globals()[method_name] = method

import_views(os.path.dirname(__file__))

1 个答案:

答案 0 :(得分:1)

我认为通过其他文件导入有点尴尬,所有视图都应该直接导入 - 就像你现在的做法一样。 但是,您可以创建一个views.py文件并从那里导入所有相关的视图方法,dir结构将保持不变,只有您将在views / dir下添加一个views.py文件。文件中的代码应该是这样的:

from .index import index
from .other_view import other_view_method
...

然后是urls.py文件中的代码:

 urlpatterns = patterns('locate.views',
    url(r'^',  'index.index'), )

将变为:

urlpatterns = patterns('locate.views.views',
    url(r'^',  'index'),
)

但是,如果您仍想运行所有* .py文件并从中获取所有视图方法,则可以创建首先运行并加载所有视图的加载程序文件,代码应如下所示:

from glob import glob1
from types import FunctionType

VIEW_METHOD_PREFIX = ''    # Whatever you like here, I suggest you use something
VIEWS_DIR          = 'views'    # Where you views are

def import_views():

    for filename in glob1(VIEWS_DIR, '*.py'):
        if filename == '__init__.py':    # I assume you don't want that
            continue

        module_name = os.path.basename(filename).split('.py')[0]

        # You might need to change this, depending on where you run the file:
        imported_module = __import__(
            module_name, fromlist=[module_name,])  

        for method_name, method in imported_module.__dict__.iteritems():
            if not isinstance(method, FunctionType):
                continue
            if not method_name.startswith(VIEW_METHOD_PREFIX):
                continue
            globals()[method_name] = method

然后在urls.py中添加:

import_views()