How to Use Databases With SQLAlchemy - Flask Fridays #8

  Рет қаралды 90,377

Codemy.com

Codemy.com

Күн бұрын

In this video I'll show you how to use databases with Flask using SQLAlchemy!
Using databases with flask is a little harder than with other web frameworks, but it doesn't have to be too bad if you use SQLAlchemy. I'll show you how in this video by setting up a SQLite database and creating a table, and then adding a form to the site that allows us to add data to the database.
After we learn how to do this with SQLite, we'll learn about MySQL and Postgres.
Timecodes
0:00​​ - Introduction
1:13 - Pip Install Flask-SQLAlchemy
1:56 - Import SQLalchemy To Our Flask App
2:55 - Set SQLAlchemy Database URI For SQLITE
4:20 - Initialize The Database
4:50 - Create Our Database Model
9:39 - Import Model From The Terminal
10:38 - Create UserForm
11:25 - Create Route And Add_User Function
12:20 - Create Add_User.html Page
13:24 - Add Link To Add_User.html on Navbar
14:22 - Set Form to UserForm in Add_User Function
15:00 - Validate Form On Submit
16:54 - Save Data To Database On Submit
18:50 - Query Database And Output Users To Webpage
21:37 - Style Form With Bootstrap
22:37 - Add Table For User Output
24:46 - Conclusion

