DEV Community

KurzGedanke
KurzGedanke

Posted on • Originally published at kurzgedanke.de on

Problems with Flask and PyCharm

I started a new Flask project and coded it in VisualCode and a Terminal. Therefore, I set up my virtual environment, installed Flask and started to code after the Flask Quistart.

The code looks like this:

from flask import Flask
app = Flask( __name__ )

@app.route('/')
def hello_world():
    return 'Hello, World!'
Enter fullscreen mode Exit fullscreen mode

Then I ran the app with:

$ export FLASK_APP=hello.py
$ flask run
 * Running on http://127.0.0.1:5000/
Enter fullscreen mode Exit fullscreen mode

Because of the great support for Web Apps I decided to switch to PyCharm. I imported the project into PyCharm, set the Interpreter to the virtualenv, but when it hit run nothing happend….

If you have the same problem: Feel welcome, I’ve got the solution!

Create a New Project, choose the Flask Template and select your existing flask project folder. Say yesto the pop-up which asks you to create a project from existing source.

PyCharm Project Creation

Your project should open now and you can change your intepreter in the settings to your virtualenv or whatever you desire.

If you try to run the app now you should see something like this:

PyCharm Console with nothing in it

I tried everything but the solution is damn simple… add this at the end of your code:

if __name__ == ' __main__':
    app.run()
Enter fullscreen mode Exit fullscreen mode

and your console should output * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit).

If you want to know more about the if __name__ == ' __main__': line I can recommend this Video from Corey Schafer.

Thank you for reading!

Top comments (1)

Collapse
 
markoshiva profile image
Marko Shiva

yes you need to call a process. So if you are starting by default from command line with python3 app.py or flask app.py its not needed.
But once you want to treat it as a independent package you need to have a main block.

That block tell you which source code to run if you start that file as an app.
In other words if you named your starting point file as application.py
and was starting it with flask application.py

Then you should include main block in that file.

I by default have main block in every flask app.