Python Flask Authentication Tutorial - Learn Flask Login

  Рет қаралды 226,102

Arpan Neupane

Arpan Neupane

Күн бұрын

Hey guys! Welcome back! In this video, I show you how to build a login authentication system using Flask and Python. We'll be using Flask-Login to build it.
If you don't know about Flask or if this is your first time using it, Flask is a Python web framework that is used to create web applications. Flask has a built-in login system that can be used to authenticate users. The login system in Flask is very simple and only requires a user to enter their username and password.
Mac Command - pip3 install flask flask_sqlalchemy flask_login flask_bcrypt flask_wtf wtforms email_validator
Windows Command - pip install flask flask_sqlalchemy flask_login flask_bcrypt flask_wtf wtforms email_validator
Code: github.com/arp...
My Website - arpanneupane.com
My GitHub: github.com/arp...
Official Flask-Login Docs - flask-login.re...
My Programming Gear :
Keyboard: amzn.to/42vXkxh
Laptop: amzn.to/3CkAP3W
Laptop Stand: amzn.to/3X116Oi
Desk: amzn.to/43wmIEt
Monitor: amzn.to/42BAaFH
Monitor Arm: amzn.to/3NR0APS
Chair: amzn.to/42vvKAn
Desk Mat/Mousepad: amzn.to/43AhKqj
Microphone: amzn.to/45RuQ43
Headphones: amzn.to/445sf4R
#Python // #Flask // #LearnToCode

