Skip to main content
 首页 » 编程设计

python之Django子目录查看并导入__init__.py中的所有文件

2025年05月04日38exmyth

技术上不是 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__)) 

请您参考如下方法:

我认为通过其他文件导入有些尴尬,所有 View 都应直接导入 - 就像您现在所做的那样。 但是,您可以创建一个 views.py 文件并从那里导入所有相关的 View 方法,目录结构将保持不变,只是您将在 views/目录下添加一个 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 文件并从中获取所有 View 方法,您可以创建一个首先运行并加载所有 View 的加载程序文件,代码应如下所示:

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()