I am new to flask and pycharm. Basically I wrote a rest webservice and initially PyCharm was running it as a python script. Everything was working fine. But then after I realuched pycharm it detects app.py as a flask application.
Part that launches the app locally in app.py looks like so:
if __name__ == '__main__':
from db import db
db.init_app(app)
if app.config['DEBUG']:
@app.before_first_request
def create_tables():
db.create_all()
app.run(port=5000)
The problem is that it seems like this part is not executed when I try to run app.py. I also have run.py
which I use to run the app through uwsgi on a web server. Here is the console output from pycharm when I launch app.py
:
FLASK_APP = app.py
FLASK_ENV = development
FLASK_DEBUG = 0
In folder /home/username/PycharmProjects/psychotest
/home/aydar/PycharmProjects/psychotest/venv/bin/python -m flask run
* Serving Flask app "app.py"
* Environment: development
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
I've added print statements to the if __name__=='main'
block, which are never printed. It also seems that pycharm launches flask with /home/username/PycharmProjects/psychotest/venv/bin/python -m flask run
. Also as you can see DEBUG
is false, even though I explicitly set debug to true in the body of app.py like so:
app = Flask(__name__)
app.config['DEBUG'] = True
Everything is working through the terminal with just python app.py
. How do I change this behaviour of Pycharm? It annoys me because I get sqlalchemy errors every time I try to get something from a database through flask. Error example:
'The sqlalchemy extension was not registered to the current ' \
AssertionError: The sqlalchemy extension was not registered to the current application. Please make sure to call init_app() first.
基于此答案,由于PyCharm将其检测为if __name__ == '__main__':
应用程序,因此永远不会命中if __name__ == '__main__':
块,因此您可能希望将db.init_app(app)
移至该块之外(导入也是如此) )
You can edit your configuration runned by Pycharm.
You can find it on the top right. There is a select box which your current configuration is selected.
Then don't use -m flask run
as parameter but just app.py
.
Actually I was able to solve the problem. While reformating app.py
, namely moving db.init_app()
outside of __name__=='__main__'
, works - it was not ideal solution for me. Because I've already set up workflow, and I did not want to change execution logic of app.py just for PyCharm.
The solution was to disable flask integration in settings -> languages and frameworks. Everything works properly now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.