So recently i started a project on Python with Flask as a newbie and wanted to create a "Register and Login Page" everything was going well. But when I arrived to create a table in database that stores the username and the password i was getting an error and the table wouldnt get created.
my topic in a more detailed way is that when i go to the bash and type this commands i get this error
i start with the termninal with python3 and i import from the app the db so it imports the variable db = SQLAlchemy after that i type db.create_all()
and I get this error
sk@Aress-MacBook-Air FPLPage % python3
Python 3.12.1 (v3.12.1:2305ca5144, Dec 7 2023, 17:23:38) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from app import db
>>> db.create_all()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/flask_sqlalchemy/extension.py", line 900, in create_all
self._call_for_binds(bind_key, "create_all")
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/flask_sqlalchemy/extension.py", line 871, in _call_for_binds
engine = self.engines[key]
^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/flask_sqlalchemy/extension.py", line 687, in engines
app = current_app._get_current_object() # type: ignore[attr-defined]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/werkzeug/local.py", line 508, 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.
Im also gonna upload the app.py code so you can get a better undertanding
from flask import Flask, render_template, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Length, ValidationError
from flask_bcrypt import Bcrypt
app = Flask(__name__)
bcrypt = Bcrypt(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SECRET_KEY'] ="b9ZHtEpIeiKHuM8"
db = SQLAlchemy(app)
class User(db.Model, UserMixin): ##Database Table for User
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=False, unique=True)
password = db.Column(db.String(50), nullable=False)
class RegisterForm(FlaskForm):
username = StringField(validators=[InputRequired(),Length(min = 4, max = 20)],render_kw={"placeholder": "Username"})
password = StringField(validators=[InputRequired(),Length(min = 4, max = 20)],render_kw={"placeholder": "Password"})
submit = SubmitField("Register")
class LoginForm(FlaskForm):
username = StringField(validators=[InputRequired(),Length(min = 4, max = 20)],render_kw={"placeholder": "Username"})
password = StringField(validators=[InputRequired(),Length(min = 4, max = 20)],render_kw={"placeholder": "Password"})
submit = SubmitField("Login")
def validate_username(self,username):
existing_user_username = User.query.filter_by(
username = username.data).first()
if existing_user_username:
raise ValidationError(
"The Username is already in use.Try to think another one:)"
)
I create a models.py and moved the code with flask and SQLAlchemy and the class but none of that work. so now i dont know what im doing wrong
After a lot of searching somehow I found how to make it work
Solution:
As of Flask-SQLAlchemy 3.0, all access to db.engine(and db.session) requires an active Flask application context.
db.create_all uses db.engine , so it requires an app context.
When Flask handles requests or runs CLI commands, a context is automatically pushed. You only need to push one manually outside of those situations, such as while setting up the app.
Instead of calling create_all in your code, you can also call it manually in the shell. Use flask shell to start a Python shell that already has an app context and the db object imported.
Or push a context manually if using a plain Python shell.