我正在使用 mod wsgi 在 Apache 2.2 上运行 Python 脚本。
是否可以在 wsgi 中使用守护进程模式在 python 脚本中运行 pdb.set_trace()?
编辑 我想使用守护进程模式而不是嵌入式模式的原因是能够重新加载代码而不必每次都重新启动 Apache 服务器(嵌入式模式需要)。我希望能够使用代码重新加载而无需每次都重新启动 Apache,并且仍然能够使用 pdb...
最佳答案
我同样需要能够使用功能强大的 pdb
,在任何我想调试 Python 服务器某些部分的地方放置一个 pdb.set_trace()
代码。
是的,Apache 在您无法控制的地方生成 WSGI 应用程序 [1]。但我发现一个很好的折衷方案是
维护您的 Apache
WSGIScriptAlias
还可以选择在终端中启动 Python 服务器(在本例中在本地测试,不再通过 Apache)
所以如果一个人像这样使用 WSGIScriptAlias
...
指向名为 webserver.py
<VirtualHost *:443>
ServerName myawesomeserver
DocumentRoot /opt/local/apache2/htdocs
<Directory /opt/local/apache2/htdocs>
[...]
</Directory>
WSGIScriptAlias /myapp /opt/local/apache2/my_wsgi_scripts/webserver.py/
<Directory /opt/local/apache2/my_wsgi_scripts/>
[...]
</Directory>
[...]
SSLEngine on
[...]
</VirtualHost>
因此您的 webserver.py
可以有一个简单的开关,以在 Apache 使用和启动手动调试之间切换。
在你的配置文件中保留一个标志,例如在一些 settings.py
中:
WEBPY_WSGI_IS_ON = True
和webserver.py
:
import web
import settings
urls = (
'/', 'excellentWebClass',
'/store', 'evenClassier',)
if settings.WEBPY_WSGI_IS_ON is True:
# MODE #1: Non-interactive web.py ; using WSGI
# So whenever true, the Web.py application here will talk wsgi.
application = web.application(urls, globals()).wsgifunc()
class excellentWebClass:
def GET(self, name):
# Drop a pdb wherever you want only if running manually from terminal.
pdb.set_trace()
try:
f = open (name)
return f.read()
except IOError:
print 'Error: No such file %s' % name
if __name__ == "__main__":
# MODE #2: Interactive web.py , for debugging.
# Here you call it directly.
app = web.application(urls, globals())
app.run()
所以当你想交互式地测试你的网络服务器时,你只需从终端运行它,
$ python webserver.py 8080
starting web...
http://0.0.0.0:8080/
[1] 脚注:有一些非常复杂的方法可以让 Apache 子进程处于您的控制之下,但如果您只想调试 Python 服务器代码,我认为上述方法要简单得多。如果真的有简单的方法,那么我也很想了解这些方法。
关于python - 使用 WSGI 在守护进程模式下运行 pdb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7222770/