Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run flask shell in PyCharm?

I created new flask project in PyCharm but I can't see how to run flask shell in integrated PyCharm python console window.

Name app is not defined when start console: Name app is not defined when start console

I still can run command "flask shell" in integrated PyCharm terminal but it will start without code completion, hints, syntax checks, etc.

Flask app is defined in terminal:

Flask app is defined in terminal Is there any way to start flask shell in integrated PyCharm python console?

like image 891
QuinceN Avatar asked May 03 '19 06:05

QuinceN


3 Answers

You can use a combination of creating a request context for the Shell (which flask shell does) and a custom starting script for the PyCharm console.

Where to enter starting script in PyCharm preferences

# 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()

Now you should have the benefits of flask shell alongside the code completion and other benefits that IPython Shell provides, all from the default PyCharm Python Shell.

like image 191
Rach Sharp Avatar answered Sep 22 '22 13:09

Rach Sharp


In my case (in my server.py I had app=Flask(__name__)) I used

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

Then added this to File | Settings | Build, Execution, Deployment | Console | Python Console starting script

like image 25
AliReza Avatar answered Sep 20 '22 13:09

AliReza


This also works:

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

more on the Flask docs page

like image 30
christok Avatar answered Sep 20 '22 13:09

christok