You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下Apache+mod_wsgi部署Django HelloWorld遇URLconf无路由错误

Django + mod_wsgi部署出现URLconf无路由规则的解决思路

你在Windows系统中用Apache+mod_wsgi部署Django HelloWorld应用时,遇到错误:包含的URLconf 'mod_wsgi...' 似乎没有任何路由规则。纯WSGI测试代码可正常运行,但Django配置的WSGI脚本无法正常工作,怀疑是urlpatterns的配置传递存在问题。

你使用的Django配置代码

import os
import sys
import site
from django.core.wsgi import get_wsgi_application
from django.conf import settings
from django.urls import path
from django.http import HttpResponse

site.addsitedir("C:/Program files/python312/Lib/site-packages")

sys.path.append('C:/Users/felhasznalo/Desktop/django')
sys.path.append('C:/Users/felhasznalo/Desktop/django/todo')

settings.ROOT_URLCONF=__name__
settings.ALLOWED_HOSTS = ['localhost', '127.0.0.1']
settings.SECRET_KEY = '1234'

def hello(request):
    return HttpResponse("Hello World!")

urlpatterns = [
    path("", hello)
]

application = get_wsgi_application()

可正常运行的纯WSGI测试代码

def application(environ, start_response):
    status = '200 OK'
    output = b'Hello World!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

问题根源

你直接在WSGI脚本中设置settings.ROOT_URLCONF=__name__,但mod_wsgi运行脚本时,当前模块的命名会被替换为_mod_wsgi_...,导致Django无法正确识别你定义的urlpatterns变量。另外,直接在WSGI脚本中编写路由和视图不属于Django标准部署方式,容易引发加载异常。

解决步骤

1. 改用标准Django项目结构

先确保项目结构符合规范:

django/
    todo/           # 项目根目录(含manage.py)
        todo/       # 项目配置子目录
            settings.py
            urls.py
        manage.py

将hello视图放到项目根目录的urls.py中:

# todo/urls.py
from django.urls import path
from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello World!")

urlpatterns = [
    path("", hello),
]

2. 修正WSGI脚本

不要在WSGI脚本中直接定义路由和配置,改为让Django加载项目的settings模块:

import os
import sys
import site

# 添加Python包路径
site.addsitedir("C:/Program files/python312/Lib/site-packages")

# 添加项目路径到sys.path
sys.path.append('C:/Users/felhasznalo/Desktop/django')
sys.path.append('C:/Users/felhasznalo/Desktop/django/todo')

# 设置Django的settings模块
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo.settings')

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

3. 确保项目settings配置正确

在todo/settings.py中至少配置以下内容:

SECRET_KEY = '1234'
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
ROOT_URLCONF = 'todo.urls'  # 确保指向你的urls.py文件

4. 验证mod_wsgi与Python版本匹配

确认mod_wsgi使用的Python版本和你安装Django的版本一致(当前为Python3.12),版本不匹配会导致模块找不到或加载异常。

临时应急方案(不推荐生产环境)

如果一定要在WSGI脚本中直接编写路由,可将路由定义到单独模块中:比如在脚本同目录下新建urls.py,然后设置settings.ROOT_URLCONF='urls',而非__name__。

内容的提问来源于stack exchange,提问作者inf3rno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:23:10