我认为通过其他文件导入有点尴尬,所有视图都应该直接导入,就像现在这样。
但是,您可以创建views.py文件并从中导入所有相关的view方法,dir结构将保持不变,只需在views/dir下添加views.py文件。文件中的代码本身应该类似于:
from .index import index
from .other_view import other_view_method
...
然后url.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()