Django拆分views.py后如何优雅导入view文件夹下所有视图类
Django 视图拆分后的导入优化方案
方案1:init.py 自动动态导入
无需每次新增视图文件时手动修改__init__.py,在api/view/__init__.py中写入以下代码即可自动导入目录下所有视图文件的公开对象:
import os import importlib # 遍历当前目录所有Python文件 for file_name in os.listdir(os.path.dirname(__file__)): if file_name.endswith(".py") and file_name != "__init__.py": module_name = file_name[:-3] # 导入对应模块 module = importlib.import_module(f".{module_name}", package=__name__) # 同步模块公开对象到当前命名空间 if hasattr(module, "__all__"): globals().update({name: getattr(module, name) for name in module.__all__}) else: # 未定义__all__时导入所有非下划线开头的对象 globals().update({k: v for k, v in module.__dict__.items() if not k.startswith("_")})
完成后还是可以直接在core/urls.py中用from api.view import *导入所有视图类,不需要额外修改。
方案2:显式按需导入(生产环境推荐)
符合Python「显式优于隐式」的开发规范,无命名冲突风险,IDE补全、跳转、代码检查都完全正常:
- 每个拆分后的视图文件末尾定义
__all__声明公开对象,以Customer.py为例:
class CustomerList(APIView): # 业务逻辑 pass class CustomerDetail(APIView): # 业务逻辑 pass __all__ = ["CustomerList", "CustomerDetail"]
- 在
core/urls.py中按需导入需要的视图:
from api.view.Customer import CustomerList, CustomerDetail from api.view.Order import OrderList, OrderDetail # 其他视图导入
方案3:路由字符串省略导入
Django原生支持路由中直接写视图的全路径字符串,完全不需要写导入语句:
from django.urls import path urlpatterns = [ path("customers/", "api.view.Customer.CustomerList.as_view()"), path("customers/<int:pk>/", "api.view.Customer.CustomerDetail.as_view()"), # 其他路由 ]
该方案适合小型项目使用,缺点是无法支持IDE直接跳转视图,路径写错仅能在运行时发现。
内容的提问来源于stack exchange,提问作者Jakub Zilinek
相关产品推荐
相关产品推荐