Пікірлер: 128
@Codemycom
@Codemycom 3 жыл бұрын
▶️ Watch Entire Flask Friday Playlist ✅ Subscribe To My KZfaq Channel: bit.ly/3ig2eJn bit.ly/2IGzvOR ▶️ See More At: ✅ Join My Facebook Group: Codemy.com bit.ly/2GFmOBz ▶️ Learn to Code at Codemy.com ✅ Buy a Codemy T-Shirt! Take $30 off with coupon code: youtube1 bit.ly/2VC9WUN ▶️ Get The Code bit.ly/2L1jBl5
@todorvladimirov1960
@todorvladimirov1960 3 жыл бұрын
I usually play educational videos at x1.5 speed. I want to thank you for being so thoughtful as to provide it as the default option! Also, great content!
@Codemycom
@Codemycom 3 жыл бұрын
Ha glad you enjoyed it!
@witty_name9768
@witty_name9768 5 ай бұрын
Just want to say that after so long these videos are still helping people learn. Thanks for keeping this series available.
@Codemycom
@Codemycom 5 ай бұрын
Welcome!
@SAMIGAMER44
@SAMIGAMER44 2 жыл бұрын
You really dont know how golden this is
@Codemycom
@Codemycom 2 жыл бұрын
Glad you're enjoying it!
@karlduckett
@karlduckett 2 жыл бұрын
Awesome! flask-sqlalchemy is great! Thanks for the tutorial!
@Codemycom
@Codemycom 2 жыл бұрын
Glad you enjoyed it!
@karthikrajamony6044
@karthikrajamony6044 3 жыл бұрын
Was waiting for this
@Codemycom
@Codemycom 3 жыл бұрын
Glad you like it
@MAAAX2211
@MAAAX2211 2 жыл бұрын
THANK FOR YOUR EFFORT, APPRECIATE IT
@Codemycom
@Codemycom 2 жыл бұрын
My pleasure!
@laavanyathanapalan4596
@laavanyathanapalan4596 2 жыл бұрын
Thank you soo much. Really helpful!
@Codemycom
@Codemycom 2 жыл бұрын
Glad it helped!
@macmohit123
@macmohit123 Жыл бұрын
Hi, I am unable to create db.. using db.create_all().... I am getting following error : " 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()." ... I have tried to use with function def create_app(): app = Flask(__name__) with app.app_context(): ..., but it doesnt resolve the error.. can you please help
@kendar1193
@kendar1193 Жыл бұрын
I think I figured it out: Put this code right below Users class stuff: with app.app_context(): db.create_all() Hope it helps ;)
@TheM4rszal
@TheM4rszal Жыл бұрын
$ python3 >>> from hello import app, db >>> app.app_context().push() >>> db.create_all() >>> exit() OR use command 'flask shell'
@Osiris_fc
@Osiris_fc Жыл бұрын
@@kendar1193 thanks hey. It has been giving me headaches
@renanrivera9805
@renanrivera9805 8 ай бұрын
@@TheM4rszal thanks it works for me
@parthivlakhani3097
@parthivlakhani3097 Жыл бұрын
Thank You! Please make a Complete Machine Learning Series
@Codemycom
@Codemycom Жыл бұрын
Yes
@kristynaherman5737
@kristynaherman5737 Жыл бұрын
Hi! This is really great and I am following it for my first flask app project, but I've made my databases + tables in the MySQL workbench and I'm having a lot of trouble connecting the app to my tables (i.e. sending the outputs of my form to the tables initiated in workbench). Would you please add an explanation on how to connect to an existing table (instead of creating one directly in the script)? Thanks a lot!
@wongjowo9152
@wongjowo9152 2 жыл бұрын
Hello, i want to ask about returning the database as string (at 8:58). Could you explain the syntax? Also is it must be self.name?
@diddlybop
@diddlybop 3 жыл бұрын
Very helpful! It would've been really helpful to have a larger code window, the panning along with the typing was really not ideal. Maybe there is a reason why you have a zoomed in window, but most tutorials look fine with a full sized window. Thank you for the helpful content! thumbs up.
@Codemycom
@Codemycom 3 жыл бұрын
click the expand button on the video player to go fullscreen
@diddlybop
@diddlybop 3 жыл бұрын
@@Codemycom ah, I can see how it would seem like I'm talking about the video window, I was referring to your coding editor window in your video. Seeing the entire line of code rather than panning with your typing is what I meant. But it was helpful nonetheless 👏👏👏
@hiwab41
@hiwab41 3 жыл бұрын
Thanks 😊
@Codemycom
@Codemycom 3 жыл бұрын
Welcome 😊
@scar8d
@scar8d 3 жыл бұрын
sir, not gonna lie, you and Heisenberg(Walter White) look uncannily similar.
@Codemycom
@Codemycom 3 жыл бұрын
Ha, I get that a lot...
@elitecoder9246
@elitecoder9246 3 жыл бұрын
Awesome
@Codemycom
@Codemycom 3 жыл бұрын
Thanks
@user-oy4bp3bx3o
@user-oy4bp3bx3o Жыл бұрын
while running the db.create_all() command i got the "RuntimeError: Working outside of application context". please help me out. I have been following along with the Flask Friday since day 1.
@evansmith87
@evansmith87 11 ай бұрын
Did you resolve this problem? I am getting the same problem.
@ShivamThakur-pl7ew
@ShivamThakur-pl7ew 4 ай бұрын
from filename import app, db with app.app_context(): db.create_all() it will resolve your issue
@sevii9256
@sevii9256 Жыл бұрын
UPDATE I was getting errors when trying to create the database. I put this in my code: with app.app_context(): db.create_all() I added this (for a single run) underneath the class that defined the db.Columns(). I also may have ran db.init_app(app) in between that and the class (or at some point in cmd - importing both db and app), I don't remember where or if that helped or not. Either way, I got it working now (5/5/23)
@Codemycom
@Codemycom Жыл бұрын
cool
@witty_name9768
@witty_name9768 5 ай бұрын
I am just getting into this series now and having the same problem. I can't quite follow your explanation of your solution. Would you be able to point me to a related tutorial or might you remember exactly what you did? Thanks in advance for any help. I've been slogging through google results for a while now.
@officielcesar
@officielcesar 2 жыл бұрын
Really great! From the beginning to the end ! Thanks a lot! One thing : I find it a bit hard to follow sometimes because the text is SO BIG ^^ Would be great to dezoom a bit.
@Codemycom
@Codemycom 2 жыл бұрын
When I do that, people complain that the text is too small.
@cxl6808
@cxl6808 2 жыл бұрын
hello! what if i get an error called AttributeError: 'NoneType' object has no attribute 'is_active' whenever i add my users to the database?
@alanalmeida7887
@alanalmeida7887 2 жыл бұрын
Should db.create_all() be executed through the python shell always (to create tables)? Or can we do that in our source code? Because if we deploy the webapp somewhere will we have to explicitly run db.create_all() in the python shell before running the webserver in deployment?
@Codemycom
@Codemycom 2 жыл бұрын
You can run commands through the shell from your python file...
@salmantas2335
@salmantas2335 10 ай бұрын
use this: with app.app_context(): db.create_all() also, I'm not sure of it but you have to use "with" because SQL alchemy requires working Python code
@pandurangasharmaramaka
@pandurangasharmaramaka 2 жыл бұрын
When added an email second time, it's not getting added but getting the same message 'User Added Successfully'. What can I do?
@wingielee
@wingielee Жыл бұрын
Hello john. Thank you for your video on flask and other KZfaq videos you have been releasing. However, i have a problem with the initialization and creation of the databse as instructed in this video at time 10:20. When i tried to create my database it kept bringing up the error below; 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. is there anything am not doing right? i"l appreciate your prompt response as usual. Thank you
@Codemycom
@Codemycom Жыл бұрын
No idea...google the error and see what you find.
@prethammuthappabs2241
@prethammuthappabs2241 Жыл бұрын
app.app_context().push() add this line to ur code and in the terminal type "from app import app from app import db" it worked for me
@wingielee
@wingielee Жыл бұрын
@@prethammuthappabs2241 thank you bro. I've got it done.. appreciate
@princeakhoury4294
@princeakhoury4294 Жыл бұрын
@@prethammuthappabs2241 Where exactly should I write this? I am still getting an error. New to this. Help would really be appreciated! Thanks!
@prethammuthappabs2241
@prethammuthappabs2241 Жыл бұрын
@@princeakhoury4294 the app.app_context thing in ur code down where you try to write ur database name and rest u type in terminal
@DimiEG
@DimiEG 3 жыл бұрын
Thanks a lot. Very interesting. Believe PostgreSQL will be the same.
@Codemycom
@Codemycom 3 жыл бұрын
Yeah we'll get into postgres soon
@jacquewilson5568
@jacquewilson5568 2 жыл бұрын
Great video... is there any good reasons to not suppress the warning with something like this? (newbie here) ? import warnings from sqlalchemy import exc as sa_exc with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) # code here...
@rban123
@rban123 3 жыл бұрын
migrating project to SQLalchemy i found a tool called sqlacodegen which allowed me to convert my entire existing database into a SQLalchemy model in one command
@Codemycom
@Codemycom 3 жыл бұрын
fun
@karolinalencina7121
@karolinalencina7121 Жыл бұрын
Thank you so much for the tutorial, it helped me a lot at uni! I'm getting an error: File "/Users/karo/Library/Python/3.8/lib/python/site-packages/werkzeug/local.py", line 513, in _get_current_object raise RuntimeError(unbound_message) from None RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed the current application. To solve this, set up an application context with app.app_context(). See the documentation for more information. Do you have any suggestions, please? I've tried about 10 stackoverflow answers but nothing works for me. From my research I believe this is an issue that happens because of a recent update to SQLAlchemy?
@Codemycom
@Codemycom Жыл бұрын
No idea...you can always use older versions of sqlalchemy. When you pip install it add ==versionNumber to it.
@wackowyatt00
@wackowyatt00 Жыл бұрын
I know this is very old, but if anyone else has the same issue I found a solution. Add the line app.app_context().push() under db = SQLAlchemy(app) In python terminal write: >>>from app import app >>>from app import db >>>db.create_all() That created an instance directory with the database inside.
@akshykumarvaidyanathan8181
@akshykumarvaidyanathan8181 Жыл бұрын
@@wackowyatt00 if you are using python shell try >>> from project import app, db >>> app.app_context().push() >>> db.create_all() this worked for me
@moh.abibsafaqdillah2845
@moh.abibsafaqdillah2845 5 ай бұрын
thanks bro@@wackowyatt00
@tarunkamra18
@tarunkamra18 2 жыл бұрын
are you installing sql alchemy in virtual environment of flask ? (venv)
@Codemycom
@Codemycom 2 жыл бұрын
Yes, the video shows exactly what I'm doing.
@vigramvasi442
@vigramvasi442 2 жыл бұрын
Hello mate, is it possible to move a row up or down in Sqlalchemy?
@Codemycom
@Codemycom 2 жыл бұрын
What do you mean?
@srishtijaiswal7079
@srishtijaiswal7079 2 жыл бұрын
Hello sir you have responded to each question so I am expecting the response from your side very soon by today , sir will the database here store on our local server , if yes how can we store it on remote server as I want to deploy my website using heroku
@Codemycom
@Codemycom 2 жыл бұрын
Yes it stores local of course. I have videos on using production databases on heroku on the list.
@georlybibas5846
@georlybibas5846 Жыл бұрын
I NEED SOME SERIOUS HELP. When I entered "from hello import db" I get nothing, no response at all. no errors, but no confirmation as well and when i tried the create_all(), I got a bunch of errors. I can't proceed. I looked it up myself but I can't find anything useful. I even tried to skip using sqlite and head over the mysql one, but the same problem persist. Please help.
@Codemycom
@Codemycom Жыл бұрын
Are you using the exact same tools that I use? Doing the exact same thing as the video?
@georlybibas5846
@georlybibas5846 Жыл бұрын
Why are my replies not showing up :)
@georlybibas5846
@georlybibas5846 Жыл бұрын
yes, apparently, I managed to create the database, idk if it will work as intended but now I have a new problem. When I load the user/add page, it picks up the "add" as a name, since the user/ makes it dynamic. So right now, I can't load the add_user page. Help?
@georlybibas5846
@georlybibas5846 Жыл бұрын
I managed to create the database by using these commands from hello import app, db app.app_context().push() db.create_all() Are these possibly the reason for my current problem now?
@georlybibas5846
@georlybibas5846 Жыл бұрын
I tried to change the route and it says in the loaded page "Method Not Allowed" "The method is not allowed for the requested URL."
@jin-zf1ur
@jin-zf1ur Жыл бұрын
The video awesome. however, somehow i am not able to get the table displayed as i add the users and it does not get saved down. The userid is not incremental by 1 as i add user. wonder why? i am using kali-linux and code-oss
@Codemycom
@Codemycom Жыл бұрын
Recheck your steps vs the video and see what you did differently.
@danilobrignone6880
@danilobrignone6880 2 жыл бұрын
Hello sir,I use mac but i don't have wintpy how do i install it? it doesn't make me create the database from classic python, because it says hello doesn't exist
@Codemycom
@Codemycom 2 жыл бұрын
you don't need to use winpty, just use the command without it
@MickeyMouse-ke9jb
@MickeyMouse-ke9jb 2 жыл бұрын
why do some people use "session" when connecting using SQLAlchemy?
@Codemycom
@Codemycom 2 жыл бұрын
A session is a specific thing, it keeps track of a specific user while they are using the system.
@eddin8583
@eddin8583 2 жыл бұрын
i keep getting this error sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: users.date_added help plzz
@Codemycom
@Codemycom 2 жыл бұрын
It's telling you the problem, you don't have a date_added column in your database
@timjames4306
@timjames4306 Жыл бұрын
did you got the solution ?
@abdullah-sx2qf
@abdullah-sx2qf 2 жыл бұрын
from main import db + ~~~~ The 'from' keyword is not supported in this version of the language.
@abdullah-sx2qf
@abdullah-sx2qf 2 жыл бұрын
PLEASE HELP
@Codemycom
@Codemycom 2 жыл бұрын
that's not true, you must have an error in your code. Check it against my code carefully.
@prajwalm.s7976
@prajwalm.s7976 8 ай бұрын
I am getting this error 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.
@Codemycom
@Codemycom 8 ай бұрын
What did you do differently from the video?
@prajwalm.s7976
@prajwalm.s7976 8 ай бұрын
@@Codemycom nothing
@YandereEnthusiast
@YandereEnthusiast 3 ай бұрын
@@Codemycom It is because 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.
@TehPwnerer
@TehPwnerer Жыл бұрын
Does everybody that uses flash just dump everything into the same damn file is there not any example anywhere at all where this isn't done cause I can't find it and it's actually quite ridiculous
@Codemycom
@Codemycom Жыл бұрын
What's actually quite ridiculous is that you couldn't find any reference online to Blueprints and Factories. Me thinks you didn't search very far, or look at the Flask Documentation at all...I mean sheesh, a google search for "how to organize large flask projects" immediately shows you this. But hey, it's much easier to just come online and snark and complain, right? lol
@gangjiatharva999
@gangjiatharva999 2 жыл бұрын
why do we need a virtual environment? can't we just use flask without a virtual environment? why?
@Codemycom
@Codemycom 2 жыл бұрын
It's standard practices. It's the correct way. You may need to install different versions of flask for different projects and you can't do that unless you have a virtual environment.
@yomaldiaholson4577
@yomaldiaholson4577 2 жыл бұрын
Think of it this way: your computer is a room in your apartment/house with a really nice hardwood floor. When you are doing projects like this, things can get pretty messy, now you don't want to ruin that floor, right? So, what do you do? You grab a container, or in this case a virtual environment, so that you can keep all the work from getting on your floor. Now, you don't have to worry too much about ruining your expensive floor! Hope that helps! 😉
@gangjiatharva999
@gangjiatharva999 2 жыл бұрын
@@yomaldiaholson4577 Yeah, thanks, its just a little late reply but works. Thanks again.
@yomaldiaholson4577
@yomaldiaholson4577 2 жыл бұрын
@@gangjiatharva999 no problem! Just know, it's never too late to use a virtual environment. I wasn't using one at first, but I moved my project to it afterwards. Just remember it for next time
@GustavoMingo
@GustavoMingo 11 ай бұрын
Why? UnboundLocalError: local variable 'our_users' referenced before assignment!!!! Review and repeat and find no error!
@palkisachdeva8246
@palkisachdeva8246 8 ай бұрын
I cant see the values stored in my db!!!
@Codemycom
@Codemycom 8 ай бұрын
Rewatch the video and try to figure out what you did differently...
@hodaamz2952
@hodaamz2952 Жыл бұрын
please the winpty python command doesn't work for me !!
@Codemycom
@Codemycom Жыл бұрын
That command is just for people on Windows using the git bash terminal. Use the same command without the winpty part
@riddhikpankhania325
@riddhikpankhania325 2 жыл бұрын
can we get code?
@Codemycom
@Codemycom 2 жыл бұрын
It's always in the pinned comment
@daggercentral9818
@daggercentral9818 3 жыл бұрын
so many ads after every 5 mins there is an ad disturbing... 😂🤣
@Codemycom
@Codemycom 3 жыл бұрын
ha, really? I see one ad when I watch it..
@MeMyselfAndBob
@MeMyselfAndBob Жыл бұрын
Hi, I've tried to add "dateOfBirth = db.Column(db.DateTime)" to the Users(db.Model) class, but it doesn't work. I Googled for two days, but I cannot find a decent answer. When I change the data type to string as in "dateOfBirth = db.Column(db.String(10)" is works just fine. It seems that sqlalchemy doesn't recognise the 'datetime' data type for entering text. When I change it to "dateOfBirth = db.Column(db.DateTime, default=datetime.utcnow)" and remove the birthday text field from the form, it works fine too. I tried very possible format like "YYYY-MM-DD", "YYYY-MM-DD HH:Mi:Sc.xxxxxx" etc. but no change in result. This is the StatementError: "sqlalchemy.exc.StatementError: (builtins.TypeError) SQLite DateTime type only accepts Python datetime and date objects as input. [SQL: INSERT INTO users (created, "firstName", "lastName", "dateOfBirth", email, phone) VALUES (?, ?, ?, ?, ?, ?) [parameters: [{'email': 'john.doe@yahoo.com', 'phone': '+112345678', 'dateOfBirth': '2001-01-01', 'lastName': 'Doe', 'firstName': 'John'}]]" Any tips how to book more success? Thanks a lot!
@mdsanima
@mdsanima 8 ай бұрын
make the font more bigger please, now I can see 18 line of code only, I want to see 8 line
@Codemycom
@Codemycom 8 ай бұрын
The font is huge...there's something wrong with your screen. Reset your display settings.
@mdsanima
@mdsanima 8 ай бұрын
@@Codemycom Everything is fine with my screen. When I open Visual Studio Code, I can see at least 80 lines of code! I don't understand why you upload videos to KZfaq in Full HD resolution, and the font in video is so large. Is it comfortable for you to work, seeing only such a small piece of code?
@elitecoder9246
@elitecoder9246 3 жыл бұрын
Hi
@Codemycom
@Codemycom 3 жыл бұрын
Hi
@elitecoder9246
@elitecoder9246 3 жыл бұрын
@@Codemycom nice
@iamkorn
@iamkorn Жыл бұрын
thank you sir. Could you accept my request? Can you say "You are goddam right"?
@Codemycom
@Codemycom Жыл бұрын
lol
@tobopat
@tobopat 2 жыл бұрын
Why is the face on the screen ?
@Codemycom
@Codemycom 2 жыл бұрын
Why ask stupid questions?
How To Use MySQL Database With Flask - Flask Fridays #9
19:00
Codemy.com
Рет қаралды 110 М.
Web Forms With WTF! - Flask Fridays #5
22:56
Codemy.com
Рет қаралды 65 М.
ОСКАР ИСПОРТИЛ ДЖОНИ ЖИЗНЬ 😢 @lenta_com
01:01
FOOLED THE GUARD🤢
00:54
INO
Рет қаралды 62 МЛН
Vivaan  Tanya once again pranked Papa 🤣😇🤣
00:10
seema lamba
Рет қаралды 25 МЛН
Databases & SQLAlchemy - Flask Tutorial Series #7
33:58
NeuralNine
Рет қаралды 9 М.
How to Use Flask-SQLAlchemy With Flask Blueprints
20:10
Pretty Printed
Рет қаралды 34 М.
SQLAlchemy Turns Python Objects Into Database Entries
22:23
NeuralNine
Рет қаралды 157 М.
Getting Started With Flask-SQLAlchemy
15:27
Pretty Printed
Рет қаралды 90 М.
Build your first REST API with Flask and PostgreSQL
27:42
teclado
Рет қаралды 59 М.
tRPC, gRPC, GraphQL or REST: when to use what?
10:46
Software Developer Diaries
Рет қаралды 71 М.
ОСКАР ИСПОРТИЛ ДЖОНИ ЖИЗНЬ 😢 @lenta_com
01:01