Cannot connect PostgreSQL database with Flask app
Question:
I recently started learning the Flask framework, but now I am stuck, because – according to internet tutorials and documentation – my project is not working as it should be.
I have a larger project, but after seeing that problem I made a smaller one just to see why it is not working – but I still have no clue.
That is my ‘smaller’ code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:test123@localhost/ranking'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r' % self.username
@app.route('/')
def index():
return "helo world"
if __name__ == '__main__':
app.run()
and after running a python interpreter and typing there:
from app import db
I have no UserWarning (as in internet tutorials), but later – after typing:
db.create_all()
I received:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:UsersMePycharmProjectsFlaskvenvlibsite-packagesflask_sqlalchemyextension.py", line 868, in create_all
self._call_for_binds(bind_key, "create_all")
File "C:UsersMePycharmProjectsFlaskvenvlibsite-packagesflask_sqlalchemyextension.py", line 839, in _call_for_binds
engine = self.engines[key]
File "C:UsersMePycharmProjectsFlaskvenvlibsite-packagesflask_sqlalchemyextension.py", line 628, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
File "C:UsersMePycharmProjectsFlaskvenvlibsite-packageswerkzeuglocal.py", line 513, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
What did I wrong? What should I do to make it work? Please help me.
Answers:
In your terminal, run:
flask shell
and inside that interpreter run from app import db
. From the docs:
Starting with Flask 0.11 the recommended way to work with the shell is the flask shell
command which does a lot of this automatically for you. For instance, the shell is automatically initialized with a loaded application context.
You can also create a request context yourself, but using flask shell
is handier.
I recently started learning the Flask framework, but now I am stuck, because – according to internet tutorials and documentation – my project is not working as it should be.
I have a larger project, but after seeing that problem I made a smaller one just to see why it is not working – but I still have no clue.
That is my ‘smaller’ code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:test123@localhost/ranking'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r' % self.username
@app.route('/')
def index():
return "helo world"
if __name__ == '__main__':
app.run()
and after running a python interpreter and typing there:
from app import db
I have no UserWarning (as in internet tutorials), but later – after typing:
db.create_all()
I received:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:UsersMePycharmProjectsFlaskvenvlibsite-packagesflask_sqlalchemyextension.py", line 868, in create_all
self._call_for_binds(bind_key, "create_all")
File "C:UsersMePycharmProjectsFlaskvenvlibsite-packagesflask_sqlalchemyextension.py", line 839, in _call_for_binds
engine = self.engines[key]
File "C:UsersMePycharmProjectsFlaskvenvlibsite-packagesflask_sqlalchemyextension.py", line 628, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
File "C:UsersMePycharmProjectsFlaskvenvlibsite-packageswerkzeuglocal.py", line 513, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
What did I wrong? What should I do to make it work? Please help me.
In your terminal, run:
flask shell
and inside that interpreter run from app import db
. From the docs:
Starting with Flask 0.11 the recommended way to work with the shell is the
flask shell
command which does a lot of this automatically for you. For instance, the shell is automatically initialized with a loaded application context.
You can also create a request context yourself, but using flask shell
is handier.