Skip to main content
 首页 » 编程设计

python之Django Web 服务器在启动守护进程后挂起

2025年05月04日33bjzhanghao

我使用 Django 开发服务器启动一个守护进程,它执行来自 views.py 的所有命令,但网页挂起。守护进程正常启动,但网页挂起需要修复。我在 Red Hat Enterprise Linux 6.3 下工作。

为了确保这不是我或我的守护程序错误,我执行了以下测试:

1) 我创建了新的 Django 项目“djtesting”,其中使用以下代码创建了一个 views.py 文件(它启动了 httpd 守护进程):

from django.http import HttpResponse 
import subprocess 
 
def hello(request): 
    res = subprocess.call("/usr/sbin/httpd") 
    return HttpResponse("Testing.") 

2) 将此函数添加到 urls.py:

from django.conf.urls.defaults import patterns, include, url 
from djtesting.views import hello 
 
urlpatterns = patterns('', 
    ('^hello/$', hello), 
    ) 

3) 然后我用“python manage.py runserver 192.168.1.226:8000”启动网络服务器,并在浏览器中用“http://192.168.1.226:8000/hello/”打开网页。它显示“测试”消息然后挂起(开始加载并挂起),尽管守护进程正常启动。但是如果用“/etc/init.d/httpd stop”停止守护进程,网页就会停止加载。看起来服务器正在等待守护进程完成工作,但我只需要启动它而不用等到它结束。

我尝试了另一种运行守护进程的方法(当然每次尝试一行)但结果同样糟糕:

thread.start_new_thread(os.system, ('/usr/sbin/httpd',)) 
process = subprocess.Popen("/usr/sbin/httpd", stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) 
res = subprocess.call(["/usr/sbin/httpd", "&"]) 
res = subprocess.Popen("/usr/sbin/httpd") 
res = os.system("/usr/sbin/httpd &") 
res = os.spawnl(os.P_NOWAITO, '/usr/sbin/httpd', '&') 

我发现了类似的问题,但我无法使用 start-stop-daemon,因为我在 RHEL6.3 下工作: Why hangs the web page after it started a daemon on the underlying server?

请您参考如下方法:

subprocess.call 等待返回值,所以我很惊讶您能够获得返回值。尝试改用 subprocess.Popen,因为它会生成进程,然后将控制权返回给您,而不是等待结束。