Skip to main content
 首页 » 编程设计

python之如何在 PyCharm 中远程调试 uWSGI 背后的 Flask 请求

2025年01月19日12freeliver54

我已经在线阅读了一些关于如何使用 PyCharm 进行远程调试的文档 - https://www.jetbrains.com/help/pycharm/remote-debugging.html

但是对于我尝试做的事情,我的设置存在一个关键问题——Nginx 连接到 uWSGI,然后连接到我的 Flask 应用程序。我不确定,但设置类似的东西,

import sys 
sys.path.append('pycharm-debug.egg') 
 
import pydevd 
 
pydevd.settrace('localhost', port=11211, 
                stdoutToServer=True, stderrToServer=True, 
                suspend=False) 
print 'connected' 
 
from wsgi_configuration_module import app 

我的 wsgi_configuration_module.py 文件是生产中使用的 uWSGI 文件,即没有调试。

将调试器连接到 uWSGI 的主/主进程,它只运行一次,在 uWSGI 启动/重新加载时,但是如果你试图在你的请求的代码块中设置断点,我发现它要么跳过超过它,或者完全挂起,从来没有碰到它,并且 uWSGI 在超时后显示网关错误。

请您参考如下方法:

这里的问题,据我所知正是最后一点,调试器连接到 uWSGI/应用程序进程,不是任何单独的请求进程。

为了解决这个问题,从我的情况来看,它需要改变两件事,其中一件是我的应用程序的 uWSGI 配置。我们的生产文件看起来像

[uwsgi] 
... 
master = true 
enable-threads = true 
processes = 5 

但是在这里,为了让调试器(和我们)轻松连接到请求进程并保持连接,我们将其更改为

[uwsgi] 
... 
master = true 
enable-threads = false 
processes = 1 

使它成为 master,禁用线程,并将它限制为只有 1 个进程 - http://uwsgi-docs.readthedocs.io/en/latest/Options.html

然后,在启动 python 文件中,不是将调试器设置为在整个 flask 应用程序启动时连接,而是将其设置为在装饰有方便的 flask 函数 before_first_request http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_first_request 的函数中连接,所以启动脚本变成类似的东西,

import sys 
import wsgi_configuration_module 
 
sys.path.append('pycharm-debug.egg') 
import pydevd 
 
app = wsgi_configuration_module.app 
 
 
@app.before_first_request 
def before_first_request(): 
    pydevd.settrace('localhost', port=11211, 
                    stdoutToServer=True, stderrToServer=True, 
                    suspend=False) 
    print 'connected' 
 
# 

所以现在,你已经将 uWSGI 限制为没有线程,只有一个进程来限制与它们和调试器混淆的机会,并将 pydevd 设置为仅在第一个请求之前连接.现在,调试器(对我而言)成功连接一次,在此函数中的第一个请求中,仅打印一次“已连接”,然后断点连接到您的任何请求端点函数中,没有问题。