【问题标题】:How to run flask shell in PyCharm?如何在 PyCharm 中运行烧瓶外壳?
【发布时间】:2019-09-21 16:38:59
【问题描述】:

我在 PyCharm 中创建了新的烧瓶项目,但我看不到如何在集成的 PyCharm python 控制台窗口中运行烧瓶外壳。

启动控制台时未定义名称应用程序:

我仍然可以在集成的 PyCharm 终端中运行命令“flask shell”,但它会在没有代码完成、提示、语法检查等的情况下启动。

Flask 应用在终端中定义:

有没有办法在集成的 PyCharm python 控制台中启动烧瓶外壳?

【问题讨论】:

    标签: python flask pycharm command-line-interface


    【解决方案1】:

    您可以结合使用creating a request context for the Shellflask shell 可以)和custom starting script for the PyCharm console

    # Step 1: acquire a reference to your Flask App instance
    import app
    app_instance = app.create_app()
    # I return app instance from a factory method here, but might be be `app.app` for basic Flask projects
    
    # Step 2: push test request context so that you can do stuff that needs App, like SQLAlchemy
    ctx = app_instance.test_request_context()
    ctx.push()
    

    现在您应该享受 flask shell 的好处以及 IPython Shell 提供的代码完成和其他好处,所有这些都来自默认的 PyCharm Python Shell。

    【讨论】:

      【解决方案2】:

      在我的情况下(在我的server.py 我有app=Flask(__name__))我使用了

      from server import app
      ctx = app.app_context()
      ctx.push()
      

      然后将此添加到File | Settings | Build, Execution, Deployment | Console | Python Console 启动脚本

      【讨论】:

        【解决方案3】:

        这也有效:

        from app import app
        ctx = app.test_request_context()
        ctx.push()
        

        更多关于Flask docs page

        【讨论】:

        • 虽然这可能是解决问题的宝贵提示,但一个好的答案也可以证明解决方案。请EDIT 提供示例代码来说明您的意思。或者,考虑将其写为评论
        【解决方案4】:

        Running a Shell

        要运行交互式 Python shell,您可以使用 shell 命令:

        flask shell
        

        这将启动一个交互式 Python shell,设置正确的 应用程序上下文并在 shell 中设置局部变量。这 通过调用 Flask.make_shell_context() 方法来完成 应用。默认情况下,您可以访问您的应用和 g。

        它只是一个普通的交互式 Python shell,已经为您设置了一些局部变量,而不是具有代码完成、提示、语法检查等功能的 IDE 编辑器。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多