Пікірлер: 478
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
For people wondering where the code is in this video, you can find it here: github.com/arpanneupane19/Python-Flask-Authentication-Tutorial
@iancorrea3151
@iancorrea3151 2 жыл бұрын
Can i request a tutorial about React and Flask Authentication? Thank you.
@k.c.9019
@k.c.9019 2 жыл бұрын
That's not the same code. Code in github doesn't have at least check_password_hash part.
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
@@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.
@k.c.9019
@k.c.9019 2 жыл бұрын
@@ArpanNeupaneProductions Thank you for your work :)
@Jack__2
@Jack__2 6 ай бұрын
​@@iancorrea3151 I am also making react + flask app have you make login and register page
@HassanRaza-cb3mz
@HassanRaza-cb3mz Жыл бұрын
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.
@davidk7212
@davidk7212 Жыл бұрын
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.
@SanSha2100
@SanSha2100 Жыл бұрын
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.
@philippkeller5882
@philippkeller5882 2 жыл бұрын
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
@wdblackout 2 жыл бұрын
right! tutorial nowadays just focused on the number of minutes for the views.
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Haha I appreciate it!
@Vangsguard
@Vangsguard 4 ай бұрын
@@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.
@wdblackout
@wdblackout 4 ай бұрын
@@Vangsguard necroposting. this is two years already and too late for a debate. you just have a kitkat, take a break alright?
@h_0412
@h_0412 2 жыл бұрын
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!
@alwinjames4777
@alwinjames4777 Жыл бұрын
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
@person....4169
@person....4169 Жыл бұрын
lol, I got the same issue did you find a solution?
@PranavMalleboyina
@PranavMalleboyina 18 күн бұрын
@@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.
@21Gannu
@21Gannu 2 жыл бұрын
you made this so simple. kudos… I suggest making whole series on flask it will benefit many students…
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Thank you!!
@Drinkyoghurt
@Drinkyoghurt 5 ай бұрын
I'm having issues with it setting up the DB file. for some reason it won't take. If I add a create_tables function it creates one in instance, but then doesn't seem to access it. Every time I submit my form it just reloads instead of taking the data I submitted
@steamhackman
@steamhackman 2 жыл бұрын
Just to echo most other commenters, great tutorial and very concise. Got my app up and running. Thank you muchly.
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Glad to have been able to help
@kevinrodriguez-zk5kq
@kevinrodriguez-zk5kq Жыл бұрын
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.
@moazali4757
@moazali4757 10 ай бұрын
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.
@wimvangeyt3866
@wimvangeyt3866 27 күн бұрын
put the db = SQLAlchemy(app) after the config statements
@Bob-kq6gt
@Bob-kq6gt Жыл бұрын
dont you need sessions to keep being logged in? Also my I mirror what you write and my database does not work.
@EpicNerdify
@EpicNerdify Жыл бұрын
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
@NasserAlshareefKSA
@NasserAlshareefKSA Ай бұрын
me too
@RansbyJohan
@RansbyJohan Жыл бұрын
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
@tinymicronano
@tinymicronano Жыл бұрын
me too
@geoffreyfouvry6094
@geoffreyfouvry6094 Жыл бұрын
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')
@mithunchandrasaha403
@mithunchandrasaha403 Жыл бұрын
Very Nice Explanation,Sir.Needs More Tutorial from you.
@black_ninja1858
@black_ninja1858 Жыл бұрын
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??
@paritoshraikar4026
@paritoshraikar4026 Жыл бұрын
try database and secret key commands before db=SQLAlchemy(app) and bcrypt=Bcrypt(app)..worked for me
@leonardoloayza
@leonardoloayza Жыл бұрын
@@paritoshraikar4026 It worked!!!
@lmoreno2103
@lmoreno2103 Жыл бұрын
@@paritoshraikar4026 worked for me, had same issue. thanks!
@rahulsumbly7310
@rahulsumbly7310 Жыл бұрын
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
@johannahigbea4521
@johannahigbea4521 Ай бұрын
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!
@indranil
@indranil Жыл бұрын
Great video!!.. Slightly off topic, which vscode theme have u used?
@Andreasstanca95
@Andreasstanca95 Жыл бұрын
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?
@end_player4032
@end_player4032 11 ай бұрын
i have the same problem
@RenanL.S.
@RenanL.S. Жыл бұрын
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.
@alwinjames4777
@alwinjames4777 Жыл бұрын
SAME HERE .DID YOU GET THE SOLUTION OR NOT
@rarisenpai
@rarisenpai 2 жыл бұрын
I am now a new subscriber you make great content and am going to watch every video I can from now on😄
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Welcome aboard!
@Cookie_Hub
@Cookie_Hub Жыл бұрын
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)
@selendivanloglu1932
@selendivanloglu1932 Жыл бұрын
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
@jeanlecigne4379
@jeanlecigne4379 Жыл бұрын
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
@omar_benaidy
@omar_benaidy Жыл бұрын
@@jeanlecigne4379 thank you so much you're a life saver
@kylekelly7232
@kylekelly7232 Жыл бұрын
@@jeanlecigne4379 just curious what you would need to do to use v3.0?
@josikie
@josikie Жыл бұрын
@@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.
@willisvensson
@willisvensson Жыл бұрын
lifesaver comment, appriciated. Thank you!!!
@progger1050
@progger1050 3 жыл бұрын
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
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
If you want to get the user’s name from the session, you can just do current_user.username.
@progger1050
@progger1050 3 жыл бұрын
What is {{hidden_tag}} error is say 1 positional argument required self
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
Can you share your code?
@ChanderMohan-lj9dy
@ChanderMohan-lj9dy Жыл бұрын
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.
@dope166
@dope166 Жыл бұрын
The validate_username function in register form, you haven’t called it anywhere in the app, how does it work? Is it called automatically?
@ammarbinmadi7175
@ammarbinmadi7175 Жыл бұрын
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
@atakankaraman4005
@atakankaraman4005 Жыл бұрын
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
@slc388
@slc388 2 жыл бұрын
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
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Can you share the code?
@BaoNguyendarkmatter820
@BaoNguyendarkmatter820 10 ай бұрын
At 13:18, I had to put line 7 and 8 (appp.config) before db=SQLAl to resolve a runtime error.
@danielfaran5783
@danielfaran5783 9 ай бұрын
thanks for the info
@Quaght
@Quaght 3 ай бұрын
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?
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 ай бұрын
Yes
@arunkumarvaradala7139
@arunkumarvaradala7139 3 жыл бұрын
Really helpful, Explained with very clear, Thank you so much. keep doing Many more on Flask and Machine Learning too.
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
of course!
@gregkrakow872
@gregkrakow872 3 жыл бұрын
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?
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
Thank you so much! The code is currently not available yet, I will make a GitHub repository for it.
@OmPathare-h1o
@OmPathare-h1o Жыл бұрын
Really liked the video. This is my first flask project. Understood many basic concepts. Thank you. The code is working.
@Sophistry0001
@Sophistry0001 Жыл бұрын
Can't get past 14:00. Keep getting an error that I have no clue how to solve
@ritusikpusik
@ritusikpusik 5 ай бұрын
When I'm trying to import db from app I'm getting ImportError: cannot import name 'db' from 'app'. Why is that so?
@aestedits4150
@aestedits4150 Жыл бұрын
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.
@baldoggie
@baldoggie Жыл бұрын
it is not working for me either
@MyselfGagan
@MyselfGagan 2 жыл бұрын
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
@khurshidbekkk2647
@khurshidbekkk2647 7 ай бұрын
Your explanation is so plain and understandable. Thank you very much. You have just earned another follower!
@jspencer89yt
@jspencer89yt Жыл бұрын
Anyone viewing this in 2023 this process has changed some. So expect some errors follow the documentation for latest updates.
@riteshkolate05
@riteshkolate05 7 ай бұрын
Where is documentation????
@valeeswarank
@valeeswarank 2 жыл бұрын
Nutshell explanation and simple and super mini project.
@andremiruzzi8968
@andremiruzzi8968 Жыл бұрын
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
@KS-ic4wv Жыл бұрын
facing the same problem
@andremiruzzi8968
@andremiruzzi8968 Жыл бұрын
@@KS-ic4wv it seems that the version for flask alchemy changed a bit. I found a fix here however: kzbin.info/www/bejne/hKqUmGCNoJqhr68&ab_channel=PeterSchneider
@1nicetyp431
@1nicetyp431 Жыл бұрын
Thanks you saved my evening, simple but wonderful
@aleksahadzic9302
@aleksahadzic9302 Жыл бұрын
For people who already know how to set up the flask app, you can start watching from 9:40
@peya02
@peya02 Жыл бұрын
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.
@TomTwyman
@TomTwyman 2 ай бұрын
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?
@adedayoadewale2509
@adedayoadewale2509 Жыл бұрын
after create_all user is not showing up after .tables
@christiannahas2142
@christiannahas2142 2 жыл бұрын
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.
@arjunpukale3310
@arjunpukale3310 Жыл бұрын
very simple and up to the point ❤
@milesthomas3317
@milesthomas3317 3 жыл бұрын
Really helpful, thanks so much.
@andyguan3553
@andyguan3553 Жыл бұрын
i was wondering why i cant from app import db? it only says that ImportError: cannot import name 'db' from 'app'
@aniketkadukar7772
@aniketkadukar7772 3 жыл бұрын
Man, You're awesome. Thanks!!
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
You’re welcome!
@RocketLR
@RocketLR Жыл бұрын
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..
@susanadesoji671
@susanadesoji671 3 жыл бұрын
This is a great tutorial, very helpful
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
Thanks!
@Oc3anWav3s
@Oc3anWav3s 3 жыл бұрын
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?
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
Thank you for the compliment! When they log in, you can do something like this in the HTML file: {{ current_user.username }}, etc.
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
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.
@timewasterlee
@timewasterlee Жыл бұрын
I‘ve watched a numbers of flask tutorials, but this one is the best one that express the core idea in such short time!!!
@CI30
@CI30 2 жыл бұрын
Hi, i'm getting this error "wtforms.validators, invalid syntax" line 7 how can I resolve it. TIA
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Can you show me the code that you wrote?
@davidbidzhoian1527
@davidbidzhoian1527 Жыл бұрын
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?
@kurty85
@kurty85 6 ай бұрын
I did all the steps and they worked perfect but I am having an issue adding more routes to the home page for "about, cloud, etc". The routes simply do not appear when added. Anyone experience this?
@MuhammadRakhaAlmasah-s9h
@MuhammadRakhaAlmasah-s9h Жыл бұрын
RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set. How to fix it ?
@lzmkalos
@lzmkalos Жыл бұрын
TIP: you must declare app.config['SQLALCHEMY_DATABASE_URI'], before db = SQLAlchemy(app);
@azyjmexcuseokstop924
@azyjmexcuseokstop924 Жыл бұрын
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 ?
@chitranshasiwal6791
@chitranshasiwal6791 3 жыл бұрын
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
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
Can you paste the line that is causing that issue?
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
For importing Flask, you should write this: from flask import Flask
@waynelei2187
@waynelei2187 Жыл бұрын
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
@edwardgyan9749
@edwardgyan9749 2 жыл бұрын
thanks for all you do. your teaching is great and hope you continue to upload videos.
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
I’m glad I can help :)
@HLD202
@HLD202 2 жыл бұрын
Hello, I have a short question that you didn't cover it in your video, [20:55]: what is form.hidden_tag() use for?
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
CSRF token
@himanshuS1718
@himanshuS1718 Жыл бұрын
I am getting "Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set" this error. can somebody help me?
@martezcarmouche3179
@martezcarmouche3179 Жыл бұрын
HEELLLPMy flask isn't working. When I hit run it gives me error "not recgnized as the name of cmdlet....". Can some one help!
@harrisonshu634
@harrisonshu634 2 жыл бұрын
Awesome straightforward tutorial thank you!
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Glad it helped!
@Mackerr
@Mackerr Жыл бұрын
thank you for this, you saved my grade
@jongolove6744
@jongolove6744 Жыл бұрын
The fact that you made this seem easy is actually impressive💡
@LukeEdet
@LukeEdet 5 ай бұрын
How did you start up ya terminal after creating the database coz my terminal isn't working was yours
@LukeEdet
@LukeEdet 5 ай бұрын
Pls can someone reply me based on this issue pls
@SomeoneSexy
@SomeoneSexy Жыл бұрын
I am having trouble with connecting to the database, when I run sqlite3 database.db, it says "the term sqlite3 is not recognized..." Not sure what I did wrong because I followed the same as your video. Send help pls! thanks!
@AndreKaiqueDellIsola
@AndreKaiqueDellIsola 3 ай бұрын
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.
@arnavghosh4242
@arnavghosh4242 Жыл бұрын
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.
@its_just_me9
@its_just_me9 9 ай бұрын
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 ??
@MuhammadMuhsinYahya
@MuhammadMuhsinYahya 2 ай бұрын
Very good explanation and well presented, thank you. But how about the styling the page
@TheNishi42
@TheNishi42 Жыл бұрын
getting error while doing registration TypeError: generate_password_hash() missing 1 required positional argument: 'password'
@vedkhetle7318
@vedkhetle7318 Жыл бұрын
dosent work!
@keevo9194
@keevo9194 6 ай бұрын
What extension does he have for his database.db file?
@kamutabung511
@kamutabung511 Жыл бұрын
most simplest tutorial ever i watched, yet effective, super best tutorial
@miguelfernandes657
@miguelfernandes657 2 жыл бұрын
Thank you very much! Simple and effective!
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Glad you were able to learn something!
@muhammmadaditiyachoirunbas4614
@muhammmadaditiyachoirunbas4614 10 ай бұрын
How do I create a database.db file whose format is still not SQL?
@stanpedrieta105
@stanpedrieta105 Жыл бұрын
How do you show the validationerror message if the user already exist?
@johnlloydfrancisco3401
@johnlloydfrancisco3401 7 ай бұрын
hello sir can you help me with my web app using flask, i need to create a point of sale for a pharmacy.
@italobuitron1165
@italobuitron1165 Жыл бұрын
I have a question with the @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) 1. When you log, the USERNAME is passed as user_id into load_user(user_id), right? then, 2. you use a User.query... (what i supposed is a query from Sql) which return the ID (in the DB) from the USERNAME So, if you use current_username.get_id() it return whatever u return from load_user(), in this case the ID from the query? is it?
@jeanpeuplu3862
@jeanpeuplu3862 Жыл бұрын
Thank you so much, I use this at work and I am sooo grateful for this perfect tutorial! Thanks!!
@allanmitala8104
@allanmitala8104 3 жыл бұрын
Man great video, I was struggling with a flask project but know am sure i can finish it. Thanks for the video.
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
Of course!
@jonathan3488
@jonathan3488 2 жыл бұрын
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.
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
You can do {{current_user.}} to get data for the current user. Ex: {{current_user.username}}
@jonathan3488
@jonathan3488 2 жыл бұрын
@@ArpanNeupaneProductions Oh thanks!
@harshsharan4127
@harshsharan4127 11 ай бұрын
what is your version of flask and werkzeug??
@rodkafelipe6605
@rodkafelipe6605 3 ай бұрын
watchout now: "Changed in version 3.0: No longer defaults to an in-memory SQLite database if not set. " Which throws runtime error, if SQLALCHEMY_DATABASE_URI is not set, right before the command db.createall()
@sabinaanibassabinaanibas
@sabinaanibassabinaanibas 2 жыл бұрын
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!
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
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.
@Onlyhousefr
@Onlyhousefr Жыл бұрын
Great value tutorial, thank you so much !
@tinymicronano
@tinymicronano Жыл бұрын
How to handle the validate_username and show the message in HTML?
@azpycoder3337
@azpycoder3337 2 жыл бұрын
Dear Arpan Neupane, can you provide link to text version of this tutorial?
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
Hello, unfortunately I don’t have a text version for this tutorial.
@Mrtero100
@Mrtero100 2 жыл бұрын
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
@ArpanNeupaneProductions
@ArpanNeupaneProductions 2 жыл бұрын
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!
@georgejuarez660
@georgejuarez660 Жыл бұрын
Nice video, but I would like to know one thing. I want the system to generate an error message (which is visible on the site) when the user in the registration puts the same email. Here I say how can I do?
@rodrigomarchi9755
@rodrigomarchi9755 Жыл бұрын
Great tutorial. I just wish you had a more comprehensive tutorial as well, creating a production ready app with more complexities involved.
@ArpanNeupaneProductions
@ArpanNeupaneProductions Жыл бұрын
Great suggestion!
@sushantthapachhetri7225
@sushantthapachhetri7225 3 жыл бұрын
bro i have a question, where will the raise validation message goes,it is not showing message "Username already used" though it is working....??
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
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.
@sushantthapachhetri7225
@sushantthapachhetri7225 3 жыл бұрын
@@ArpanNeupaneProductions Thank you!!
@ArpanNeupaneProductions
@ArpanNeupaneProductions 3 жыл бұрын
@@sushantthapachhetri7225 Happy to help! 😁
User Authentication - Flask Tutorial Series #8
28:14
NeuralNine
Рет қаралды 9 М.
build a meme Python website (Flask Tutorial for Beginners)
13:30
NetworkChuck
Рет қаралды 489 М.
Touching Act of Kindness Brings Hope to the Homeless #shorts
00:18
Fabiosa Best Lifehacks
Рет қаралды 20 МЛН
Brawl Stars Edit😈📕
00:15
Kan Andrey
Рет қаралды 49 МЛН
Bike Vs Tricycle Fast Challenge
00:43
Russo
Рет қаралды 77 МЛН
FastAPI, Flask or Django - Which Should You Use?
9:49
Tech With Tim
Рет қаралды 82 М.
User Login with Flask_Login - Flask Fridays #22
23:51
Codemy.com
Рет қаралды 57 М.
Python Blog Tutorial #2 - Flask User Authentication and Security
52:10
Authentication in React app using Flask Server-Sided Sessions
54:12
Authenticating a Flask API Using JSON Web Tokens
20:33
Pretty Printed
Рет қаралды 174 М.
Secure Login System in Python
14:43
NeuralNine
Рет қаралды 109 М.
Touching Act of Kindness Brings Hope to the Homeless #shorts
00:18
Fabiosa Best Lifehacks
Рет қаралды 20 МЛН