Skip to main content
 首页 » 编程设计

python之Apache + mod_wsgi之来自同一浏览器的并行请求

2025年05月04日44lidabo

你能帮我解决这个问题吗?

我正在使用 mod_wsgi 运行 Apache 2.2.22

我正确配置了 WSGI 以在多线程上工作并且我正在使用 Python 我需要处理来自同一浏览器的并行请求,但 wsgi 唯一可以处理的并行请求是来自不同浏览器的请求(或 1 个浏览器选项卡 + 1 个隐身选项卡)。

我尝试了嵌入式和守护进程。

Apache 配置:

WSGIDaemonProcess appname processes=5 threads=25 display-name=%{GROUP} 
WSGIProcessGroup appname  
 
WSGIScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ 
 
<Directory "/usr/lib/cgi-bin"> 
    AllowOverride None 
    AddHandler wsgi-script .py 
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch 
    #Require all granted 
</Directory> 

我把 wsgi.py 放在/usr/lib/cgi-bin 目录下,755 mod

wsgi.py的内容:

import os, sys 
import time 
from datetime import datetime 
 
def application(environ, start_response): 
 
    sys.stderr.write("before wait time = %s\n" % str(datetime.now())) 
    sys.stderr.write("client= %s\n" % environ['REMOTE_ADDR']) 
    sys.stderr.write("waiting\n") 
    print >> sys.stderr, 'mod_wsgi.process_group = %s' % repr(environ['mod_wsgi.process_group']) 
    time.sleep(10) 
    sys.stderr.write("wait finished time = %s\n" % str(datetime.now())) 
    status = '200 OK' 
    output = 'Hello World!' 
 
    response_headers = [('Content-type', 'text/plain'), 
                    ('Content-Length', str(len(output)))] 
    start_response(status, response_headers) 
 
    return [output] 

请求时http://my.ip/cgi-bin/wsgi.py我一切都很好,但是当我在单个浏览器的两个选项卡中并行运行它时,第二个选项卡正在等待第一个选项卡完成... 日志:

[Tue Sep 02 18:25:06 2014] [error] before wait time = 2014-09-02 18:25:06.365133 
[Tue Sep 02 18:25:06 2014] [error] client= 192.168.113.35 
[Tue Sep 02 18:25:06 2014] [error] waiting 
[Tue Sep 02 18:25:06 2014] [error] mod_wsgi.process_group = 'appname' 
[Tue Sep 02 18:25:16 2014] [error] wait finished time = 2014-09-02 18:25:16.371944 
[Tue Sep 02 18:25:16 2014] [error] before wait time = 2014-09-02 18:25:16.390348 
[Tue Sep 02 18:25:16 2014] [error] client= 192.168.113.35 
[Tue Sep 02 18:25:16 2014] [error] waiting 
[Tue Sep 02 18:25:16 2014] [error] mod_wsgi.process_group = 'appname' 
[Tue Sep 02 18:25:26 2014] [error] wait finished time = 2014-09-02 18:25:26.400464 

请您参考如下方法:

如果这与浏览器回收与服务器的打开连接以发送后续请求有关,我不会感到惊讶。如果它为从隐身选项卡发送的请求打开一个新连接,那将允许服务器上的一个单独线程来处理它;这正常工作表明您的 WSGI 设置基本上没问题。