【问题标题】:How to remote debug Flask request behind uWSGI in PyCharm如何在 PyCharm 中远程调试 uWSGI 后面的 Flask 请求
【发布时间】:2017-11-30 19:32:28
【问题描述】:

我已经在线阅读了一些关于如何使用 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 在超时后显示网关错误。

【问题讨论】:

    标签: python uwsgi remote-debugging


    【解决方案1】:

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

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

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

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

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

    使其成为主控,禁用线程,并将其限制为仅 1 个进程 - http://uwsgi-docs.readthedocs.io/en/latest/Options.html

    然后,在启动 python 文件中,不是将调试器设置为在整个烧瓶应用程序启动时连接,而是在一个用方便的烧瓶函数装饰的函数中设置它连接,before_first_requesthttp://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 限制为没有线程,并且只有 1 个进程来限制与它们和调试器发生任何混淆的机会,并将 pydevd 设置为仅在第一个请求之前连接。现在,调试器(对我而言)成功连接一次,在此函数的第一个请求中,仅打印一次“已连接”,然后断点在您的任何请求端点函数中连接,没有问题。

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 2013-04-12
      • 2014-03-01
      • 2014-02-02
      • 2013-05-30
      • 2023-03-09
      • 2021-05-20
      • 2015-08-17
      • 2019-02-05
      相关资源
      最近更新 更多