Python Flask Tutorial: Full-Featured Web App Part 4 - Database with Flask-SQLAlchemy

Поделиться
HTML-код
  • Опубликовано: 29 ноя 2024

Комментарии • 1 тыс.

  • @danielwarzecha2007
    @danielwarzecha2007 Год назад +355

    Hey All: As of version SQLAlchemy 3.0 to create your db file you will need to run some commands like this in the shell :
    from project import app, db
    app.app_context().push()
    db.create_all()
    Then the .db file is created in a folder called "Instance" in your project.
    Hope this helps some one

    • @MykhailoRogozhyn
      @MykhailoRogozhyn Год назад +4

      Thank you very much. It really helps me.

    • @MattFussell
      @MattFussell Год назад +5

      I was able to get the database created, but none of the follow-up steps worked for me. I'm sure given enough time I could find a fix, but I'm short on it, so I'm hoping it works well enough for rest of the tutorial.

    • @MykhailoRogozhyn
      @MykhailoRogozhyn Год назад +7

      @@MattFussell Everything else works as in the video. But I don't really like that the database is stored in the Instance directory. I changed the path to the database file as described in Miguel Grinberg's book.
      import os
      basedir = os.path.abspath(os.path.dirname(__file__))
      app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'site.db')
      Maybe it will be useful for others.

    • @harshitpathak5958
      @harshitpathak5958 Год назад +1

      I somehow managed to create this site.db but now , 1- I couldn't able to run any other command for entering the users in command prompt (getting same out of context error)
      2 - if adding the user within our
      with app.app_context():
      db.create_all()
      user 1= details.....
      db.session.add(user1)
      By doins so I am still getting a integrity error for email , even its unique

    • @MattFussell
      @MattFussell Год назад

      @@harshitpathak5958 My DB knowledge is thin, so apply the appropriate amount of salt. It sounds like you may have an error in your ORM code - like the field has been set to expect one thing and receiving something else.

  • @othmanethebold9004
    @othmanethebold9004 2 года назад +83

    For anyone who is facing the error of 'outside application context', try this :
    - in your terminal: from import app, db
    - with app.app_context():
    db.create_all()
    Note: You can use this also when you will want to add data to the database. GoodLuck!

    • @mikevogt71
      @mikevogt71 2 года назад

      Oh wow! You saved me! I have been stuck for days with this error and was ready to throw out the entire tutorial.
      I owe you a beer! Thanks VERY MUCH!

    • @mikevogt71
      @mikevogt71 2 года назад +1

      Well - while this gets me beyond the immediate 'application context' error, it takes me off the path shown in Corey's video.
      I am planning on abandoning this series in favor of a more up to date offering.
      Thank you for your insight.

    • @othmanethebold9004
      @othmanethebold9004 2 года назад +6

      @@mikevogt71 These bugs really blow one's mind lol but they should never be a roadblock, just keep trying, you will learn alot!

    • @aliyanpops6424
      @aliyanpops6424 Год назад +2

      Thnks for killing the fustration

    • @sarahcruz7352
      @sarahcruz7352 Год назад +1

      Thank you for posting this

  • @meenamotiramani5244
    @meenamotiramani5244 4 года назад +97

    Behind the smooth voice is tons of debugging and eternities of reading the docs

    • @brawlmania7544
      @brawlmania7544 3 года назад +4

      Most of which is trying to find the 1 damnable parenthesis or quotes

  • @soumyajitdey5720
    @soumyajitdey5720 4 года назад +419

    Corey Schafer is teaching us things which we did not learn in universities. I promise I will support you through Patreon once I land a job.

    • @coreyms
      @coreyms  4 года назад +65

      Thanks! Glad you found the videos helpful!

    • @hananjamal2431
      @hananjamal2431 3 года назад +3

      I will too

    • @Akshay-cj3hq
      @Akshay-cj3hq 3 года назад +27

      Did you land a job yet?

    • @MichaelTheSaffa
      @MichaelTheSaffa 2 года назад +3

      my uni is teaching me this

    • @pascalowilly2653
      @pascalowilly2653 2 года назад +2

      @@coreyms I will support you too, this is the work of a legend

  • @CainanParker
    @CainanParker 5 лет назад +144

    17:04 made me so happy when you noticed that and fixed it. I had a solid 10 minutes of anxiety.

    • @zainbaloch5541
      @zainbaloch5541 5 лет назад +2

      yeah, I was waiting for him to realize it, though I did it right in the first place ;)

    • @a69e87
      @a69e87 4 года назад +2

      lol

  • @padraic1983
    @padraic1983 3 года назад +20

    Hey Corey, you literally helped me Land a dream job . Thank you for all you've contributed.

  • @giuseppetemisio1158
    @giuseppetemisio1158 6 лет назад +248

    In my university I'm attending a course of Information System in which the professor is using exactly your code in the labs lessons without mentioning you. I found you by looking for help on youtube.

    • @andreasmiles6066
      @andreasmiles6066 6 лет назад +4

      Hey GT, do yo mind me asking which uni do you study at and which course? Thanks.

    • @sagarthakore
      @sagarthakore 5 лет назад +3

      @@X............................. Your display picture made me scratch my monitor screen! Felt like a fool when I realized it was just your picture. This is pure evil genius!

    • @rancoxu
      @rancoxu 5 лет назад

      University of Queensland?

    • @rulo1894
      @rulo1894 5 лет назад

      If I am right you study at Università degli Studi di Napoli Federico II jajaja. Also love the number of likes in your comment!

    • @irishRocker1
      @irishRocker1 5 лет назад +6

      ​@@matthewbotti That is a pretty naive view of things. I have learned lots from youtube and google in general but i still would not trade in my college education. There are things college cant teach you or give real world experience in but it does set you up well for "learning how to learn" and developing your career. It helps create the foundation that you will build upon for the rest of your career. Just learning from youtube will teach you some things but it doesn't quite give you the solid foundation that college will or as good an understanding. I studied electronic engineering (which includes programming) and I read some hobbyist forums sometimes where people have learned stuff themselves but they also lack some pretty important knowledge and understanding. It usually takes the handful of talented guys on those forums to bring up the level of everyone else who still have to ask simple questions or to correct some opinions that are not accurate etc. Same for places like stack overflow. people asking basic questions because they learned something online but they hit one bump on the road and don't have the background/understanding to figure it out themselves and have to go ask online and wait for someone else to solve it for them. And for the record, in Europe we pay far less for college education than say the USA. €1500 a year is what i paid and had no debt after it.

  • @fouroakfarm
    @fouroakfarm 6 лет назад +33

    As someone who wrote PHP 20 years ago, damn do I wish this existed then haha This is awesome. Thanks for your incredibly clear and concise videos

  • @kanishkasah4383
    @kanishkasah4383 8 месяцев назад +1

    23:44 "user = User.query.get(1)" while running this query ...
    :1: LegacyAPIWarning: The Query.get() method is considered legacy as of the 1.x series of SQLAlchemy and becomes a legacy construct in 2.0. The method is now available as Session.get() (deprecated since: 2.0)
    The warning you're seeing is indicating that the Query.get() method is considered legacy in SQLAlchemy and will be deprecated in version 2.0. Instead, it suggests using the Session.get() method.
    solution-
    "user = db.session.get(User, 1)"

  • @stormerthe2nd
    @stormerthe2nd 5 лет назад +114

    While True:
    Print("Thank You So Much")

    • @BurgerBurglar8964
      @BurgerBurglar8964 4 года назад +16

      Do keep in mind that Python is case sensitive!

    • @riddhiman2926
      @riddhiman2926 4 года назад +36

      Traceback (most recent call last):
      File "", line 1, in
      NameError: name 'Print' is not defined

    • @BurgerBurglar8964
      @BurgerBurglar8964 4 года назад +6

      Riddhiman 36 I'm pretty sure While isn't a keyword and this will fail on the first line

    • @sansovino4124
      @sansovino4124 4 года назад +13

      @@BurgerBurglar8964 'while' is a valid keyword.
      Should read:
      while True:
      print("Thank You So Much")
      God we're pedantic aren't we!

    • @liubohan7008
      @liubohan7008 4 года назад

      I think auto-correction is the culprit to blame here hhh

  • @TRasheed94
    @TRasheed94 3 года назад +1

    From watching your videos and reading these comments, I no longer regret not studying a computer science degree at university :)

  • @sirnakerb209
    @sirnakerb209 6 лет назад +137

    Your videos are really great! Every second of this video is understandable, that really takes talent! Keep it up!

    • @jartavia05
      @jartavia05 6 лет назад +4

      Im completely agree. Great Videos.

  • @Manuel-rl6um
    @Manuel-rl6um 5 лет назад +2

    If db.create_all() is not creating the file for you, check that you wrote URI and not URL in "app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'".
    Don't be me xD
    Following this tutorial in WLS2 but in my Windows 10's VS Code accessing Ubuntu remotely. Working perfectly so far.
    To set up VS Code of Windows 10 to work with your Ubuntu WLS, following this: code.visualstudio.com/remote-tutorials/wsl/getting-started
    Amazing tutorial so far!

  • @ArchAid1
    @ArchAid1 6 лет назад +42

    Dude, I am loving this series of videos, but MAN that was a challenging 29:57 minutes! Thank you thank you thank you for making this video

  • @tubalix
    @tubalix 4 года назад +2

    One of the clearest, most understandable and easy to follow instructional videos on the topic. Much much better than 99.9% (OK, I could have written 100%....) of what I have seen around.

  • @mahtoosacks
    @mahtoosacks 5 лет назад +6

    Ive been playing with laravel for several months, but after seeing how clean and simple flask is, I'm probably going to jump onto python. Thank you for this amazing reference

  • @brentelisens9163
    @brentelisens9163 5 лет назад +1

    the best flask tutorial series hands down. i don't even mind the ads and i've had monstrous urges to break screens over them.

    • @irishRocker1
      @irishRocker1 5 лет назад

      ah, reading comments like these makes me glad i subscribed for youtube premium lol adverts used to wreck my head!

    • @brentelisens9163
      @brentelisens9163 5 лет назад

      @@irishRocker1 it's free knowledge. his presentation is in depth and easy to follow. you paid for a free service because you didn't want to wait 5 whole seconds.

  • @ayomaluh452
    @ayomaluh452 2 года назад +2

    for anyone whose having an issue with db.create_all(), use the following commands after watching the next video.
    (env) C:.\..\..\flask app\Flask_blog>set FLASK_APP=run
    (env) C:.\..\..\flask app\Flask_blog>flask shell
    >>> from flaskblog import db
    >>> from flaskblog.models import User, Post
    >>>db.create_all()

  • @mckadesorensen2539
    @mckadesorensen2539 5 лет назад +31

    When I'm no longer a broke college student I'll be joining your Patreon!!

  • @roosterglobal2648
    @roosterglobal2648 5 лет назад +12

    Note: When using Postgres as Production DB, SQLAlchemy creates a table name 'user' from Class User. 'user' is a reserved table in postgres and is used for db admin users. Using pgAdmin I could not see that my table existed. My db worked but I couldn't see the table in pgAdmin sidebar. I could only see the reserved 'user' table. I had to use SELECT * FROM "user"; (double quotes) to get my data. I changed Class 'User' to 'Users' to avoid later confusion. Not sure if this is similar behavior in other dbs. Hope it saves someone a day of head scratching!

  • @drozdekPty
    @drozdekPty 5 лет назад +3

    Have been doing coding since 15 years, but this is one of the best videos have seen so far. Respect!

  • @treelight1707
    @treelight1707 6 лет назад +6

    This may be the best crash course on sqlalchemy. Love the series.

  • @kavabangaungava
    @kavabangaungava 6 лет назад +4

    Many thanks from Russia. Your educational videos are great.

  • @prkprime
    @prkprime 4 года назад

    this is the most detailed tutorial i have ever seen
    i'm watching every video in this tutorial

  • @tomasemilio
    @tomasemilio 5 лет назад +9

    bro. genius , love the way you teach.
    on vacation actually, pumped to learn here at a cafe in the middle of patagonia. keep it up

    • @coreyms
      @coreyms  5 лет назад +2

      Whoa, that sounds like an awesome vacation!

  • @chetna.gorawala
    @chetna.gorawala 2 года назад

    Couldn't find a better teacher and programmer> Amazing teaching techniques. Thank You Corey

  • @elecmn
    @elecmn 6 лет назад +6

    by the way Corey you are the best tutor ever on youtube

  • @EnesKab
    @EnesKab 5 лет назад +38

    If you are getting error while creating new user, you can try to change lazy="True" to lazy="dynamic"
    I had to spend 2 hours, before i figure it out.

    • @lipcioful
      @lipcioful 5 лет назад +3

      Omg, thanks for sharing that with us! It threw "sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize" and answers on the web were very confusing, this one did the job!

    • @ahmedjalal9518
      @ahmedjalal9518 4 года назад

      @@lipcioful man you saved me .You wasted 2hours but i waste 4hours solving this one. Thanks!

    • @r.h.5172
      @r.h.5172 4 года назад +1

      I changed lazy="True" to lazy="dynamic" still I am getting this error

    • @joellekamaha2600
      @joellekamaha2600 4 года назад +1

      Thanks for the tweak

    • @joellekamaha2600
      @joellekamaha2600 4 года назад +2

      @@r.h.5172 save the work and in the python shell import the tables again `from flaskblog import User, Post` before creating the user.

  • @mahyarazad
    @mahyarazad 4 года назад +1

    You are the best teacher ever I had. many thanks to you, I can now connect the dots and, understand how do these libraries work together. Respect.

  • @tradewinds9832
    @tradewinds9832 4 года назад +3

    OMG, this is one of the best tutorials that I have found on YT. I'll see what I can to help.

  • @mjj2u2
    @mjj2u2 2 года назад +1

    Exceptional video. Your examples are on point and flow very well. I find you explanations clear and very concise. They explain everything I need to know with out rambling. Any questions that came to my mind were answered in the video. (Get out of my mind you freaking mind reader! Ha ha) All technical videos should take a note from how this was made. Well done, and thank you. I'm sure a lot of hard work and forethought went into this.

  • @bhoomeendra
    @bhoomeendra 6 лет назад +4

    This is my first time with database and it is really simple because of you thanks again

  • @vishupal8982
    @vishupal8982 4 года назад +1

    It is the best video than my udemy courses I learn a lot form your video Thanks a lot sir continue your series..

  • @irmscher9
    @irmscher9 6 лет назад +4

    Wow, you are starting super fast in this video, I first though my video is set on 1.25 speed :). Thanks a lot for your tutorials by the way!

  • @ukuleleguy16cs36
    @ukuleleguy16cs36 4 года назад

    Good teacher... Your teaching style is amazing. Each and every line is clearer and to the point..

  • @clippysnips
    @clippysnips 3 года назад +7

    Hi Corey! First off, I want to say thank you for all of these comprehensive tutorials that you shared with us! I really appreciate all the work that you've done on your channel!
    With regards to my concern, I was wondering what steps I should take when converting from an SQLite database to a PostgreSQL one. Hope you could enlighten me on this one. Thank you again very much!

  • @Shubham16ify
    @Shubham16ify 2 года назад +1

    One very basic question..related to the python about this lecture...why we mostly use class attributes in python while accessing DB?
    Example why we didnt use self.username or self.id , etc here and used.
    Example:
    class User(db.Model):
    id=db.Column(db.Integer, primary_key=True)
    username=db.Column(db.String(20), unique=True, nullable=False)
    email=db.Column(db.String(120), unique=True, nullable=False)

  • @mu9344
    @mu9344 4 года назад +4

    Around 18:30, for those who are having module error or name error at terminal, please try to write python -m pip install flask_wtf or whatever.

    • @investandcyclecheap4890
      @investandcyclecheap4890 2 года назад

      thank you ! This saved me so much time !

    • @roodrums
      @roodrums 2 года назад

      if that doesn't work just use every different type of pip install e.g. python3-m pip install .... pip3 install ...... should work

    • @xxXNMEXxx
      @xxXNMEXxx Год назад

      thanks!!!

  • @programming_hut
    @programming_hut 4 года назад +1

    you are simple best and you provide high quality education for free ❤️❤️ thanks a lot 🙏

  • @meqsed-novruzov-92
    @meqsed-novruzov-92 5 лет назад +3

    I love this guy's tutorial series.

  • @jatin1688
    @jatin1688 3 года назад

    Amazing , superb and best video of flask python in whole internet , RUclips and all

  • @Rafiki041087
    @Rafiki041087 6 лет назад +4

    Really like the quality of these videos. Great tutorial.
    Took some time to wrap my head around the datetime.utcnow part and why it should be without the (), especially after creating post1 in the terminal and the datetime was Null. But after running the .add(post1) and the .commit() it all made sense.

    • @sonny8595
      @sonny8595 5 лет назад

      Could you explain it to us?

    • @silverzero9524
      @silverzero9524 4 года назад +2

      @@sonny8595 if u do datetime.utcnow() then the function will get executed and will return a DateTime
      and that returned value will be assigned as default
      we dont want that
      we want get current datetime everytime

  • @I_am_pradeep
    @I_am_pradeep 6 лет назад +2

    The quality of the content is so good. It's so understandable and useful.

  • @derrickakomeah
    @derrickakomeah 4 года назад +3

    Dude you are so talented and know how to commincate
    Your videos are the best thank you so much

  • @ibrahimoluwajobaadisa392
    @ibrahimoluwajobaadisa392 2 года назад

    Thank you Corey. You cover all that is necessary within reasonable time yet in details.

  • @marc-olivierblouin4709
    @marc-olivierblouin4709 6 лет назад +17

    Will you make a tutorial for switching SQLAlchemy database to production one?
    Thanks!!

  • @sachavanweeren9578
    @sachavanweeren9578 3 года назад +1

    Thanks for this great video. Tried to code along with the similar tutorial from Flask itself but that one is difficult to understand. Here you break it up in nice pieces and use much more intuitive coding. Thank you very much....

  • @dsdgaming2242
    @dsdgaming2242 6 лет назад +9

    Hello Corey, please include a tutorial for making a Many-to-Many relationship in Flask-SQLAlchemy. Thanks

  • @johnphilipangeles1825
    @johnphilipangeles1825 4 года назад +1

    Thanks Corey! Really helpful as I'm trying to finish up my first web app in Flask.

  • @mudassiraqeel8604
    @mudassiraqeel8604 2 года назад +7

    I'm getting this error, when I try to run db.create_all() in terminal:
    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.

    • @sanjayjain3139
      @sanjayjain3139 2 года назад

      i am stucked here from 2 days

    • @harshbhandari5549
      @harshbhandari5549 Год назад +6

      You have to manually set the context-
      >>> from project import app, db
      >>> app.app_context().push()
      >>> db.create_all()

    • @kenimprov
      @kenimprov 9 месяцев назад

      @handari5549 Why didn't Corey have to do this? Is it because of a difference in versions?
      Edit. seems like I needed to add
      db.init_app(app)
      after the line
      db=SQLAlchemy()

  • @pengtroll6247
    @pengtroll6247 4 года назад

    This was by far the best tutorial on integrating sqlalchemy with python! thanks man!!

  • @hrishikeshmahajan752
    @hrishikeshmahajan752 4 года назад +3

    If someone manages to mess up at 21:25 and now are getting an error do remember to close of the session before trying again using db.session.close().

    • @0xLoneWolf
      @0xLoneWolf 4 года назад

      Thank you for that. Idk what fixed my "SQLite objects created in a thread can only be used in that same thread." issue but this may have been it!

  • @muthukamalan.m6316
    @muthukamalan.m6316 4 года назад +1

    for those who have sqlalchemy has no column member error while working on vs code
    please do some changes in settings
    preference>settings>edit>setting.json>copy and paste the below code
    {
    "python.linting.pylintArgs": [
    "--load-plugins",
    "pylint-flask"
    ]
    }

    • @tlupion
      @tlupion 4 года назад

      It worked for me muthu, thanks a lot

  • @ykangho
    @ykangho 5 лет назад +3

    Thank you so much, your teaching is clear and easy to understand! It helps me a lot.

  • @ted9097
    @ted9097 4 года назад

    This is a step above a lot of videos in terms of DB set up. Nice work!

  • @44_Leaf_Clover
    @44_Leaf_Clover 5 лет назад +3

    Great series Corey, I'm recommending your channel to everyone I meet! To anyone getting an error:
    sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects.sqllite when running $ db.create_all() - I solved this by pip installing an earlier version of SQLAlchemy (1.2.7) [my previous version was 1.2.16] and this solved the problem. Thought it might help someone.

    • @Brogun420
      @Brogun420 4 года назад

      you did sqllite not sqlite in app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' (i did the same thing :-/)

  • @maximeyahou
    @maximeyahou 5 лет назад +1

    For those who have an error like "has no 'Column' member" or "'db is not defined", just add in settings.json this line and save:
    "python.linting.pylintArgs": ["--load-plugins", "pylint-flask"]
    I am running it on VS code on a mac.

  • @heisenburgfreed7591
    @heisenburgfreed7591 4 года назад +13

    The command to install Flask-SQLAlchemy in the video is out of date now, please use below instead:
    pip install -U Flask-SQLAlchemy

    • @keshavbansal5148
      @keshavbansal5148 3 года назад +1

      Both the commands work just fine.

    • @PythonDevelopment
      @PythonDevelopment 3 года назад

      @@keshavbansal5148 no, first command don't working more

    • @ase713
      @ase713 3 года назад

      @@PythonDevelopment if you follow the requirements file, you will find that it does work fine'

  • @sebastianskopek
    @sebastianskopek 4 года назад +1

    am i the only one who watches a 30min video in over an hour (coding included) ? :)

  • @AdityaFingerstyle
    @AdityaFingerstyle 5 лет назад +3

    To make that sqlalchemy warning disappear add this
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

  • @monishagowda8928
    @monishagowda8928 6 лет назад +2

    Thank you sooo much for the tutorials!! It helped me big time for my project. You teach way better than my teachers.

    • @prashantjeena4629
      @prashantjeena4629 5 лет назад

      what project did you make ?....i'm a beginner and need to make a project ..can you please guide me a little?

  • @janmurin6834
    @janmurin6834 3 года назад +1

    Best flask tutorial i have seen. helped me start my own projects. I Have a question however, if you can show how to do many to many relationship that would be helpfull.

  • @davidboatengadams301
    @davidboatengadams301 5 лет назад +8

    i get errors with this line of code, db.Column(db.String(60), nullable=False)
    it says " Instance of 'SQLAlchemy' has no 'Column' member"

    • @lieuich6184
      @lieuich6184 5 лет назад +6

      i got the same problem as you so this is what I did, hopefully, it will work for you
      1.pip install pylint-flask
      2Load the installed plugin.
      For example, if you use VS code, please edit setting.json file as follows: (opened with the File > Preferences > Settings command ⌘, search for settings.json and one of the options will let you edit it)
      add this line
      "python.linting.pylintArgs": ["--load-plugins", "pylint_flask"]

    • @Jay-pm6vk
      @Jay-pm6vk 4 года назад

      @@lieuich6184 Thank you very much!

    • @MarcusReaiche
      @MarcusReaiche 4 года назад +1

      Hello,
      I just wanna add some remarks. I had the same problem, but for me the solution was to install the pylint_flask_sqlalchemy additionally to the pylint_flask plugin. This post (pypi.org/project/pylint-flask-sqlalchemy/) shows all the steps including the load of the plugin through the command line.
      For someone that uses VSCode, it is worth pointing that one should add the following lines to the .pylintrc file:
      load-plugins=pylint_flask,pylint_flask_sqlalchemy
      Hope that this can be useful for somebody!

    • @goldymazumdar9741
      @goldymazumdar9741 4 года назад +1

      How to resolve this problem in Pycharm ??

    • @25kirtan
      @25kirtan 4 года назад

      @@lieuich6184 Hey this doesn't seem to help. Any other fixes?

  • @Kotik112
    @Kotik112 Год назад +1

    User.query.get(1) is considered a legacy method as of SQLAlchemy 1.x. The new syntax to get by ID is db.session.get(1).

  • @luke2306
    @luke2306 Год назад +1

    This video really helped me a lot, everything is clear now tysm Corey !

  • @bartox-tt4pg
    @bartox-tt4pg 5 лет назад

    In my opinion Peewee is more clear and understandable, but SQLA is nice too. Thanks for all of yours tuts

  • @techcode_man
    @techcode_man 2 года назад

    I keep coming back to Corey's videos for years. No one teaches like him. But he doesn't post new videos anymore. Sad!!

  • @paulcal3500
    @paulcal3500 2 года назад +3

    I am getting an error when I try to db.create_all(). The error is: "RuntimeError: Working outside of application context". This even happens when I try to run the source code. Any idea why?

    • @weedwackerfannypacker
      @weedwackerfannypacker 2 года назад

      i have been stuck on this for a while too did you figure it out?

    • @paulcal3500
      @paulcal3500 2 года назад

      @@weedwackerfannypacker Nope. Don't understand any of the explanations online. You?

  • @pururaj6566
    @pururaj6566 4 года назад

    A universities never teach us these you are greate.

  • @takundamafuta7355
    @takundamafuta7355 4 года назад +3

    I'm stuck on 17:30, I'm using Pycharm and I don't know how to create the database like you did. Please help.

    • @himanshusingh3219
      @himanshusingh3219 4 года назад

      @Squishy Chilli im also using pycharm and getting some error while using terminal

  • @rodhash
    @rodhash 3 года назад

    Sir you have sick teaching skills, omg .. I'll definetly become a patreon

  • @parvazprint1009
    @parvazprint1009 5 лет назад +4

    hey there hows it going everybody

  • @ihebhaboubi1570
    @ihebhaboubi1570 5 лет назад +1

    Thank you so much Corey , Your Videos have taught me a lot about python and Web development, You are amazing!

  • @pranshuagrawal8046
    @pranshuagrawal8046 4 года назад +4

    Sir its showing error when I am trying to import User, Post from flaskblog, saying : ImportError: cannot import name 'User' from 'flaskblog'

    • @SandipPoddar
      @SandipPoddar 4 года назад

      Check spelling of User or your main file name

  • @glensworld66
    @glensworld66 6 лет назад +1

    Love this series (and have watched several of your others, including the learning python series). Thanks! Wish you would have discussed indexes and when and how you use them. Thanks again!

  • @Prelude2ADream
    @Prelude2ADream 6 лет назад +5

    If you use the filter_by function with say username='Corey' and you had users with usernames Corey and say CoreyS, would it pick up both of them or only the exact match Corey? Thanks for a great video!

    • @shakiestnerd
      @shakiestnerd 5 лет назад +5

      filter_by() is going to return an exact match. If there are more than one username='Corey', User.query.filter_by(username='Corey').all() would return all of them.
      On the other hand, if you wanted all of the variants, you could use something like User.query.filter(User.username.like == '%Corey%')).all(). This would return a list of all the username that contained the string 'Corey'.
      Love the question --- you made my look up the answer!

  • @guntarget
    @guntarget 4 года назад +6

    There appears to be a recent update to werkzeug that prevents the command from flaskblog import db from working (ruclips.net/video/cYWiDiIUxQc/видео.htmlm46s).
    pip install werkzeug==0.16.0 seems to fix it.
    see github.com/scoringengine/scoringengine/issues/670

    • @gideonyektai3414
      @gideonyektai3414 4 года назад

      Yes! Thank you for the solution this is exactly what I was searching for. Is this a problem from the first pip installs not covering this, or was something changed in an update?

  • @samiam.402
    @samiam.402 2 года назад +1

    I might have been the only one confused by this. But if you create a post object in memory, and haven't done the "db.session.commit()" yet, you will see "None" for the id and the datetime, because the database does that work. It's obvious to me now, but if anyone is confused why they are getting "None" for any of the values, just make sure you've committed your changes first.

  • @forithall2417
    @forithall2417 6 лет назад +3

    I can't use db.Column, in the "class User(db.Model)" it says >>>>>>>> [pylint] E1101:Instance of 'SQLAlchemy' has no 'Column' member
    HELP!!!!!!!!!!!

  • @untildawn5714
    @untildawn5714 6 лет назад +1

    Hi @Corey! Thank for the series I had some headache until I found your videos to resolve my little issues :D Thanks !

  • @antongirdeux4148
    @antongirdeux4148 6 лет назад +7

    Hey, Corey
    I got this error:
    [pylint] E1101:Instance of 'SQLAlchemy' has no 'Column' member
    How do I fix it?
    Thank you.

    • @johnathaningle8855
      @johnathaningle8855 5 лет назад +2

      Its an error within the python linter. If you are using VScode (like me) it shows an error in the editor but runs correctly

    • @joerothstein8101
      @joerothstein8101 5 лет назад

      @@johnathaningle8855 I'm also running VSCode, and see the same error.

    • @esaadlb
      @esaadlb 5 лет назад +2

      pip install flake8

    • @azizbohra6666
      @azizbohra6666 4 года назад

      @@johnathaningle8855 Disable Linter (pylint)

    • @azizbohra6666
      @azizbohra6666 4 года назад

      @@ElmerGLue Disable the Linter (pylint)

  • @gunnarpope
    @gunnarpope 5 лет назад +1

    Dude, your videos are so good! Very high quality and helpful. Thanks!

  • @puravida77700
    @puravida77700 6 лет назад +3

    Wonderful tutorial, thanks alot!
    Everything went fine until 19:55. when typing in the user_1=... in the terminal I get following error:
    "sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|User|user'. Original exception was: Could not determine join condition between parent/child tables on relationship User.posts - there are no foreign keys linking these tables. Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression."
    Also when typing in db.create_all() following error occurs:
    "sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'post.user_id' could not find table 'user_id' with which to generate a foreign key to target column 'None'"
    I have copied the code straight from Corey github just to be sure... Any idea as to why this is happening?

    • @scarmusic90
      @scarmusic90 5 лет назад

      flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/ - this helped me out. make a quests user and then create the user_1 - mine worked all of a sudden.

    • @WanhedaPY
      @WanhedaPY 4 года назад +1

      1 year after lol but yeah I got this too, fixed it when I put my Posts class above my User class. Also the second thing about can’t find user_id table, the foreign key is “user.id” not “user_id”

  • @victornikolov537
    @victornikolov537 6 лет назад

    'id' is coloured in orange. I think it's a keyword or method/function name. Great tutorial. SQLAlchemy is not so scary anymore. I will look at it.

    • @coreyms
      @coreyms  6 лет назад

      You’re right. I should probably change that. Thanks for pointing that out!

  • @tusharguliany3633
    @tusharguliany3633 6 лет назад +5

    Error :
    sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|User|user'. Original exception was: When initializing mapper Mapper|User|user, expression 'Post' failed to locate a name ("name 'Post' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.
    All that I did different was to change blogpost.py to app.py
    Can You Please Help ?

    • @inztomoe2530
      @inztomoe2530 6 лет назад

      i had the same problem. turned out i misspeling word 'ForeignKey'. after i corected it, i reopen project and it start working.

    • @reggiemate7288
      @reggiemate7288 6 лет назад +3

      It is probably too late, but I ran into the same error. I had a couple of spelling errors. However as you edit you will get the same errors over and over again. You may have also entered the python commands in wrong into the terminal. Best option is create a new instance of the terminal. Then re enter all the commands. THis worked for me.
      from flaskblog import db
      db.create_all()
      from flaskblog import User, Post
      user_1 = User(username='Test', email='t@t.com', password='p')
      db.session.add(user_1)

    • @saidkarimsaidmahmudov3048
      @saidkarimsaidmahmudov3048 6 лет назад

      sqlalchemy.exc.InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlite3.IntegrityError) UNIQUE constraint failed: user.email [SQL: 'INSERT INTO user (username, email, image_file, password) VALUES (?, ?, ?, ?)'] [parameters: ('Corey', 'C@demo.com', 'default.jpg', 'password')] (Background on this error at: sqlalche.me/e/gkpj)

    • @stephenosei-bonsu625
      @stephenosei-bonsu625 6 лет назад +1

      I also had this problem. it got me stuck a whole day

    • @vijaysinghrajput8526
      @vijaysinghrajput8526 6 лет назад

      FOR THOSE...WHOSE SQLALCHEMY IS NOT WORKING....USE MOGODB AND PYTHON MODULE [FLASK-PYMONGO]

  • @sebastianmarrera1822
    @sebastianmarrera1822 2 года назад +1

    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.
    I got this with the db.session.add()
    Before that, i added the:
    ```
    with app.app_context():
    db.create_all()
    ```

    • @sebastianmarrera1822
      @sebastianmarrera1822 2 года назад

      Still got it

    • @ryperson269
      @ryperson269 2 года назад

      im still a bit confused on this, where did you add the
      ```
      with app.app_context():
      db.create_all()
      ```
      ???

    • @sebastianmarrera1822
      @sebastianmarrera1822 2 года назад

      @@ryperson269 i finished it, thanks

    • @harshbhandari5549
      @harshbhandari5549 Год назад +2

      @@ryperson269
      Run below in python shell , this will manually set the context.
      >>> from project import app, db
      >>> app.app_context().push()
      >>> db.create_all()

    • @ayo4590
      @ayo4590 Год назад

      ​@@harshbhandari5549 Thank you very much, I was stuck on this for 2 days.For anyone else that needs help just do exactly what ​ @harshbhandari5549 said in the python shell in the terminal. 'project' is whatever you named the python file with all the app routes and stuff. for me it is flaskblog

  • @ahmedyousif4782
    @ahmedyousif4782 3 года назад +5

    fun fact: you are in the comment section because db.create_all() didn't work

  • @charles7483
    @charles7483 4 года назад

    I will support you as well after I get the job!

  • @lucianpirjol8526
    @lucianpirjol8526 3 года назад +3

    Hello, can anyone help me with this error? :
    Traceback (most recent call last):
    File "C:/Users/lucia/PycharmProjects/Flask_blog/flaskblog.py", line 13, in
    class User(db.Model):
    File "C:/Users/lucia/PycharmProjects/Flask_blog/flaskblog.py", line 14, in User
    id = db.Column(db.Integer, primary_key=True)
    TypeError: Column() got an unexpected keyword argument 'primary_key'
    Process finished with exit code 1
    Thank you !

    • @aashayshah1120
      @aashayshah1120 3 года назад

      Save your files, close your command prompt and restart it. It worked for me !

  • @christinagorbenko6811
    @christinagorbenko6811 2 года назад

    I wish uni taught us all of this. Such a great course and instead I cam out of college only knowing theory lol

  • @epic_waffle2359
    @epic_waffle2359 4 года назад

    YOU DESERVE 1 MILLION SUBS!

  • @christoph3333
    @christoph3333 6 лет назад

    Amazing tutorial. Everything is explained clearly and easy to follow.

  • @IbrahimKhan-nd1wq
    @IbrahimKhan-nd1wq 2 года назад +1

    Can you please give credit to Miguel Grinberg?..although loved your explanation.

  • @PaulSmith-zs5je
    @PaulSmith-zs5je 6 лет назад +1

    Thanks Corey. After creating my database and committing the session data I was unable to query without getting thread errors. I found I had to add the following change my db config to site.db?check_same_thread=False im running on windows

  • @csbnikhil
    @csbnikhil 4 года назад

    Just something on the design of SQLAlchemy: a foreign key column could infer the column type from the referenced table, so that we could avoid mentioning the type ourselves. Could be a dumb thought. Now I wonder why it is not the case with databases in general.

  • @xtrzne
    @xtrzne 3 года назад +1

    Where can I find documentation for the ORM code? How to use data validation rules within the python classes etc? Thanks so much for this series!

  • @seattletcp1
    @seattletcp1 3 года назад +1

    Are you doing any new series in the future? Quite missing those high quality videos

  • @xl0xl0xl0
    @xl0xl0xl0 Год назад

    Would love to see an update version of this series. Or maybe FastAPI instead of Flask? I think the two are pretty similar.

  • @novicetech1
    @novicetech1 10 месяцев назад

    I officially give up on this one. I learned quite a bit, but Flask has apparently changed quite a bit since this tutorial was made and, as a result, I'm not sure this is an accurate learning guide at this point. I love Corey's style and content, but this one probably needs to be updated.

  • @anastasiaklimenko1745
    @anastasiaklimenko1745 Год назад +1

    hey all!
    as long as "The relationship.backref keyword should be considered legacy, and use of
    relationship.back_populates with explicit relationship() constructs should be preferred. "
    that's what I changed in models:
    class User(db.Model):
    # changed posts line:
    posts = db.relationship('Post', back_populates='author')
    class Post(db.Model):
    # added line
    author = db.relationship('User', back_populates='posts')
    to see in Terminal those relationship attributes:
    app.app_context().push()
    u = User.query.filter_by(id=1).first()
    u.posts
    all_posts = Post.query.all()
    all_posts[0].author