Watching your tutorials is not just learning. It's more like a thrilling experience. I've never met a person with an ability to explain such complicated things in such a logical and comprehensive way. You're exceptional...
CobraL0rd as far as i know, companies are still looking for Django devs rather than flask ones, at least in Poland. Personally i prefer flask as well but it is still nice to learn both imo
I do see it indeed. But I meant the market keeps being more Django oriented, at least here. That's why you should learn both theese particular frameworks(not just cause the more whatever language you know the better). I'm also curious where "Flask is replacing Django"? Is it worldwide or just in your country?
This is just life saving. I have been struggling with circular imports on flask for the entire weekend. Funny fact, almost no one is talking about this, and surely no one is doing so as thoroughly and crystal clear as you do. Thanks so much Corey. Finally was able to get this solved. Time to build models!
I don't know how many times I said to myself "Ahaa, never fully understood this before" while watching your Python videos. Even after a year or so dealing with Python, I always come back to some of the videos and extract something new and valuable.
6 years later, and still the best explanation of circular imports I've ever seen. Thank you for your work Corey. It is much appreciated even after all these years.
This video is a fair justification of knowledge never dies. I have been searching for this in a lot of documentations and all, but the explaination and justification in this video is so on point. Thanks a lot Corey. You are amazing
That's right, I read from Miguels solution about this; it was horrifically involved, complex and didn't break it down at the right level. Your description and show and tell is absolutely fantastic, a breath of fresh air and no doubt helped the 100k people that have watched this. Thanks so much!
This video helped me so much. As a university student who knew only java, working in python and browsing github was confusing. I did not know how to read code and how the project was structured. This video made it all clear. Thanks Corey!
5:00 Superb explanation! Couldn't understand it better from anyone else. A completely mind-boggling scenario made extremely simple. Corey you are just fantastic!
I absolutely LOVE this series. These are the kind of tutorials that I have always wanted, and now I have found them. Well done, Corey. You are awesome!
Some amazed Russian student here Your lessons are so cool, nobody in my university can explain something so clear... I'm going to watch all of your tutorials. Thank you so much!
@@slavchina_reviews радуйся, у нас из адекватно преподаваемых языков был только паскаль на первом курсе, а уже третий c: Все остальные языки самостоятельно разбирать приходится для всяких учебных проектов, заданий и т.д. Так что сильно не надейся на универ и самостоятельно учи то, что тебе интересно и нужно.
Спасибо за совет! Да в своём универе я конечно разочаровался, но хорошо что есть тонна возможностей для самообразования, тем более если хорошо понимаешь английский.
if you're using vscode and you're unable to move the import statements below the top of the file, its because of a linter automatically reformatting your code. Uninstall or modify your python linter extension you have installed to continue with the tutorial. Thank you Corey, this is the guide I needed
you are unbelievable. This video showed me that I have learnt almost nothing about flask , and even python until watching these series of yours. You didn't only structure the app, you also restructured my python knowledge with a higher level. Thanks
This person here "explains" stuff. I'm just starting out with Flask and I think the videos are concise enough to not bore the pros and yet they're in simple enough terms so as not to scare the noobs like me away.... Just Great.
Hey Corey, I just wanted to say thank you for putting together such comprehensive tutorials for free. I had been slamming my head against the keyboard trying to build an app with Flask and not having a solid understanding of package structure. All of your videos have been exceptional, but I wanted to highlight that it was very difficult to find resources around package structure that made sense. I have been using your tutorials to prepare for a pair-programming interview involving Flask, and this series has made me feel so much better about the whole process. Thanks for all you do; now to get this job!
man the feeling I had just after understanding the circular issue and why it is happening on User import and not on db import is something awesome. For those who found it hard to understand, I really advise you to go through the video as many times as you need(I watched it 3 times ) , it is really worth the effort. Bear in mind that when python calls the script directly that script's name is not flaskblog anymore, it is __main__. That's where you start to grasp it. Corey M Schafer you are great !
@@harshupreti1526 don’t think I could be clearer that Schafer’s explanation ! all you need to do ( or those who did not find it straight forward) is to repeat the video as many times as you need!
as a beginner, I find it way more friendly to keep everything in the same file. :) so this was a real headache actually. Forgot to add that your tutorials are great! learning alot.
Thank you thank you thank you! This is pure gold!! I had made an app just in one file. Really chaotic, but it worked. It seemed like such an enormous effort to restructure everything, but with your video I did in in under an hour. Thanks!
Thank you for this great tutorial. I've been following your tutorial series and it's a complete gold mine! I watched countless tutorials where they take shortcuts by not showing the proper way to implement things. For example, most tutorials don't show how to organize their Python projects because the instructors would rather skip explaining circular dependency and just put all the code in a single main Python file instead of breaking them up. They are not solving the problem but merely getting around it for the sake of producing tutorials. But in this tutorial, you covered everything from the ground up and it is truly eye-opening. Thank you so much from the bottom of my heart.
Thanks, Corey. LOVE your Python videos. I would love to see another full-scale real world application with Python and MySQL / PostGreSQL. Python and MySQL / PostGreSQL are some of the most in-demand skills from employers I have been seeing lately.
I'd love to see this lesson structured like this from the beginning. Maybe just a bare-bones website, nothing fancy. I wish there was something as simple as a template you could just git clone to get you into a package structure with common modules already set up and ready to go with basic functionality. I set up my own website with your help and am trying to customize it and skip unneeded features from these lessons as I follow along, but the amount of drift my project has taken from the start of this series is almost too much to follow along on this one. Too many moving parts. Thank you for everything you do, it's made a huge difference in my life.
This particular module of the flask course is really awesome.. I revisited this video again to solve a problem with packaging and module structuring. Now I am sure that I can make a better project module structure 🙂 Thanks a lot to Corey.. your videos are crisp with great content!
Thank you for this part of the tutorial. I've been struggling with project structure for some time now, wrapping my head around circular imports, and this made things much clearer.
I have just subscribed dude and I wish I could do more, you are just a life savior, you deserve way more subscribers , you are dedicated and you aren't holding any important information back, may god bless you those Tutorials are priceless.
Corey - AWESOME video! This saved my bacon, I have a huge project and was really struggling with restructuring after switching from Mongo to Postgres (don't ask). Thanks so much for taking your time to put this together.
Great lecture Corey! Just for the information, you don't need to create directory flaskblog. You can easily get rid of circular imports by doing following (Please correct me if anything goes wrong): in models.py from flask_sqlalchemy import SQLAlchemy from datetime import datetime db = SQLAlchemy() in flaskblog.py from flask import Flask, render_template, url_for, flash, redirect from forms import RegistrationForm, LoginForm from models import * URL = "server://username:password@localhost:port/name_of_database" app = Flask(__name__) app.config['SECRET_KEY'] = your_key_here app.config["SQLALCHEMY_DATABASE_URI"] = URL app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) # This is the step that will create the magic now you don't have to say db = SQLAlchemy(app) Anyway you are great!
Markdown summary/timestamps of this video: - [0:05](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - intro, reasons why structuring as package. How to convert a modular structure to package. - [0:45](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - creates models.py file - copies User & Post classes to new file. - `from flaskblog import db` # imports db - `from datetime import datetime` # imports datetime - `from models import User, Post` # within flaskblog.py module (later named run.py), imports the db classes - [2:17](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - attempts to run flaskblog.py. - Error message saying `cannot import name 'User'. - This is a circular import. - When something is imported from a module, the entire module is still run - not just the section being imported. - There are 2 errors here. - TBH I can't really understand the logic of error #1. - It's not super important to understand why, but the answer is package restructuring. - Basically the cause/solution for error #2 is: 1. in flaskblog.py/run.py: `from models import User, Post` (referring to the models.py file) 2. in models.py: `from flaskblog import db` 3. db hasn't yet been imported in flaskblog/run.py file as the line is below the import command in #1. 4. Solution to this, is moving the models User/Post import to below the `db = SQLAlchemy(app)` line. - [9:50](th-cam.com/video/44PvX0Yv368/w-d-xo.html) The answer to error #1 is: 1. Create a new folder in project folder with same name as application. 'flaskblog' in this case. 2. Create a new file in the application/flaskblog folder called `__init__.py` 3. Move forms.py, models.py, static + template folders into the application folder. 4. Edit __init__.py. This is where we initialise the package. 1. Move all the imports (at the top of the page - not the models import) from the flaskblog.py 2. Move also the app, app.config and db initialisation lines. 5. [11:24](th-cam.com/video/44PvX0Yv368/w-d-xo.html) Create routes.py file in package folder 1. Paste all the routes + dummy data into this file - everything left but `if __name__ == '__main__'` line 6. Rename the flaskblog.py to run.py as it's only purpose now is to run the application. 7. [12:38](th-cam.com/video/44PvX0Yv368/w-d-xo.html) Import the app into the run.py file, so the `app.run` command works by adding `from flaskblog import app`, this will import from the __init__.py file. *The app variable MUST exist within the _init__.py file.* 8. **Routes.py** clean up time: 1. Get the imports sorted for routes. Move the `from flask import redirect, url_for, render_template, flash` to routes.py, make sure you leave the `from flask import Flask` line in the init file. 2. Move the forms import to routes.py, you'll need to use package names as well, so `from flaksblog` becomes `from flaskblog.models` - `from flaskblog.forms import LoginForm, RegistrationForm` 3. You'll also need to import the app, as you have lines `app.routes`: `from flaskblog import app` 4. Import the routes into the init file, make sure the line goes below the app variable to avoid circular importing problems: `from flaskblog import routes` 9. [15:47](th-cam.com/video/44PvX0Yv368/w-d-xo.html) **Forms.py** clean up not needed as we're only importing pip installed packages. 10. [15:56](th-cam.com/video/44PvX0Yv368/w-d-xo.html) **Models.py** clean up: 1. Change the `from __main__ import db` to `from flaskblog import db` 11. [17:38](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - runs application 12. [18:21](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - creates database again 1. `from flaskblog import db` 2. `from flaskblog.models import User, Post` 3. `db.create_all()` 13. [19:28](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - Checks the site.db location - it's in the package folder, as the address is relative. 14. [16:30](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - Tree structure and overview of package: ``` ├── flaskblog/ │ ├── __init__.py │ ├── forms.py │ ├── models.py │ ├── routes.py │ ├── static/ │ | └── main.css │ ├── templates/ │ └── about.html │ └── home.html │ └── layout.html │ └── login.html │ └── register.html ├── run.py ```
Thanks a lot!! Really appreciate how you go into the depth of topics like you explained the import error. I think these things are difficult to learn as a beginner.
In addition to helping to understand flask structure (and why everyone uses a run.py entry point into a python package), I was surprised to learn that you can import a variable, in this case "app" which contains the application created in __init__. I guess I had assumed you could import a module, a class, and even a function, and that all made sense to me--sort of like "including" code from some other file. Now I understand you can also import an object which isn't code itself (in the source-code sense) but is rather a thing created by code, again in this case "app." That really helps clear up a lot of confusion.
Hi Corey! Thank you for sharing your knowledge! I really much appreciate your efforts. Breaking down the structure of the project into a package is a very good idea but your approach with putting import statement at the bottom of the __init__.py file not only breaks pep8 standard but also does not solve the 'ugly import' in flaskblog.py problem that you wanted to avoid by creating a package initially. Have you considered moving the 'from flaskblog import routes' statement into the top of the run.py file? This seems to solve all of the issues. Cheers!
Hi, just check this post on stack overflow. Your linter seems to be the problem. stackoverflow.com/questions/42649800/moving-views-to-a-separate-file-without-violating-pep-8
@@alexanderhoffmann4930 Sorry but I won't agree with that putting Import statement anywhere else than in the beggining of the file is not confusing for a human reader.
I agree that it does not technically violate PEP8 standards but I feel that the import at the beginning makes it that much less confusing,especially for beginners. P.S: Both work perfectly fine
Your solution works for me, initially i was having exceptions "jinja2.exceptions.TemplateNotFound: home.html" when import routes in __init__.py. After moving import routes to run.py.. smooth running. not sure what happened. Cheers and Thanks a lot.
@@avitinformatics8221 let me explain why this works, when you do 'from flaskblog import routes', it will first run the module's __init__.py, so it already get app, then it will run routes.py, when it comes the line 'from flaskblog import app', since it already run the init of flaskblog, it won't re-run the __init__.py, and just watch for the app, and it's actually found, so there is no circular import.
Correct me if I am wrong. I haven't achieved to blueprint video yet. But, via this package structure, in deed we are preparing re-usable flask apps like it is in Django. Only thing we will do to use an app in another flask platform, is to copy app folder and register it in run.py via flask blueprint capabilities. Amazing, I think if people knew this strategy, Flask would be much more popular than Django.
Thank you for this. I was having a doozy of a time with circular import issues. I knew what was going on, but couldn't figure out what to do about it exactly.
What a confusing error ! and how you are explaining it so fast? dude, you explain in a way that I thought you had made the Flask your own! Good job but I still need to play this video for several times to get whats going on. LoL
PRO TIP: Do NOT use dashes "-" for naming your packages. For example, I used "flask-blog" instead of "flask_blog". I got a SyntaxError when I ran "run.py". There is a reason Python does not like dashes, and only likes underscores when naming your packages :)
Corey, I have watched a number of your TH-cam videos and I think you do a great job. Most other videos on TH-cam take a long time to get to the point, over explain simple issues or take for granted more complex knowledge. Sometimes all three in one video !!! You get to the point and explain things once (leaving me to rewind if I don't understand), which is perfect and makes your channel my 1st port of call. Thank you. I am using PyCharm and it’s “new project” command sets up a project with an environment (venv subdirectory). Pycharm will make a package directory (complete with __inint__.py, do I move the venv directory into the package directory as well as static, templates etc ?
I wondered why Corey needed the import of routes in __init__.py, since we don't use the name "routes". I see other people wondered the same thing. As Corey notes at 2:57, importing a module doesn't just bring in the names -- it also runs the code in the module. The routes.py code defines the route functions and registers them with the app (with the help of some decorators). If we don't import routes somewhere, then that code never gets run. The import in __init__.py is just there to run that routes code.
When I tried to use db.create_all() command.. 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.
have the same problem. i used "from flaskblog import app, db with app.app_context(): db.create_all()' It created the site. db file in my anaconda folder, in a folder called var/flaskblog-instance. i am unable to query the db file. it gives me this error: 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.
Watching your tutorials is not just learning. It's more like a thrilling experience. I've never met a person with an ability to explain such complicated things in such a logical and comprehensive way. You're exceptional...
Thanks!
Thank You Corey! Cant wait for the Django tutorial :)
+1
CobraL0rd as far as i know, companies are still looking for Django devs rather than flask ones, at least in Poland. Personally i prefer flask as well but it is still nice to learn both imo
I do see it indeed. But I meant the market keeps being more Django oriented, at least here. That's why you should learn both theese particular frameworks(not just cause the more whatever language you know the better). I'm also curious where "Flask is replacing Django"? Is it worldwide or just in your country?
Anyone watching in 2020? This series is so helpful man, especially for a high school student.
:It's helpful for me as well...I am into software development for 4 years..I find his tutorials awesome too
A high school student is doing flask, python programming? World is in grave danger..
kuls43 how so lol?
@@kuls43 I'm in middle school and i'm doing flask, python programming lol
I think Corey will be must have in 2030 too🙃🙏🏽
This is just life saving. I have been struggling with circular imports on flask for the entire weekend. Funny fact, almost no one is talking about this, and surely no one is doing so as thoroughly and crystal clear as you do. Thanks so much Corey. Finally was able to get this solved. Time to build models!
That was exactly the same struggle to me this weekend
Many Years later, this training is still helping people grow. Thanks Corey.
I don't know how many times I said to myself "Ahaa, never fully understood this before" while watching your Python videos. Even after a year or so dealing with Python, I always come back to some of the videos and extract something new and valuable.
I wanted to post exactly this.
6 years later, and still the best explanation of circular imports I've ever seen. Thank you for your work Corey. It is much appreciated even after all these years.
Thanks for taking time to explain the import errors! wasted 2 days searching for the right approach.
Your explanation of the circular imports made more sense than anything I've tried to understand so far!!!
This video is a fair justification of knowledge never dies. I have been searching for this in a lot of documentations and all, but the explaination and justification in this video is so on point. Thanks a lot Corey. You are amazing
That's right, I read from Miguels solution about this; it was horrifically involved, complex and didn't break it down at the right level. Your description and show and tell is absolutely fantastic, a breath of fresh air and no doubt helped the 100k people that have watched this. Thanks so much!
This video helped me so much. As a university student who knew only java, working in python and browsing github was confusing. I did not know how to read code and how the project was structured. This video made it all clear. Thanks Corey!
Very important video for those who wish to go a long way. Very important for big projects.
Thanks a lot.
5:00 Superb explanation! Couldn't understand it better from anyone else. A completely mind-boggling scenario made extremely simple. Corey you are just fantastic!
I absolutely LOVE this series. These are the kind of tutorials that I have always wanted, and now I have found them. Well done, Corey. You are awesome!
Some amazed Russian student here
Your lessons are so cool, nobody in my university can explain something so clear... I'm going to watch all of your tutorials. Thank you so much!
На каком курсе пайтон проходите? Я просто на первом, и у нас только C++ ;(
@@slavchina_reviews радуйся, у нас из адекватно преподаваемых языков был только паскаль на первом курсе, а уже третий c: Все остальные языки самостоятельно разбирать приходится для всяких учебных проектов, заданий и т.д. Так что сильно не надейся на универ и самостоятельно учи то, что тебе интересно и нужно.
Спасибо за совет! Да в своём универе я конечно разочаровался, но хорошо что есть тонна возможностей для самообразования, тем более если хорошо понимаешь английский.
if you're using vscode and you're unable to move the import statements below the top of the file, its because of a linter automatically reformatting your code. Uninstall or modify your python linter extension you have installed to continue with the tutorial. Thank you Corey, this is the guide I needed
you are unbelievable. This video showed me that I have learnt almost nothing about flask , and even python until watching these series of yours. You didn't only structure the app, you also restructured my python knowledge with a higher level. Thanks
Now I can even understand how they structured Django platform 8)
I have gone through many tutorials on youtube but the way you proceed with the course and explain the topics is something very unique.
Amazing as always... I don't think I would have ever understood the concepts of restructuring the project without your explanation. Thank you Corey!
Thanks in my new internship I have got this package structure with more
package and understood why they did it
Great teachers still exist honestly, you're good at what you're doing Corey. Well done.
This person here "explains" stuff. I'm just starting out with Flask and I think the videos are concise enough to not bore the pros and yet they're in simple enough terms so as not to scare the noobs like me away.... Just Great.
the twist in that error was amazing ❤️🔥
Hey Corey, I just wanted to say thank you for putting together such comprehensive tutorials for free. I had been slamming my head against the keyboard trying to build an app with Flask and not having a solid understanding of package structure. All of your videos have been exceptional, but I wanted to highlight that it was very difficult to find resources around package structure that made sense.
I have been using your tutorials to prepare for a pair-programming interview involving Flask, and this series has made me feel so much better about the whole process. Thanks for all you do; now to get this job!
man the feeling I had just after understanding the circular issue and why it is happening on User import and not on db import is something awesome.
For those who found it hard to understand, I really advise you to go through the video as many times as you need(I watched it 3 times ) , it is really worth the effort.
Bear in mind that when python calls the script directly that script's name is not flaskblog anymore, it is __main__. That's where you start to grasp it.
Corey M Schafer you are great !
Bruh . If only u could explain and not say for those having hard time . Watch again . I won't help
@@harshupreti1526 don’t think I could be clearer that Schafer’s explanation ! all you need to do ( or those who did not find it straight forward) is to repeat the video as many times as you need!
as a beginner, I find it way more friendly to keep everything in the same file. :) so this was a real headache actually. Forgot to add that your tutorials are great! learning alot.
Same hahahaha
exactly my point.. Splitting it all up makes it complex
Thank you thank you thank you! This is pure gold!! I had made an app just in one file. Really chaotic, but it worked. It seemed like such an enormous effort to restructure everything, but with your video I did in in under an hour. Thanks!
3:10 woow! when a module is imported ,python runs that entire module.
Amazing series!!
Thank you for this great tutorial. I've been following your tutorial series and it's a complete gold mine! I watched countless tutorials where they take shortcuts by not showing the proper way to implement things. For example, most tutorials don't show how to organize their Python projects because the instructors would rather skip explaining circular dependency and just put all the code in a single main Python file instead of breaking them up. They are not solving the problem but merely getting around it for the sake of producing tutorials. But in this tutorial, you covered everything from the ground up and it is truly eye-opening. Thank you so much from the bottom of my heart.
I love the way this man talks, so explanatory :D
We should say thank you for uploading instead you said thank you for watching.
Thanks a ton.
Tree package in windows - "pip install tree"
View the directory structure by using command "tree /f /a"
Thanks, don't suppose there's a way to make it look like Corey's did. Perhaps windows we don't get as nice a tree
it is a DOS command, no need to install
yes, but my tree is not as nice as Corey's.
D:.
├─.idea
│ └─inspectionProfiles
└─flaskblog
├─static
│ └─css
└─templates
Does it work on Mac also, I installed tree with pip3 and pip and it does not run.
Thanks, Corey. LOVE your Python videos. I would love to see another full-scale real world application with Python and MySQL / PostGreSQL. Python and MySQL / PostGreSQL are some of the most in-demand skills from employers I have been seeing lately.
Watching from 2023 and I still find this super helpful 😍
I'd love to see this lesson structured like this from the beginning. Maybe just a bare-bones website, nothing fancy. I wish there was something as simple as a template you could just git clone to get you into a package structure with common modules already set up and ready to go with basic functionality. I set up my own website with your help and am trying to customize it and skip unneeded features from these lessons as I follow along, but the amount of drift my project has taken from the start of this series is almost too much to follow along on this one. Too many moving parts. Thank you for everything you do, it's made a huge difference in my life.
Excellent explanations - helped me finally clear the hurdle of circular imports and get my first practice Flask app working.
This particular module of the flask course is really awesome.. I revisited this video again to solve a problem with packaging and module structuring.
Now I am sure that I can make a better project module structure 🙂 Thanks a lot to Corey.. your videos are crisp with great content!
Thank you for this part of the tutorial. I've been struggling with project structure for some time now, wrapping my head around circular imports, and this made things much clearer.
some months ago I didnt get this, now I understand. feels good,
Really impressive explanations and argumentation lines!
Best python series I have ever come across!
I have just subscribed dude and I wish I could do more, you are just a life savior, you deserve way more subscribers , you are dedicated and you aren't holding any important information back, may god bless you those Tutorials are priceless.
Corey - AWESOME video! This saved my bacon, I have a huge project and was really struggling with restructuring after switching from Mongo to Postgres (don't ask). Thanks so much for taking your time to put this together.
This channel is the best. I'm working on my first Flask project and your tutorials have been of great assistance. Thank you.
Great lecture Corey! Just for the information, you don't need to create directory flaskblog. You can easily get rid of circular imports by doing following (Please correct me if anything goes wrong):
in models.py
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
db = SQLAlchemy()
in flaskblog.py
from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm, LoginForm
from models import *
URL = "server://username:password@localhost:port/name_of_database"
app = Flask(__name__)
app.config['SECRET_KEY'] = your_key_here
app.config["SQLALCHEMY_DATABASE_URI"] = URL
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app) # This is the step that will create the magic now you don't have to say db = SQLAlchemy(app)
Anyway you are great!
I'm making a flask server and the directory structure was one problem so I wen through many videos and find anything... until now. THANK YOU!
Markdown summary/timestamps of this video:
- [0:05](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - intro, reasons why structuring as package. How to convert a modular structure to package.
- [0:45](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - creates models.py file
- copies User & Post classes to new file.
- `from flaskblog import db` # imports db
- `from datetime import datetime` # imports datetime
- `from models import User, Post` # within flaskblog.py module (later named run.py), imports the db classes
- [2:17](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - attempts to run flaskblog.py.
- Error message saying `cannot import name 'User'.
- This is a circular import.
- When something is imported from a module, the entire module is still run - not just the section being imported.
- There are 2 errors here.
- TBH I can't really understand the logic of error #1.
- It's not super important to understand why, but the answer is package restructuring.
- Basically the cause/solution for error #2 is:
1. in flaskblog.py/run.py: `from models import User, Post` (referring to the models.py file)
2. in models.py: `from flaskblog import db`
3. db hasn't yet been imported in flaskblog/run.py file as the line is below the import command in #1.
4. Solution to this, is moving the models User/Post import to below the `db = SQLAlchemy(app)` line.
- [9:50](th-cam.com/video/44PvX0Yv368/w-d-xo.html) The answer to error #1 is:
1. Create a new folder in project folder with same name as application. 'flaskblog' in this case.
2. Create a new file in the application/flaskblog folder called `__init__.py`
3. Move forms.py, models.py, static + template folders into the application folder.
4. Edit __init__.py. This is where we initialise the package.
1. Move all the imports (at the top of the page - not the models import) from the flaskblog.py
2. Move also the app, app.config and db initialisation lines.
5. [11:24](th-cam.com/video/44PvX0Yv368/w-d-xo.html) Create routes.py file in package folder
1. Paste all the routes + dummy data into this file - everything left but `if __name__ == '__main__'` line
6. Rename the flaskblog.py to run.py as it's only purpose now is to run the application.
7. [12:38](th-cam.com/video/44PvX0Yv368/w-d-xo.html) Import the app into the run.py file, so the `app.run` command works by adding `from flaskblog import app`, this will import from the __init__.py file. *The app variable MUST exist within the _init__.py file.*
8. **Routes.py** clean up time:
1. Get the imports sorted for routes. Move the `from flask import redirect, url_for, render_template, flash` to routes.py, make sure you leave the `from flask import Flask` line in the init file.
2. Move the forms import to routes.py, you'll need to use package names as well, so `from flaksblog` becomes `from flaskblog.models` - `from flaskblog.forms import LoginForm, RegistrationForm`
3. You'll also need to import the app, as you have lines `app.routes`: `from flaskblog import app`
4. Import the routes into the init file, make sure the line goes below the app variable to avoid circular importing problems: `from flaskblog import routes`
9. [15:47](th-cam.com/video/44PvX0Yv368/w-d-xo.html) **Forms.py** clean up not needed as we're only importing pip installed packages.
10. [15:56](th-cam.com/video/44PvX0Yv368/w-d-xo.html) **Models.py** clean up:
1. Change the `from __main__ import db` to `from flaskblog import db`
11. [17:38](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - runs application
12. [18:21](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - creates database again
1. `from flaskblog import db`
2. `from flaskblog.models import User, Post`
3. `db.create_all()`
13. [19:28](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - Checks the site.db location - it's in the package folder, as the address is relative.
14. [16:30](th-cam.com/video/44PvX0Yv368/w-d-xo.html) - Tree structure and overview of package:
```
├── flaskblog/
│ ├── __init__.py
│ ├── forms.py
│ ├── models.py
│ ├── routes.py
│ ├── static/
│ | └── main.css
│ ├── templates/
│ └── about.html
│ └── home.html
│ └── layout.html
│ └── login.html
│ └── register.html
├── run.py
```
Wow, your package explanation was so clear. I am so far VERY impressed with this tutorial series! You deserve way more subs Corey!
watching this in 2024! Thanks Corey
WOW! You made this very sensitive and complicated topic look much easier! Thanks!
Great explanation on the circular import error!
Overall, great content & extremely helpful!!
That is really really clean explanation. Even if i was a dummy i could understand very well. Thanks for videos...
You inspire me like no other pythonista Corey!! Thanks a bunch brother.
Thanks a lot!! Really appreciate how you go into the depth of topics like you explained the import error. I think these things are difficult to learn as a beginner.
Yes, true.
Best explanation for packaging. Thank for your clear explanations.
In addition to helping to understand flask structure (and why everyone uses a run.py entry point into a python package), I was surprised to learn that you can import a variable, in this case "app" which contains the application created in __init__. I guess I had assumed you could import a module, a class, and even a function, and that all made sense to me--sort of like "including" code from some other file. Now I understand you can also import an object which isn't code itself (in the source-code sense) but is rather a thing created by code, again in this case "app." That really helps clear up a lot of confusion.
These series are fenomenal, if a 15 yo can fallow this tutorial then everybody can too. Great job!!
0:30 => "imports can get a little weird" is an understatement . Imports in python area hell of a lot confusing !
Thanks a ton for this video , its still so relevant even after 6 years!!!
Hi Corey! Thank you for sharing your knowledge! I really much appreciate your efforts.
Breaking down the structure of the project into a package is a very good idea but your approach with putting import statement at the bottom of the __init__.py file not only breaks pep8 standard but also does not solve the 'ugly import' in flaskblog.py problem that you wanted to avoid by creating a package initially. Have you considered moving the 'from flaskblog import routes' statement into the top of the run.py file? This seems to solve all of the issues. Cheers!
Hi, just check this post on stack overflow. Your linter seems to be the problem. stackoverflow.com/questions/42649800/moving-views-to-a-separate-file-without-violating-pep-8
@@alexanderhoffmann4930 Sorry but I won't agree with that putting Import statement anywhere else than in the beggining of the file is not confusing for a human reader.
I agree that it does not technically violate PEP8 standards but I feel that the import at the beginning makes it that much less confusing,especially for beginners. P.S: Both work perfectly fine
Your solution works for me, initially i was having exceptions "jinja2.exceptions.TemplateNotFound: home.html" when import routes in __init__.py. After moving import routes to run.py.. smooth running. not sure what happened. Cheers and Thanks a lot.
@@avitinformatics8221 let me explain why this works, when you do 'from flaskblog import routes', it will first run the module's __init__.py, so it already get app, then it will run routes.py, when it comes the line 'from flaskblog import app', since it already run the init of flaskblog, it won't re-run the __init__.py, and just watch for the app, and it's actually found, so there is no circular import.
Your tutorials are pure bliss! Thank you for putting the time to deliver such a high quality product!
This series is awesome! Thank you so much for giving this tutorial to us for free!
Correct me if I am wrong. I haven't achieved to blueprint video yet. But, via this package structure, in deed we are preparing re-usable flask apps like it is in Django. Only thing we will do to use an app in another flask platform, is to copy app folder and register it in run.py via flask blueprint capabilities. Amazing, I think if people knew this strategy, Flask would be much more popular than Django.
Great work. Not many channels like yours in youtube. Amazing content, very valuable
Thank you. I was having trouble understanding circular imports in python.
The best tutorial ever. You're doing a good work!
this was an amazing tutorial. I think i've learned the most from you and sentdex on youtube keep up the great work.
You've borned a teacher man
Thanks for Corey Schafer and your video always give me a very good concept not only for flask and python but programming. :)!!
Thank you for this. I was having a doozy of a time with circular import issues. I knew what was going on, but couldn't figure out what to do about it exactly.
What a confusing error ! and how you are explaining it so fast? dude, you explain in a way that I thought you had made the Flask your own! Good job but I still need to play this video for several times to get whats going on. LoL
Your tutorials are great, I learnt python entirely from you, it would be lovely if you could break the content down into smaller videos. Thanks a lot.
Thank you so much Mr Corey! I really love your tutorial series. Especially easy for beginners like myself to understand easily
Great tutorial, now I know how to structure my app good :-) !
Big respect for these super tutorials! You are a great teacher :)
It's working! Dopamine incoming! Merci beaucoup mon ami Corey.
yummm Dopamine
He's back! Keep up the good work!
Edit: I have been waiting for a good toturial on flask, so thanks!
more knowledge in 20mins than any uni degree
PRO TIP: Do NOT use dashes "-" for naming your packages. For example, I used "flask-blog" instead of "flask_blog". I got a SyntaxError when I ran "run.py".
There is a reason Python does not like dashes, and only likes underscores when naming your packages :)
A guess would be because python, as an interpreted language, thinks of '-*' words as flags, right?
@Major Gear I've never worked on Ansible before, but that's nice to know!
Its so cool you also give some theory, thank you very much
I love this guy, Corey!
Make me feel so smart...
I freakin love you man...no alcohol and I am married and no shame in saying it ;)
Great course, great explanations. Thanks a lot.
Thank you for such amazing series. This is really very helpful.
Corey, I have watched a number of your TH-cam videos and I think you do a great job. Most other videos on TH-cam take a long time to get to the point, over explain simple issues or take for granted more complex knowledge. Sometimes all three in one video !!! You get to the point and explain things once (leaving me to rewind if I don't understand), which is perfect and makes your channel my 1st port of call. Thank you.
I am using PyCharm and it’s “new project” command sets up a project with an environment (venv subdirectory). Pycharm will make a package directory (complete with __inint__.py, do I move the venv directory into the package directory as well as static, templates etc ?
I wondered why Corey needed the import of routes in __init__.py, since we don't use the name "routes". I see other people wondered the same thing. As Corey notes at 2:57, importing a module doesn't just bring in the names -- it also runs the code in the module. The routes.py code defines the route functions and registers them with the app (with the help of some decorators). If we don't import routes somewhere, then that code never gets run. The import in __init__.py is just there to run that routes code.
Thank you so much for THIS video, and for the whole flask tutorial!
Nice not to need set speed to 1.25 great videos.
This video really great..i fully understand now
Again, I can't like enough! Excellent job!
Why are u so damn good at teaching❤️❤️❤️
Lovely. I wanted to blog. This can help me. Thanks. :)
This is truly a treasure...
When I tried to use db.create_all() command..
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.
have the same problem. i used "from flaskblog import app, db
with app.app_context():
db.create_all()'
It created the site. db file in my anaconda folder, in a folder called var/flaskblog-instance.
i am unable to query the db file. it gives me this error:
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.
You are the man! Thank so much. I'm a big fan of yours!
Amazing tutorial as always!
Yeah I need to watch this one again. I was with you and then I got lost. But, a great tut nonetheless
Thanks for the inspiration and knowledge
Hell yeah I understood the concept.
Not fully got it, but thanks for the free content anyways.
awesome videos. Thank you very much !
Cory, my man, I promise myself to see you in person and buy you a pint of beer.
A truck load more like!!
I was gonna comment the same ! :)
@@waleedmashrequi5173 We will all do a meet-up one day and throw a thank you party for Cory; the man, the myth, the legend.