@@k.c.9019 Thank you for reminding me. I hadn’t added a repo for this app when the video was made and saw many people requesting it so I decided to make one this month. Thanks for reminding me though.
Straight to the point with no fluff, yet thorough and with every detail explained succinctly. And no cringey attempts at comedy. This is exactly what the world needs more of.
I don't usually comment on videos, but WOW. This is the most simplest and most focused tutorial for this particular subject. You are doing great job man! loved the video.
What people are taking hours and still not able to illustrate, your focused approach teaches it minimum time with maximum impact. Kudos to you and very well done.
Such a great tutorial. I like that you focussed on the bare minimum, no styling, no fancy databases, no long explanations. That got me going with login and forms in Flask
@@wdblackout You are aware that you can just... skip those parts of the video right? Also if you don't like long explanations you might want to find a different career. Understand why you do what you do is the most important in this field. Doing it is one thing, understanding why is what's hard. If not everyone could be a programmer with ChatGPT.
One of the best tutorial I've ever seen. I really appreciate that you chose to explain your code instead of blasting some random music like some other tutorials nowadays. Thank you!
showing this error at 14:41 >>> from app import db Traceback (most recent call last): File "", line 1, in File "C:\Users\User\Desktop\flask-auth\app.py", line 5, in db = SQLAlchemy(app) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\extension.py", line 219, in __init__ self.init_app(app) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\extension.py", line 301, in init_app raise RuntimeError( RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set. can you please help me
Hi sir, at 14:00 when i try to do import , i get this error ModuleNotFoundError: No module named 'flask', does anyone know of a fix for this? i have installed every necessary flask pip install modules
Hey, very nice and useful video 👍. Just one suggestion, make playlists on your channel for videos on same topic it will be easier for users to navigate videos on your channel
On a scale of 10, you got 11.5... Just one thing: Don't forget the .decode('utf8') in the line............ hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf8')
Hi! I'm having the message error for Either SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set after I try to import db. Is this something outside of this tutorial? I am unsure as to why it continues to pop up.
You might want to move the creation of the db object after configuring the database URI. It will solve this problem. Here's how you can modify your code: app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' # Move the configuration here app.config['SECRET_KEY'] = 'thisisasecretkey' db = SQLAlchemy(app) # Initialize the db object after configuring the app bcrypt = Bcrypt(app) Copy this code, and replace with previous lines of code.
I have a problem on 14:02 when typing from app import db I got: RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set. I' ve done everuthing same (working on Ubuntu) .I spent some time looking for solution, but couldn't find :((. Can anyone help please??
Hi Arpan, thanks for the tutorial, very simple and effective. I'm on minute 13.56 right now, and my terminal is giving me a runtime error though I don't know why. I followed the code you wrote exactly, but this "RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set." is showing up on my terminal. Do you know how I can solve this? Thanks so much
pip3 uninstall flask_sqlalchemy and pip3 install flask-sqlalchemy==2.5.1because big changes with flask-sqlalchemy==3.0 sqlite db in memory not set as default in this version
Amazing content but I get stuck at some point. when I want to db.create_all() in my terminal, I get the following error: RuntimeError: Working outside of application context. Any ideas how to solve this?
Hi thanks for this great tutorial. I am having a problem, "database.db" is not working for me, I have installed SQL all extensions but the problem is same still. Could you please help.
I like the simplicity of your approach. The app contains just what is needed and it is explained all in less than 30 minutes. Is the code available for this project?
When I run your code i get this error, can you help? Traceback (most recent call last): File "/home/johan/Dokumenter/login/app.py", line 10, in db = SQLAlchemy(app) File "/usr/local/lib/python3.9/dist-packages/flask_sqlalchemy/extension.py", line 219, in __init__ self.init_app(app) File "/usr/local/lib/python3.9/dist-packages/flask_sqlalchemy/extension.py", line 307, in init_app raise RuntimeError( RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set. B
Just found this video and I loved how well you described everything! You earned a subscriber. Could you possibly make a video trailing off this - when a user logs in with their username, it will display the dashboard based on their specific details?
Been following the tutorial up to the point where you run the .tables command , but for me it is returning nothing. i had to do the create_all() this way in order for it to work: >>> from app import app, db >>> app.app_context().push() >>> db.create_all() >>> exit() but when i check with the .tables i find nothing there
@@KS-ic4wv it seems that the version for flask alchemy changed a bit. I found a fix here however: ruclips.net/video/Ny1g-Wk5nyM/видео.html&ab_channel=PeterSchneider
Great video, love that you go step by step and explain why you are adding the code. I know you are using a MAC, but wanted to ask if you tested this full tutorial in a Windows system. It seems that many users are having issues with the DB part of the tutorial and think it might be good for you to provide more insight and answers on the issues that may occur in a Windows environment. When I run 'from app import db', it creates a folder called instance, therefore, when I run db.create_all() I get an error, because there is no database.db in the instance folder.. Can you please try this exact tutorial in Windows and update the video to include the differences? Thank you!
Hey arpan, thanks for your video. I would like to know, before trying the sqlite command, should I have sqlite previously installed in my system? I'm sorry if it seems obvious, but I have to ask.
at 14:27 my Sqlite database file didn't contain any tables so i followed the following format #Unix/Mac (note the four leading slashes) sqlite:////absolute/path/to/foo.db #Windows (note 3 leading forward slashes and backslash escapes) sqlite:///C:\\absolute\\path\\to\\foo.db #Windows (alternative using raw string) r'sqlite:///C:\absolute\path\to\foo.db' in my Sqlite file link at line 7
Hi, I'm getting this error "sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user" when I try to register any name and am not able to solve the issue. Any assistance is greatly appreciated.
Hey Arpan, thanks for the great video. I have a quick question: when the user is logged out, how do we manage the security of the other html pages (this case dashboard.html)? lets say the user logged in and got redirected to the dashboard, clicks logout ->back to login page, but lets say user pressed backspace to force go into previous page (which is dashboard.html). Will the app show the dashboard html? or is there any forbidden/404.html?
I believe in the video I used the @login_required decorator which will only allow you to access a page if logged in. So to answer your question, they will not be able to.
Thank you! For me i had some troubles with bcrypt.check_password_hash, bcrypt.generate_password_hash so i imported them from flask_bcrypt and used the directly like : hashed_password = generate_password_hash(form.password.data) of course your method is very good and works but incase some have my same problem this can be helpful
Thank you not only for watching the video but also for providing a solution to viewers who may have encountered a similar problem :) Greatly appreciated!
hello, i got an error message when i import library as a "from flask_wtf import FlaskForm" i received an error. ImportError: cannot import name 'url_encode' from 'werkzeug'. i've installed all library from requirements.txt with same version my python version is 3.10. pycharm version is 2022.3.1. what is your python version could you please help me
15:38 O erro "No module named 'flask'" indica que o módulo Flask não está instalado no seu ambiente Python atual. Para resolver isso, siga os passos abaixo: ### Passos para instalar o Flask 1. **Criar um ambiente virtual** (se ainda não tiver criado): ```bash python -m venv venv ``` 2. **Ativar o ambiente virtual**: - No Windows: ```bash venv\Scripts\activate ``` - No macOS/Linux: ```bash source venv/bin/activate ``` 3. **Instalar Flask e outras dependências**: ```bash pip install flask flask_sqlalchemy flask_login flask_wtf ``` 4. **Verificar a instalação**: - Você pode verificar se o Flask foi instalado corretamente executando: ```bash pip list ``` - Certifique-se de que `flask`, `flask_sqlalchemy`, `flask_login` e `flask_wtf` estejam listados. ### Reestruturando o projeto Certifique-se de que a estrutura do seu projeto está correta. Aqui está um exemplo: ``` my_flask_app/ │ ├── app.py ├── models.py ├── forms.py ├── templates/ │ ├── login.html │ ├── register.html │ └── home.html └── static/ └── styles.css ``` ### Arquivo `app.py` ```python from flask import Flask, render_template, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user from forms import LoginForm, RegisterForm from models import User, db app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db.init_app(app) login_manager = LoginManager(app) login_manager.login_view = 'login' @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) @app.route('/') @app.route('/home') def home(): return render_template('home.html') @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and user.check_password(form.password.data): login_user(user, remember=form.remember.data) return redirect(url_for('home')) else: flash('Login Unsuccessful. Please check email and password', 'danger') return render_template('login.html', form=form) @app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() flash('Your account has been created!', 'success') return redirect(url_for('login')) return render_template('register.html', form=form) @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('home')) if __name__ == '__main__': with app.app_context(): db.create_all() app.run(debug=True) ``` ### Arquivo `models.py` ```python from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash db = SQLAlchemy() class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(150), nullable=False, unique=True) email = db.Column(db.String(150), nullable=False, unique=True) password_hash = db.Column(db.String(256), nullable=False) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) ``` ### Arquivo `forms.py` ```python from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField from wtforms.validators import DataRequired, Length, Email, EqualTo class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) remember = BooleanField('Remember Me') submit = SubmitField('Login') class RegisterForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)]) email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Sign Up') ``` ### Verifique se todos os arquivos estão no mesmo diretório e executando o servidor Flask Certifique-se de que todos os arquivos estão no diretório correto e execute o servidor Flask novamente. Navegue até o diretório do seu projeto e execute: ```bash flask run ``` Se o Flask ainda não estiver encontrado, tente instalar o Flask explicitamente novamente e garantir que você está ativando o ambiente virtual corretamente: ```bash pip install flask ``` Certifique-se de que o comando `pip list` inclui `flask` na lista de pacotes instalados.
When I put the key and SQLAlchemy part I get this: RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set My webpage stop working.
Wow! Great video! you just saved me a TON of time - new to Flask, and I was busy trying to piece together everything I needed for a simple authentication system, and you nailed it in one! Thanks a ton! I do have a question about some of the items in your requirements.txt - you have some items in there that aren't explicitly called out in the video - cffi, asgiref, dnspython, etc. Can you expand on why you included them?
Hi , I Am "ValueError: Invalid salt" while validating the login inputs, I have tried everything from google but not able to resolve it, please help me out in this
Great video. A question: after I ran "db.create_all()" and checked for ".tables", I noticed that "user" is not there. What do you think is wrong with my execution?
@@ArpanNeupaneProductions Very interesting content! Just curious, do you have some resources on the deployment of python web apps that require login? If find your content super helpful!
Hello all, I get as far as 12:03 but then I find that I get this error 'RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.' Can anyone help? (ps. compared to other tutorials on the topic this one is the best I have found so far. Thank you for taking the time to put it together)
is it possible to add in the def register(): function a connection, cursor, and cursor.execute(INSERT...) to save the data entered in the register into a sqlite3 data base that is already created? Because when i tried that the data was not saving in the database.
Hi, any idea how to setup the expiry or duration for he the cookie? Thank you! I think it should have something to do with the login_user method, but I am not able to make it work
I get this Error: pls help Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set. File "/home/miuka/Python/FlaskTest2/app.py", line 10, in db = SQLAlchemy(app)
M getting a very different error..!!! Can u help me resolve.. Import "flask" could not be resolved from sourcePylance (reportMissingModuleSource) This is the only error I am getting
Great tutorial, but isn't it better to use UUID's instead of Incrementing Numbers for ID field?😄Great Tutorial, and I have Successfully Learnt Authentication in Flask in 26 mins.
Is there a way to make required admin system??? I already used current_user.is_authenticated to check if the user already sign in they will see and use some specific part for login users, but I want to made some function required admin role, even you already login you can't use. (Sorry for the grammar 🙏 English is not my main language.)
Hi, The pip3 install command which installs the flask_sqlachemy and flask_bcrypt fails on my Mac with this error: ERROR: Could not find a version that satisfies the requirement flask_bycrypt (from versions: none) ERROR: No matching distribution found for flask_bycrypt . I have tried several things but cannot get it to work. Please help.
You spelled it wrong. It should be “pip3 install flask_bcrypt” for installing Flask-Bcrypt and “pip3 install flask_sqlalchemy” for installing Flask-SQLAlchemy.
Hi after some trial and error it finally worked for me. However, I didn't understand how do I fetch the current user from the templates after the login. I see that the load_user() method is invoked every time I load a page, but I have no idea what to do.
Thanks a lot for the video very helpful and well explained! I having an issue with url_for, when signing up its not taking me to login, when login in its not taking me to dashboard, etc. Do you know why could that be? Thanks!
Sir please and please help me do a video on how to add a search 🔎 systems to the flask app 🔎. cause I search for this request on RUclips but didn't get any
If you'd like to create a search engine, then I'd recommend checking this link out: dev.to/itachiuchiha/using-elasticsearch-with-python-and-flask-2i0e If you'd like to just build a search feature to search users, you can create a form on your page and when that form is submitted, you can get the fields of that form and query the User table and see if a user with that username exists or not. If they exist, you can redirect to a user's profile, and if they don't exist, you can flash a message stating that they do not exist.
@@ArpanNeupaneProductions ok bro sounds good but to be frank I followed that but don't really understand.. And about your second statement I just want to use it to search 🔎 for either specific user or users that's all
omg. im 35 and trying to get into IT, some basic Devops and programming and then I see you so perfectly explaining this. I wish i was 15 again. But Im trying to get it working with flask-ldap3 and flask-security as well. So I can use the groups as roles. Somehow got some annoying issues with that though. Are there actually still apps or websites that store user information on their on databases out there? Isnt everything Oauth these days, or backed by an ldap?
That depends on the auth system the website uses. OAuth is newer and is used if you want to avoid building your own system. This video was just for beginners to build their own system with Flask. Glad to hear the positive comments! Wishing you great luck for the upcoming career!! Good luck :)
@@ArpanNeupaneProductions thanks. Im still a bit overwhelmed by the sheer amount of possibilities in flask. I have my own ldap backend with freeipa so im trying to retrieve the users there, authenticate them, store their username and group and then allow certain areas of my website. So users can comment on my blog posts, and admins can post etc. But it's getting quite complicated and sometimes some things magically stop working haha.
My apologies, I forgot to include that in the video. To view the error message when a validation error is raised, you can do this in your HTML template: {% for error in form.username.errors %} {{error}} {% endfor %} You can write those lines in both the register and login templates. If the program encounters a validation error (ex: username already exists), it will display the error.
Thank you very much for great tutorial, but I want to change design of login page. I've made my HTML file, but I don't know how to combine it with your code from login.html, because there is only {{form.username}} etc.. Can you please help mi with customizing that HTML file? Thank you in advance!
Sure! You would basically make a normal HTML file in your templates directory and then you'd just render it in your Python file. Then you can add the {{form.username}}, {{form.password}}, etc as well and you can style it however you'd like.
shouldnt the password be hashed from the client side ? as it is, the password still goes on the network uncrypted, and is only crypted when it enters the post function, server side, no ?
I'm getting an error when creating the User class. Unresolved attribute reference 'Column' for class 'SQLAlchemy' . I get the same error for db.Integer and db.String. Can you help me fix this?
Yes, I also imported the library the same way you did. I came across a few other people experiencing the same issue on a different video. I've tried finding a solution on the internet but no success.
My code is written from a different video, so it may not be identical to yours. Here it is: from flask import Flask, redirect, url_for, render_template, request, session, flash from datetime import timedelta from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = "anyStringHere" app.permanent_session_lifetime = timedelta(days=5) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///users.sqlite3" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db = SQLAlchemy(app) class Users(db.Model): _id = db.Column("id", db.Integer, primary_key=True) name = db.Column("name", db.String(100)) email = db.Column(db.String(100)) def __init__(self, name, email): self.name = name self.email = email
Well, I got ValueError: Password must be non-empty of bcrypt.generate_password_hash(form.password.data). I run the same code as you posted. What's wrong?
You can. However, if you decide to change the route for the backend in the future for GET & POST requests, the url_for() will call the function with the route and you won’t need to manually adjust routes for each page.
hello i keep having this issue: RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set. i've checked multiple times and idk whats wrong with my code
For people wondering where the code is in this video, you can find it here: github.com/arpanneupane19/Python-Flask-Authentication-Tutorial
Can i request a tutorial about React and Flask Authentication? Thank you.
That's not the same code. Code in github doesn't have at least check_password_hash part.
@@k.c.9019 Thank you for reminding me. I hadn’t added a repo for this app when the video was made and saw many people requesting it so I decided to make one this month. Thanks for reminding me though.
@@ArpanNeupaneProductions Thank you for your work :)
@@iancorrea3151 I am also making react + flask app have you make login and register page
No unnecessary introduction, no begging for subs, no attempts at stupid humour just straight to the point. Excellent video, thank you.
Straight to the point with no fluff, yet thorough and with every detail explained succinctly. And no cringey attempts at comedy. This is exactly what the world needs more of.
I don't usually comment on videos, but WOW. This is the most simplest and most focused tutorial for this particular subject. You are doing great job man! loved the video.
What people are taking hours and still not able to illustrate, your focused approach teaches it minimum time with maximum impact. Kudos to you and very well done.
Such a great tutorial. I like that you focussed on the bare minimum, no styling, no fancy databases, no long explanations. That got me going with login and forms in Flask
right! tutorial nowadays just focused on the number of minutes for the views.
Haha I appreciate it!
@@wdblackout You are aware that you can just... skip those parts of the video right? Also if you don't like long explanations you might want to find a different career. Understand why you do what you do is the most important in this field. Doing it is one thing, understanding why is what's hard. If not everyone could be a programmer with ChatGPT.
@@Vangsguard necroposting. this is two years already and too late for a debate.
you just have a kitkat, take a break alright?
One of the best tutorial I've ever seen. I really appreciate that you chose to explain your code instead of blasting some random music like some other tutorials nowadays. Thank you!
you made this so simple. kudos… I suggest making whole series on flask it will benefit many students…
Thank you!!
Just to echo most other commenters, great tutorial and very concise. Got my app up and running. Thank you muchly.
Glad to have been able to help
Very Nice Explanation,Sir.Needs More Tutorial from you.
showing this error at 14:41
>>> from app import db
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\User\Desktop\flask-auth\app.py", line 5, in
db = SQLAlchemy(app)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\extension.py", line 219, in __init__
self.init_app(app)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\extension.py", line 301, in init_app
raise RuntimeError(
RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.
can you please help me
lol, I got the same issue did you find a solution?
@@person....4169 The solution would be to create the db object after you set the URI and the secret key values. I tried this and it worked fine.
@@PranavMalleboyina hi. can you help me?
For people who already know how to set up the flask app, you can start watching from 9:40
Really liked the video. This is my first flask project. Understood many basic concepts. Thank you. The code is working.
Really helpful, Explained with very clear, Thank you so much.
keep doing Many more on Flask and Machine Learning too.
of course!
I am now a new subscriber you make great content and am going to watch every video I can from now on😄
Welcome aboard!
At 13:18, I had to put line 7 and 8 (appp.config) before db=SQLAl to resolve a runtime error.
thanks for the info
Hi sir, at 14:00 when i try to do import , i get this error ModuleNotFoundError: No module named 'flask', does anyone know of a fix for this? i have installed every necessary flask pip install modules
me too
I‘ve watched a numbers of flask tutorials, but this one is the best one that express the core idea in such short time!!!
Great video!!.. Slightly off topic, which vscode theme have u used?
Hey, very nice and useful video 👍. Just one suggestion, make playlists on your channel for videos on same topic it will be easier for users to navigate videos on your channel
On a scale of 10, you got 11.5... Just one thing: Don't forget the .decode('utf8') in the line............ hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf8')
dont you need sessions to keep being logged in? Also my I mirror what you write and my database does not work.
Hi! I'm having the message error for Either SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set after I try to import db. Is this something outside of this tutorial? I am unsure as to why it continues to pop up.
You might want to move the creation of the db object after configuring the database URI. It will solve this problem. Here's how you can modify your code:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' # Move the configuration here
app.config['SECRET_KEY'] = 'thisisasecretkey'
db = SQLAlchemy(app) # Initialize the db object after configuring the app
bcrypt = Bcrypt(app)
Copy this code, and replace with previous lines of code.
put the db = SQLAlchemy(app) after the config statements
Nutshell explanation and simple and super mini project.
I have a problem on 14:02 when typing from app import db I got:
RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.
I' ve done everuthing same (working on Ubuntu) .I spent some time looking for solution, but couldn't find :((. Can anyone help please??
try database and secret key commands before db=SQLAlchemy(app) and bcrypt=Bcrypt(app)..worked for me
@@paritoshraikar4026 It worked!!!
@@paritoshraikar4026 worked for me, had same issue. thanks!
Your explanation is so plain and understandable. Thank you very much. You have just earned another follower!
Hi Arpan, thanks for the tutorial, very simple and effective. I'm on minute 13.56 right now, and my terminal is giving me a runtime error though I don't know why. I followed the code you wrote exactly, but this "RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set." is showing up on my terminal. Do you know how I can solve this? Thanks so much
pip3 uninstall flask_sqlalchemy and pip3 install flask-sqlalchemy==2.5.1because big changes with flask-sqlalchemy==3.0 sqlite db in memory not set as default in this version
@@jeanlecigne4379 thank you so much you're a life saver
@@jeanlecigne4379 just curious what you would need to do to use v3.0?
@@kylekelly7232 Hi Kyle! We can initialize the db first. Only after adding configurations, do we use db.init_app(app) to bind the db to the app.
lifesaver comment, appriciated. Thank you!!!
14:08
from app import app, db
with app.app_context():
db.create_all()
Amazing content but I get stuck at some point. when I want to db.create_all() in my terminal, I get the following error: RuntimeError: Working outside of application context.
Any ideas how to solve this?
i have the same problem
The fact that you made this seem easy is actually impressive💡
thanks for all you do. your teaching is great and hope you continue to upload videos.
I’m glad I can help :)
Hello, I have a short question that you didn't cover it in your video, [20:55]: what is form.hidden_tag() use for?
CSRF token
Can't get past 14:00. Keep getting an error that I have no clue how to solve
I have a questions
If I login I want to create a session but how to get the user name in the session because it is coming from the form
If you want to get the user’s name from the session, you can just do current_user.username.
Hi thanks for this great tutorial. I am having a problem, "database.db" is not working for me, I have installed SQL all extensions but the problem is same still. Could you please help.
it is not working for me either
I like the simplicity of your approach. The app contains just what is needed and it is explained all in less than 30 minutes. Is the code available for this project?
Thank you so much! The code is currently not available yet, I will make a GitHub repository for it.
The validate_username function in register form, you haven’t called it anywhere in the app, how does it work? Is it called automatically?
Thank you so much, I use this at work and I am sooo grateful for this perfect tutorial! Thanks!!
When I run your code i get this error, can you help?
Traceback (most recent call last):
File "/home/johan/Dokumenter/login/app.py", line 10, in
db = SQLAlchemy(app)
File "/usr/local/lib/python3.9/dist-packages/flask_sqlalchemy/extension.py", line 219, in __init__
self.init_app(app)
File "/usr/local/lib/python3.9/dist-packages/flask_sqlalchemy/extension.py", line 307, in init_app
raise RuntimeError(
RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.
B
me too
Just found this video and I loved how well you described everything! You earned a subscriber.
Could you possibly make a video trailing off this - when a user logs in with their username, it will display the dashboard based on their specific details?
Thank you for the compliment!
When they log in, you can do something like this in the HTML file:
{{ current_user.username }}, etc.
You can basically access the current_user object in Flask and use that to display certain details/properties about the current user that is logged in.
Been following the tutorial up to the point where you run the .tables command , but for me it is returning nothing. i had to do the create_all() this way in order for it to work:
>>> from app import app, db
>>> app.app_context().push()
>>> db.create_all()
>>> exit()
but when i check with the .tables i find nothing there
facing the same problem
@@KS-ic4wv it seems that the version for flask alchemy changed a bit. I found a fix here however: ruclips.net/video/Ny1g-Wk5nyM/видео.html&ab_channel=PeterSchneider
Thanks you saved my evening, simple but wonderful
most simplest tutorial ever i watched, yet effective, super best tutorial
Say I have 5 web pages but only one of them requires a login. Do I add @login_required only to the route to that page?
Yes
This is a great tutorial, very helpful
Thanks!
very simple and up to the point ❤
Great video, love that you go step by step and explain why you are adding the code. I know you are using a MAC, but wanted to ask if you tested this full tutorial in a Windows system. It seems that many users are having issues with the DB part of the tutorial and think it might be good for you to provide more insight and answers on the issues that may occur in a Windows environment. When I run 'from app import db', it creates a folder called instance, therefore, when I run db.create_all() I get an error, because there is no database.db in the instance folder.. Can you please try this exact tutorial in Windows and update the video to include the differences? Thank you!
exactly ! I also faced this problem what could be possible solution our guy here he explained very well
Really helpful, thanks so much.
Hey arpan, thanks for your video. I would like to know, before trying the sqlite command, should I have sqlite previously installed in my system? I'm sorry if it seems obvious, but I have to ask.
Installed sqlite as shown in this video ruclips.net/video/BomCx0jbwPY/видео.html
Man, You're awesome. Thanks!!
You’re welcome!
What is {{hidden_tag}} error is say 1 positional argument required self
Can you share your code?
at 14:27 my Sqlite database file didn't contain any tables so i followed the following format
#Unix/Mac (note the four leading slashes)
sqlite:////absolute/path/to/foo.db
#Windows (note 3 leading forward slashes and backslash escapes)
sqlite:///C:\\absolute\\path\\to\\foo.db
#Windows (alternative using raw string)
r'sqlite:///C:\absolute\path\to\foo.db'
in my Sqlite file link at line 7
Hi, I'm getting this error "sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user" when I try to register any name and am not able to solve the issue. Any assistance is greatly appreciated.
Man great video, I was struggling with a flask project but know am sure i can finish it. Thanks for the video.
Of course!
amazing tutorial, thanks for the help!
Hey Arpan, thanks for the great video. I have a quick question: when the user is logged out, how do we manage the security of the other html pages (this case dashboard.html)? lets say the user logged in and got redirected to the dashboard, clicks logout ->back to login page, but lets say user pressed backspace to force go into previous page (which is dashboard.html). Will the app show the dashboard html? or is there any forbidden/404.html?
I believe in the video I used the @login_required decorator which will only allow you to access a page if logged in. So to answer your question, they will not be able to.
@@ArpanNeupaneProductions I just tried by myself with my flask app. it automatically redirects to the login page even if i try forcing it. thanks!!!
@@paulkang2806 Glad to help!!
Thank you!
For me i had some troubles with bcrypt.check_password_hash, bcrypt.generate_password_hash so i imported them from flask_bcrypt and used the directly like : hashed_password = generate_password_hash(form.password.data)
of course your method is very good and works but incase some have my same problem this can be helpful
Thank you not only for watching the video but also for providing a solution to viewers who may have encountered a similar problem :)
Greatly appreciated!
hello, i got an error message
when i import library as a "from flask_wtf import FlaskForm" i received an error. ImportError: cannot import name 'url_encode' from 'werkzeug'.
i've installed all library from requirements.txt with same version
my python version is 3.10. pycharm version is 2022.3.1.
what is your python version
could you please help me
15:38
O erro "No module named 'flask'" indica que o módulo Flask não está instalado no seu ambiente Python atual. Para resolver isso, siga os passos abaixo:
### Passos para instalar o Flask
1. **Criar um ambiente virtual** (se ainda não tiver criado):
```bash
python -m venv venv
```
2. **Ativar o ambiente virtual**:
- No Windows:
```bash
venv\Scripts\activate
```
- No macOS/Linux:
```bash
source venv/bin/activate
```
3. **Instalar Flask e outras dependências**:
```bash
pip install flask flask_sqlalchemy flask_login flask_wtf
```
4. **Verificar a instalação**:
- Você pode verificar se o Flask foi instalado corretamente executando:
```bash
pip list
```
- Certifique-se de que `flask`, `flask_sqlalchemy`, `flask_login` e `flask_wtf` estejam listados.
### Reestruturando o projeto
Certifique-se de que a estrutura do seu projeto está correta. Aqui está um exemplo:
```
my_flask_app/
│
├── app.py
├── models.py
├── forms.py
├── templates/
│ ├── login.html
│ ├── register.html
│ └── home.html
└── static/
└── styles.css
```
### Arquivo `app.py`
```python
from flask import Flask, render_template, redirect, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from forms import LoginForm, RegisterForm
from models import User, db
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db.init_app(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/')
@app.route('/home')
def home():
return render_template('home.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and user.check_password(form.password.data):
login_user(user, remember=form.remember.data)
return redirect(url_for('home'))
else:
flash('Login Unsuccessful. Please check email and password', 'danger')
return render_template('login.html', form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(email=form.email.data, username=form.username.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Your account has been created!', 'success')
return redirect(url_for('login'))
return render_template('register.html', form=form)
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)
```
### Arquivo `models.py`
```python
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
db = SQLAlchemy()
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), nullable=False, unique=True)
email = db.Column(db.String(150), nullable=False, unique=True)
password_hash = db.Column(db.String(256), nullable=False)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
```
### Arquivo `forms.py`
```python
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
remember = BooleanField('Remember Me')
submit = SubmitField('Login')
class RegisterForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Sign Up')
```
### Verifique se todos os arquivos estão no mesmo diretório e executando o servidor Flask
Certifique-se de que todos os arquivos estão no diretório correto e execute o servidor Flask novamente. Navegue até o diretório do seu projeto e execute:
```bash
flask run
```
Se o Flask ainda não estiver encontrado, tente instalar o Flask explicitamente novamente e garantir que você está ativando o ambiente virtual corretamente:
```bash
pip install flask
```
Certifique-se de que o comando `pip list` inclui `flask` na lista de pacotes instalados.
thank you for this, you saved my grade
When I put the key and SQLAlchemy part I get this: RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set
My webpage stop working.
SAME HERE .DID YOU GET THE SOLUTION OR NOT
Wow! Great video! you just saved me a TON of time - new to Flask, and I was busy trying to piece together everything I needed for a simple authentication system, and you nailed it in one! Thanks a ton! I do have a question about some of the items in your requirements.txt - you have some items in there that aren't explicitly called out in the video - cffi, asgiref, dnspython, etc. Can you expand on why you included them?
Hi , I Am "ValueError: Invalid salt" while validating the login inputs, I have tried everything from google but not able to resolve it, please help me out in this
Great video. A question: after I ran "db.create_all()" and checked for ".tables", I noticed that "user" is not there. What do you think is wrong with my execution?
Actually, I made a typo in earlier codes: I should have copied "SQLALCHEMY_DATABASE_URI" instead of "SQLALCHEMY_DATABASE_URL"
Problem solved. Thanks!
@@casualcomputer6544 Sweet!
@@ArpanNeupaneProductions Very interesting content! Just curious, do you have some resources on the deployment of python web apps that require login? If find your content super helpful!
@@casualcomputer6544 Yeah! I have a video on how to deploy a Flask app to Heroku which can be found here: ruclips.net/video/D2GLVoiEZyE/видео.html
I have the same problem but it doesnt work even tho my URI is right. What is wrong?
Awesome straightforward tutorial thank you!
Glad it helped!
What steps should I do to deploy the app on a hosting? I'm trying and I get internal server error. You don't like something about the login part.
Hello all, I get as far as 12:03 but then I find that I get this error 'RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.' Can anyone help? (ps. compared to other tutorials on the topic this one is the best I have found so far. Thank you for taking the time to put it together)
same im stuck there too
Thank you very much! Simple and effective!
Glad you were able to learn something!
is it possible to add in the def register(): function a connection, cursor, and cursor.execute(INSERT...) to save the data entered in the register into a sqlite3 data base that is already created? Because when i tried that the data was not saving in the database.
Very good explanation and well presented, thank you. But how about the styling the page
when i type from app import db
it shows error like
name 'db' is not defined
why it shows like that please reply me sir
Can you share the code?
Hi, any idea how to setup the expiry or duration for he the cookie? Thank you! I think it should have something to do with the login_user method, but I am not able to make it work
its a great tuturial but i am lost at the classes of the form can we do this without them ?? can we just type it in html ??
RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.
How to fix it ?
TIP: you must declare app.config['SQLALCHEMY_DATABASE_URI'], before db = SQLAlchemy(app);
Hi, i'm getting this error "wtforms.validators, invalid syntax" line 7
how can I resolve it.
TIA
Can you show me the code that you wrote?
I get this Error: pls help
Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.
File "/home/miuka/Python/FlaskTest2/app.py", line 10, in
db = SQLAlchemy(app)
Anyone viewing this in 2023 this process has changed some. So expect some errors follow the documentation for latest updates.
Where is documentation????
M getting a very different error..!!! Can u help me resolve..
Import "flask" could not be resolved from sourcePylance (reportMissingModuleSource)
This is the only error I am getting
Can you paste the line that is causing that issue?
For importing Flask, you should write this:
from flask import Flask
Great tutorial, but isn't it better to use UUID's instead of Incrementing Numbers for ID field?😄Great Tutorial, and I have Successfully Learnt Authentication in Flask in 26 mins.
Is there a way to make required admin system???
I already used current_user.is_authenticated to check if the user already sign in they will see and use some specific part for login users, but I want to made some function required admin role, even you already login you can't use.
(Sorry for the grammar 🙏 English is not my main language.)
Hi, The pip3 install command which installs the flask_sqlachemy and flask_bcrypt fails on my Mac with this error: ERROR: Could not find a version that satisfies the requirement flask_bycrypt (from versions: none)
ERROR: No matching distribution found for flask_bycrypt . I have tried several things but cannot get it to work. Please help.
You spelled it wrong.
It should be “pip3 install flask_bcrypt” for installing Flask-Bcrypt and “pip3 install flask_sqlalchemy” for installing Flask-SQLAlchemy.
@@ArpanNeupaneProductions Thank you!
@@dimplebhatia2953 Did it work ?
@@ArpanNeupaneProductions Yup, it did
@@dimplebhatia2953 Happy I could help :)
Hi after some trial and error it finally worked for me. However, I didn't understand how do I fetch the current user from the templates after the login. I see that the load_user() method is invoked every time I load a page, but I have no idea what to do.
You can do
{{current_user.}}
to get data for the current user.
Ex:
{{current_user.username}}
@@ArpanNeupaneProductions Oh thanks!
Thanks a lot for the video very helpful and well explained! I having an issue with url_for, when signing up its not taking me to login, when login in its not taking me to dashboard, etc. Do you know why could that be? Thanks!
Can you share the code ?
@@ArpanNeupaneProductions having the same problem, any luck with it?
Sir please and please help me do a video on how to add a search 🔎 systems to the flask app 🔎. cause I search for this request on RUclips but didn't get any
If you'd like to create a search engine, then I'd recommend checking this link out: dev.to/itachiuchiha/using-elasticsearch-with-python-and-flask-2i0e
If you'd like to just build a search feature to search users, you can create a form on your page and when that form is submitted, you can get the fields of that form and query the User table and see if a user with that username exists or not. If they exist, you can redirect to a user's profile, and if they don't exist, you can flash a message stating that they do not exist.
@@ArpanNeupaneProductions ok bro sounds good but to be frank I followed that but don't really understand.. And about your second statement I just want to use it to search 🔎 for either specific user or users that's all
So please if you can do the video I will love it paa
omg. im 35 and trying to get into IT, some basic Devops and programming and then I see you so perfectly explaining this. I wish i was 15 again.
But Im trying to get it working with flask-ldap3 and flask-security as well. So I can use the groups as roles. Somehow got some annoying issues with that though. Are there actually still apps or websites that store user information on their on databases out there? Isnt everything Oauth these days, or backed by an ldap?
That depends on the auth system the website uses. OAuth is newer and is used if you want to avoid building your own system. This video was just for beginners to build their own system with Flask.
Glad to hear the positive comments! Wishing you great luck for the upcoming career!! Good luck :)
@@ArpanNeupaneProductions thanks. Im still a bit overwhelmed by the sheer amount of possibilities in flask. I have my own ldap backend with freeipa so im trying to retrieve the users there, authenticate them, store their username and group and then allow certain areas of my website. So users can comment on my blog posts, and admins can post etc. But it's getting quite complicated and sometimes some things magically stop working haha.
Great tutorial. I just wish you had a more comprehensive tutorial as well, creating a production ready app with more complexities involved.
Great suggestion!
bro i have a question, where will the raise validation message goes,it is not showing message "Username already used" though it is working....??
My apologies, I forgot to include that in the video. To view the error message when a validation error is raised, you can do this in your HTML template:
{% for error in form.username.errors %}
{{error}}
{% endfor %}
You can write those lines in both the register and login templates. If the program encounters a validation error (ex: username already exists), it will display the error.
@@ArpanNeupaneProductions Thank you!!
@@sushantthapachhetri7225 Happy to help! 😁
Great value tutorial, thank you so much !
Thank you very much for great tutorial, but I want to change design of login page. I've made my HTML file, but I don't know how to combine it with your code from login.html, because there is only {{form.username}} etc.. Can you please help mi with customizing that HTML file? Thank you in advance!
Sure! You would basically make a normal HTML file in your templates directory and then you'd just render it in your Python file. Then you can add the {{form.username}}, {{form.password}}, etc as well and you can style it however you'd like.
Dear Arpan Neupane, can you provide link to text version of this tutorial?
Hello, unfortunately I don’t have a text version for this tutorial.
i was wondering why i cant from app import db? it only says that ImportError: cannot import name 'db' from 'app'
is it just me or did u forget to show the part where u filled in the forms action attribute? I cant find it where you put that info in..
shouldnt the password be hashed from the client side ? as it is, the password still goes on the network uncrypted, and is only crypted when it enters the post function, server side, no ?
I'm getting an error when creating the User class. Unresolved attribute reference 'Column' for class 'SQLAlchemy' .
I get the same error for db.Integer and db.String. Can you help me fix this?
Did you do
db = SQLAlchemy(app)
?
Yes, I also imported the library the same way you did. I came across a few other people experiencing the same issue on a different video. I've tried finding a solution on the internet but no success.
@@fireman8141 Can you share a link to your code ?
My code is written from a different video, so it may not be identical to yours. Here it is:
from flask import Flask, redirect, url_for, render_template, request, session, flash
from datetime import timedelta
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = "anyStringHere"
app.permanent_session_lifetime = timedelta(days=5)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///users.sqlite3"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
class Users(db.Model):
_id = db.Column("id", db.Integer, primary_key=True)
name = db.Column("name", db.String(100))
email = db.Column(db.String(100))
def __init__(self, name, email):
self.name = name
self.email = email
@@fireman8141 Can you copy the exact database configuration shown in the video and replace it with your current configuration and see if that works?
after create_all user is not showing up after .tables
Well, I got ValueError: Password must be non-empty of bcrypt.generate_password_hash(form.password.data). I run the same code as you posted. What's wrong?
Is ir necessary to use url_for in html page? We can't simply use the route name without url_for function?
You can. However, if you decide to change the route for the backend in the future for GET & POST requests, the url_for() will call the function with the route and you won’t need to manually adjust routes for each page.
@@ArpanNeupaneProductions will you explain it with an example please?
Awesome tutorial!
Thanks!
How did you start up ya terminal after creating the database coz my terminal isn't working was yours
Pls can someone reply me based on this issue pls
24:49 but where does the session get the user id from ????????
It is stored within Flask-Login
hello i keep having this issue: RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.
i've checked multiple times and idk whats wrong with my code
You have to put the db = SQLAlchemy(app) line under the app.config lines