Flask Course - Python Web Application Development

Flask Course - Python Web Application Development

SUBTITLE'S INFO:

Language: English

Type: Robot

Number of phrases: 10217

Number of words: 59867

Number of symbols: 242617

DOWNLOAD SUBTITLES:

DOWNLOAD AUDIO AND VIDEO:

SUBTITLES:

Subtitles generated by robot
00:00
we are going to start learning about the flask web framework now this is a micro framework that allows everyone to build their own web applications using the python programming language and what is so great with flask it allows everyone to build web application with only a few lines of code so it turns the experience of building a website to a lot quicker and easier and in this series of videos we are also going to start with a very minimal application and we are going to push forward until we have an advanced website
00:31
where real users can start using it so i really believe that in this series of videos we will cover everything that you need to know about the flask web framework in order to come with a great looking website alright so let's have a quick look to the website that we are going to build throughout this series okay so this is the final result of the website that we are going to build throughout this series now the main idea of this website will be to create a marketing system where different users can buy or sell their items so in order to get started i can press
01:02
in here in that button and then you can see that i see a warning here that i should log in to access that page now if i'm happened to not have a user here then i can basically go ahead and click register now i'm going to mismatch these details a bit so you can be aware of the different error handling that we are going to apply on this website and once i click on create account then we can see that we receive several errors regarding to that website so as you can understand we are going to
01:33
apply a lot of error handling like in real websites so now i will go ahead and create a valid account here so once i click on create account then we can see that we are inside a real looking web page and you can see on the left pane that we have the available items on market and each item has its name and also its barcode and price and we can display more information about each of our products and as you can see in up top here we have our budget that is
02:05
set by default to 15 grand so that means that we are going to create a budget system for our users as well and if i go ahead and purchase that item which its price is 520 then you can see that we receive a nice message with the purchase item and we can also pay attention that our budget has been changed over here and further than that we can see in the right pane that now on my items i see that we have
02:36
a new item that we have the option to sell it so if i'm going ahead and sell this item back to the market then we can see that our budget is back at 15 grand and we can also see that this page is refreshed to what it was before i purchased that item so it is going to be a lot of fun building this website and let's go ahead and get started all right everyone so you can pay attention that i'm inside the terminal in a windows machine but of course don't
03:07
worry if you use a mac or any kind of linux distribution because i'm going to say the same command that is going to work on those operating systems as well and also one more important point here i'm going to assume that you have python 3.8 or any version above installed and also a ready ide installed that you'll work with so it could be visual code sublime text or pycharm and just to mention off i'm going to use pycharm in this series but it is not quite important which id you are working with
03:38
just make sure that it is configured with python correctly okay so let's go ahead and create our directory that we are going to store our project files inside it so i will go here and write in make directory and this is the same command for any linux distribution as well and i will type in here the name of the directory that i want to make so it will be flask market and then i will go ahead and use the cd command to change the directory and i
04:08
will basically type in the name of the directory that we created and now before we go ahead and actually launch this directory in our pycharm i want to install the dependencies that are quite important in order to start building our first flask application so i will go here and use the pip to install some package and you can use basically the same command for any linux machine as well and i'm going to type in here pip install
04:37
flask and once i have done that then you can see that we got some warnings that are saying that requirement already satisfied because when you go ahead and install flask it is basically going to install some secondary packages that are kind of dependent to flask so just make sure that you hit this command correctly and then there is no any output of errors or something like that and once you have done that let me just clean our screen here then we can basically go ahead and test out if we
05:09
installed flash correctly and i will do that by type in here flask dash dash version and if you don't see any errors in this command then we should go ahead and try to start our first flask application because we received a correct output that just specifies the versions of some of the dependencies that are related to the flask framework so let's go ahead and build our first application in python okay so i have already opened my pycharm
05:40
here and you can basically pay attention that i opened it in a directory that is the same directory that we created so make sure that you point your id to the directory that we created a few minutes ago and then inside our directory we are going to create our first python file and you can do that by that way in python so i will call it market and then once i have done that it is a great idea to bring in from the web browser the starter template to basically build
06:11
up your first flask application now flask documentation already includes some basic structure that is going to allow us to build our first hello world application so let's go ahead and bring this in our screen and make that a little bigger and you can see here that inside that website we have a minimal application that is looking something like the following and i will allow myself to copy the entire code from here and paste
06:42
this in our python so let's open our ide again and i will paste this here and let's see what is going on here so as the first line we can already see that we import the flask instance from the entire flask package so it is quite obvious and it is not surprising but then we can see that we initialize the instance of the flask with the given argument of double underscore name double underscore now if you never saw this variable
07:12
before i have a video that is quite explaining what this magic variable is about basically this is a built-in variable that you can always call from any python file and it is referring to the local python file that you are working with so the flask instance is requiring to receive this parameter and this is why you are going to see that and don't worry too much about that if you don't understand it basically just leave it as it is and now we can see that in the fault line we have something that
07:43
is called a decorator in python now a decorator is basically a one step before a function that is going to be executed now when you see here app.route it is basically saying that what url in your website i am going to navigate through and display you some html code so you can see that inside here we have an argument that is basically saying a full slash inside the string
08:14
now this is the home page of your built-in website so if you just basically go ahead and type in some url without navigating for a specific page then it is going to lead you by default to that specific page so you can refer it as your root url of your website and then we can see that we have a function that is defined here and then it returns a string that says hello world now this is the exact place that we should see some html code in the future
08:46
but for now we are only returning a basic string that is saying hello world and those in flask are trended to call routes or views sometimes people call it wheels because in django it is called views and django is another web framework of python but i will try to stick with one word when i'm going to refer to those functions that are routing to a specific page and we are going to call them routes so once we understand what is going on inside this startup template then
09:17
it is a great idea to raise our terminal here and run in some commands to start this application so let me clean the screen here and in order to make our application run successfully we are required to set up several environment variables so i will go here and write up set flask app like this and make sure that all the letters are capitalized here and if you are working on a linux machine this command is basically should be export and not set so if you are on
09:48
windows set will work and i'm going to make that to be equal to the same name of the python file that we have just created and if you remember we call this market dot pi and once we have set that then we can basically go ahead and execute our application by saying here flask run and once i have done that you can see that we receive several warnings that we are going to explain them in the future but that last line is quite important to understand so
10:20
you can see that it says that it's running on http 127.001 and then we see a column here and then a number after that now if you know a little bit about basic networking then you can understand that this ip is a convention ip address that is basically referring to your local machine so this ip is going to be the same for each machine that this application is running on and we have something that is called the ports that are basically
10:52
describing the application that you are hosting as numbers so for flask by default it will be 5000 so if i will copy this url from here and paste this in our web browser then we should see a message hello world and that is perfect because we were able to complete the entire starting process successfully in the flask web framework so we can
11:23
basically go ahead and continue from here and one more point that i did not mention you'll see this hello world text because this is the root url of your web application and basically the hello world function that we saw before knows how to handle this so for example if i was to go here and type in slash about for example then we should receive an error that this is not found because we are not having a route that is handling the slash about so this is the reason we saw the
11:54
hello world message properly okay so i'm back to my pycharm and let's actually go ahead and try to customize this string a little bit to return a better looking page so we can basically go inside the string that we are returning and type in here some html code that will basically be rendered in the page that we are displaying so we can go here and use the h1 tag which is basically
12:25
the biggest header tag that is possible in html and we can write in here some text again like hello world but bigger and then we can go ahead and close our tag like this now if you don't know anything about html don't worry too much about that because most of the html code that i'm going to write here i'm going to explain what i'm going to do or i'm just basically going to copying and pasting several html code snippets so
12:56
we can make our lives easier when we display nicer pages okay so let's go ahead and save this out and go back to our terminal and restart our server so i will stop the execution of our web server and type in again flask run and then we will go to our web browser again and basically navigate back to the root url so i will just hit enter here then we can see that we receive this message
13:27
of hello rolled but bigger now you could see that in order to display this text i went ahead to my terminal and restarted our web application and you are probably asking yourself if this process is required to accomplish every time that you are changing your code well the answer for that is for sure no because you probably don't want to go ahead and restart your application every time that you are taking several changes
13:59
within your project so in order to prevent such a behavior we should go back to our terminal and look up for something that is called debug mode right here now you can see that we are having the debug mode off and you want to turn it on basically because this will allow your application to being synchronized every time you change your code within your market.pi file so if i was to exit
14:30
our web application that time and let's actually clean our screen again and we can basically go ahead and set up one more environment variable that will turn the debug mode on and that will be by the set command again and i will set the flask on the scar debug to one so basically this turns on the debug mode and then i will allow myself to run flask run again and then now that time we can see that the debug mode is on
15:02
now let's go to our python again and change the string that we are returning on our root url and see if those changes will be synchronized without restarting our web server so i will go here and i will basically type in here change text something like that and i will go back to my web browser and refresh that out and then you can see that the changes have been affected without restarting our web server so we can test this one more time by
15:33
adding some explanation marks here and save that out and go back to our web browser and refresh it and then you can see that the changes are being synchronized when you are on debug mode now the debug mode is something that you always want to turn on when you develop your application but once you go ahead and deploy this application in production then you definitely don't want to turn the debug mode on because this will cause the clients that are
16:03
basically surfing on that web server to see errors of your web application and it is always not nice to see your bugs as the one who uses your services so make sure that if you deploy your web application in the future then prevent the debug mode on because this is very important okay so let's see what else we can do with our routes here so let's actually revert this back to hello world again and i will basically create
16:34
here one more route just to practice how routes are working because we are going to create a lot of them in the future so i will write here the decorator that is required to make the route to understand which url you want to enable in your web application so i will go ahead here and type in slash about and then once i have done that you should go ahead and create your function that will handle
17:04
all the requests that are arriving to this url which is slash about and i will call this function about underscore page and i will close this out and i will go ahead and return one more html string here that will say about page so as you paid attention i created those h1 tags again and just to test this off in that stage let's go ahead to our web browser again and try to
17:36
navigate through slash about and this time you could guess that the slash about is going to work because we are handling what the slash about supposed to do so i just wanted to show you that you can create as much as routes as you want and then you can basically return some html response to your web pages now sometimes you don't always want to go ahead and hard coding your routes like we did until now so if you imagine a
18:08
situation like in facebook where you have different urls for like millions of profiles then you probably can understand that the facebook developers are not going ahead and creating millions of routes by hard coding their profile names so besides that we can accept something that is called dynamic routes and what i mean by that is that basically you can go ahead to your route in your flask application
18:38
and receive a variable name that is going to be accepted as well so let's imagine a situation that we want to display an about page for different people so let's go here and type in one more forward slash and then basically call the tags and add in here username now what i have done by this is basically i allowed this route to receive any string that we want after the
19:09
about page and since i have done that i can go here and change this return to something else so let's go here and write in a formatted string and i will open this h1 tags again and i will close it like this and then between those i will go ahead and type in this is the about page of and then let's call here the user name that we receive here now you can pay attention that
19:39
this returns us an error because we should handle this variable inside our function as well so let's accept this as a parameter so i will go here and type in username and now i can basically go back to our web browser and check out if this works properly so i will go back to our web browser again and i will type in here forward slash and then let's give a random name like john and then you can see that we receive
20:10
a page so we see the message here of this is the about page of john and i could go here and change this to whatever i want i can change it to michael to jim and to more names if i'd like to so the important point here is to understand the behavior of dynamic routes so just make sure that you understand the behavior of that as well okay so as you could notice here i deleted the about route from the last episode
20:43
because i want to focus on the next topic that i am going to talk about just now so until now we raised our html text within our routes in a hard coded text like you see here now when we go ahead and design complex html pages you probably want to avoid storing long strings within only a single file so in order to overcome this we have a convention in flask to a way we can
21:14
achieve such a task and the way we can basically do this is by creating a new directory that is called templates and then inside the templates directory we will start creating our html files and then we will separate our html code within this directory and we will refer our routes to those different html files so let's go ahead and get started and see how we can do this okay so i will start by creating a new
21:47
directory here and you can see that i'm creating that inside our flask market project so it is very important and you want to name it templates so make sure that you don't give it another name like html pages or something else just basically go with templates because the templates name is actually a convention to a flask so the package can understand that you are going to locate there some html files and within our templates directory we will go ahead and create one more
22:17
file and you can directly select the html file if you use the pycharm so i will name it home and then you can see that it already returns us some default html code and just for now i'm going to delete what is inside here and let's make our font bigger so we can understand what we are going to type in here just in a second now again for a basic example and to understand the process of referring
22:47
a route to an html file we will basically go ahead here and type in hello i mean home page it might be a better way to do that so we will call it home page and basically i will save this file and go back to our market dot py and then besides returning the hard-coded string like we did previously we want to look for a way to point this route to the home.html
23:17
that we have just created so it basically makes more sense to change this route a little bit and let's do that okay and let's go ahead and call this home page and then we will close this out and then write a column here and then we will return render underscore template now you could already pay attention that this returns us an error because we did not import it so we have to realize that we are going to import a lot of built-in functions
23:49
that are inside the flask package so one of them will be render template and the render template knows how to handle your requests and basically direct them into html files so let's go ahead here to our first line and import here one more function from our flask package and it will be render underscore template and as i have done that i have to specify here one more argument and for sure this will be the name of our html file
24:20
so i will go here and type in home.html and once i have done that let's go to our terminal and make sure that our server is still running and it is so let's go to our web browser and navigate to our root url and then you can see that we have completed the render template function successfully so this is the proper way that you always want to work when you organize your flask projects you always want to create that directory that is called templates and
24:53
then you want to start storing your html files in this specific directory okay so now that we understood how we can refer our routes into different html files it is about time to start working on styling our pages so our application could start be looking like a real website so in order to start styling we probably want to import one of the styling frameworks that are already existing out there so the most popular styling framework
25:23
will be a styling framework that is called bootstrap and you may have heard about bootstrap already because this is the most popular framework to style your pages and the main reason that you want to use a ready styling framework is to save time by the process of styling each of our html elements because we really want to focus on the python side of our web application so you can import the bootstrap styling by going ahead to your web browser
25:54
and basically searching bootstrap starter template and this starter template will help you to get started with all the requirements that are necessary to style your web pages so let's actually go into getbootstrap.com like i have already done here and go to that docs 4.5 so this is right here is the version of bootstrap so you want to make sure that you use the same version as i do currently because this might lead to differences if you just
26:26
work with another version so just make sure to work with 4.5 as well so i will allow myself to copy the entire html code from here and paste this in into our home.html that we have just created so i will open back our pycharm again and i will go inside our home.html and i will paste this over here now i know that it is a lot of html code to sync in but i'm going to go over each of the lines once
26:56
so we can really understand how an html structure looks like so let's go to the first line here and make our phone a little bit smaller so we can see most of the parts of this file alright so at the top here at the very first two lines we have some lines that should be located in each html file so basically this specifies that this document is going to be within a type of html and the language that we are going to use is going to be english so this is why we see the e
27:26
and n letters now each html file is divided into two important sections or what is so called html tags and those sections are called head and body now inside a head tag you are probably going to see a lot of things that are pretty much meta information or some imports that is pulling the styling and also some necessary information to change
27:58
your tab name when you navigate for that specific page so for example if we see here inside our head tag another html tag that is called title so this should be our name of the tab that we currently looking on so i will show the result of this html file just in a second and we can verify that the tab name is going to be hello comma road so one more important line inside our head tag will be this line
28:29
over here so you don't want to touch it at all because this is what importing the entire styling for our home.html file so you can basically see that by the link tag and the href attribute is the url that is probably pointing to that complex styling so this is something that is called css and the css allows pages to look a lot better and more dynamic so it is important to leave those lines over here
28:59
okay so i will allow myself to close the head tag and let's talk about the body now the body tag is what is really important and what really matters when you want to display some information within your pages now you can see that we also have here the h1 tag that we used previously and you can see that its text is hello world as well and you know what let's actually go ahead and change this to home page so we can have a better understanding of how this is going to be
29:30
look like now when you see the tag explanation mark and then the dashes two times it is basically saying that the following line is going to be a comment now you can already understand that because this is uncolored in pycharm so this is basically a comment and down here you can see two more tags that are called script now when you see script tags those are javascript libraries that are also going to be important and this is also a huge part
30:01
when you design a webpage so you also don't want to touch that because it deals with all the functionality within our pages so you don't want to touch those script tags as well so just make sure to keep them in your file and you can also see that we have one more long comment here but you can see that we have script tags within those comments so what that means it means that we can go ahead in the future and uncomment those lines so we can make use of more javascript libraries
30:32
but i will leave it now as it is okay so now we understood the structure of a basic html file let's go back to our web browser again and see the results of this page so i will go here and close this starter template and refresh our page then you can see that already the font of our page has been changed now i noticed that i zoomed in much in this page so i will basically revert this back
31:03
okay so you can see that the font has been already changed and this is what bootstrap is responsible for so when we go ahead and add more html code you are probably going to see that in a nicer way because of this bootstrap starter template that we already imported now you can also see here that our tab name is hello comma world as we have said a few minutes ago so this is also something nice that we can control by ourselves
31:34
and we will for sure do that in the future okay so i think this will be it about the explanation of how html page is looking like so as i said before i really want to keep on decreasing my explanations about each of the html lines that i'm going to write in so we will have a better focus on the python side of this flask application but for sure if you have any questions about the html in general make sure to comment them out so i can read them off and respond you all right so let's go back to our market dot py
32:06
and take care of something that is quite bothering me until now now you can see that our homepage is basically rendered when we went ahead and did not specify any extra information after our ip address and our poll now in most of the websites if you go ahead and type in slash home here basically this will be responsible to render you the same result like we saw previously now in order to handle two routes for a single html file
32:38
it is as easy as going down to our pycharm and right in here one more decorator so it will be app dot route and then this time we will write here slash home and if we want to test this out we can basically refresh our page and then you can see that we see the same result like previously and if i delete everything from here the result is going to be same so this is something that you want to keep on your web pages because it makes
33:10
sense to display the home page in both of the cases okay so now that we have understand how we can design our pages nicer it is about time to give our page a little bit nicer style rather than displaying a home page so we will start by adding a navigation bar so our users could have the option to navigate through different pages so the page that i will bring in here will be my personal website and throughout
33:40
this video or in the future episodes i am going to go into my personal website a lot and copying some html code snippets that will help us to write html a little bit faster so i'm going to include a lot of html code snippets throughout this tutorial so just make sure to go to the description of that video and navigate through the url that is going to be specified as the code snippets url and get those
34:12
code snippets so it will be much easier to you to follow this video so for this example to add a navigation bar i will go here and select the second part of this tutorial and i will basically go and navigate for our code and then you can see that as the first code snippet i have here the code snippet of navbar so i will allow myself to copy everything here and paste this in just under our body tag so let's fix the
34:43
indentation here and paste this in and now we should see a nice navigation bar inside our homepage so let's fix the indentation here a little bit more so we can have a better understanding which tag is inside another tag so i'm just going to fix that and i think that will be enough okay so what let's delete those indentations and now i think we are fine
35:15
okay so now i will save this up and go to our website and refresh that out and then you can see that we have this nice navigation bar up top here and then you can see that we have its name which is called gymshade coding market now we can change this whatever text we want we just need to find this specific html tag that is responsible to display this text so let's actually go ahead and find it so we can have a better practice
35:47
of how we can find specific html tags so i see that we have this text here and i can basically go ahead and change this to flask market and if i save this up and refresh it you can see that the changes are affected now you can see that we have this navigation bar but we don't have any extra links that we can click on them and actually navigate through different pages so to add those links we have to go to our python
36:18
and basically add some optional links so that the user can see which pages he can navigate so to ease on that process i can also go to my website i mean to my original website and then copy the second code snippet here which is called navbar dash options i mean underscore so let's go back to our pycharm and we want to paste this in right here where we see
36:48
a div tag which is with a class that is named as collapsed navbar collapse okay so we will paste this in over here and once we do that then we should see a better result of the items that should be available inside our navigation bar so if we go to our website and refresh that out then we can already see a better result of how a real navigation bar looks like and we can see that we have home
37:19
market and we have login and register now for sure when i go ahead and click on them it should not lead us to any different page because we did not configure those routes yet and we will do them in the near future now just to have a better understanding what is going on inside the second code snippet that we have just copied and pasted you can see that we have some li tags over here and this is a shortened version of a list tag
37:50
so you can see that each one of them just responsible to display some item that is available inside our navigation bar so we have here this which is basically a link to our home and we have that one which is going to be the link for the market in the future and as you could pay attention we have in the right side the login and register which we will configure in the future as well okay so one more customization that i want to apply
38:21
for this home page is to return it into a dark mode now in order to allow the page to be in dark mode basically you have to override some styling attributes and then your page will be displayed in a background color of black and all the text that you are going to provide are going to be displayed as white colors so in order to accomplish that i'm going to navigate down in this home.html file and let's make our font a little bit bigger here so you can have a better
38:52
look and right after our closure of the body tag i'm going to open up a new tag that is named style and i will close this up and between those i am going to provide some extra attributes that will override the attributes of our entire body so it will be something like the following so we will start by typing in body and then we will open and close curly brackets and press enter here so we can enter
39:22
inside our brackets and then here we will override the two attributes and the first one will be background dash color and i'm going to add here a column sign as well and this will be equal to a hexadecimal value that i already know that it is going to display a back color so if you don't know what an hexadecimal value is it is basically another way to define colors rather than just text so this is pretty much equal to
39:53
writing here black inside a string but this is going to make it a little bit more close to gray rather than just black so this is why i defined it with an hexadecimal value now in order to close this attribute we should add a semicolon here and our second attribute that we want to override will be color and that time i will give it as a pure text so it will be white now once i go ahead
40:24
and save this file and go back to our page and refresh that out then you can see that our page is turned into dark mode so make sure that you apply those configurations as well in your home.html file in order to turn your website into a cool looking dark mode and i just realized that our tab name over here is still hello world so let's go ahead and change this to finalize our styling so i will go back to our pycharm and
40:56
let's find this title tag that is responsible to display the tab name so i will expand our head tag back and we should change this into something that they are currently in the homepage so let's change this to homepage and remove the explanation mark and let's separate those words here and save that out and if we go ahead and refresh this then you can see that our tab name is changed so i think that will be it for the
41:27
styling part of our website and in the future for sure we will add some extra elements to make our site even nicer alright so now it makes sense to start working on some new python code to deliver a new items page to our users so this is why i will be starting to create here a new route and we will render a new html template so let's go ahead and do this so i will jump to a new line here and we will start creating a new route
42:01
so i will call the app dot route decorator here and it quite makes sense to send our users to a url that is looking like slash market so i will write it like this and i will continue on and create our function and we will name it market page and currently we will receive nothing as parameters and we will go ahead here and return vendor template and we will send them to a new html file that is called market.html
42:32
now i know that we did not create this yet so let's go ahead and do this so as you remember previously we just went inside our templates directory and we created an html file and we should name it market so this route could understand where we should send our users so let's go ahead and name this market and if you use pycharm then you will receive this auto-generated html now to make our lives easier a little bit i'm going to copy everything from the
43:04
home.html and i'm going to customize it a little bit so we can understand that we are inside the market page and not inside the home page so i will go to our home page here and i will grab everything that is inside the home.html and i will paste this in inside our market page and let's make the font a little bit bigger here now several changes that it might be a great idea to done here is for sure this title tag that
43:35
is changing the tab name so let's change this to market and i will scroll down here let's minimize this navbar and we will change this home page h1 tag to market page so we can understand where we are currently at now for myself here the website is currently not running so let's go ahead and complete the steps that we are required to run our website quickly so set flask app equals to market dot py
44:06
and we also have to set the flask underscore debug to one and now we are ready to go ahead and execute flask run and as we have completed this let's go to our web browser and try to navigate through the slash market route that we have just created and we can see that the results are quite great so now we are ready to work on to see how we can send information to this html from our route now to
44:36
do this i am basically going to go back to my pycharm and we are going to work on the route of market that we have created and we will try to send some random data from this route to our html and see how we can access it now the way we can do this is as easy as going here and sending more arguments that we will be accessing by their keys so let's go ahead and see an example for that so let's write in here item underscore
45:08
name equals to phone and i will close the parameters here back again and let's make this to be in the pip 8 style and now the way that we can access this is by this key name item underscore name now it makes sense to go back to our market page now and see how we can see the value of the item name argument so i will go to our market and actually to access that information we have to start
45:40
using some new web templating engine that is called jinja template now this might be sound weird what i'm saying now but if you remember when we went ahead and installed the flask library we kind of saw a lot of secondary libraries that the flask library is required to have them and one of those libraries are actually named jinja now as i said jinja is a special web templating syntax that we are able to access through html
46:11
because it is specially designed for python web frameworks so to do this i am going to go here and let's open here a new html tag for example a p tag so it will be a new paragraph and the way we can access this is by calling the variable syntax and that will be by double curly brackets opening and closing like the following now as i have set those curly brackets here we are allowed to access the information
46:43
that we have sent from our route and as you remember we have sent the key value of item underscore name so if i was to go inside our curly brackets and type in here item underscore name then we should see the value of this variable on our page so to test this out i will go to my web browser and refresh it and then you can see that we see the value of the item underscore name so this is a quite great
47:13
achievement and i hope that you understood all the process of how we can display information from our routes because to be honest when i saw the ginger syntax first i really was shocked and did not understand anything but i hope that this was a clear explanation and that you understand correctly why we have to include ginger syntax in our html templates so i will go back to our html file here and continue from here okay so as you see i'm back on my market.py file and now we have to look
47:45
forward to how we can display multiple items on our website now to do this we can basically change the value that we send to a list now i already have some information that i already generated up and this is basically a list of dictionaries so we will be able to display better data on our website when it comes to displaying some random items so to bring this code snippet that i already have generated up let's go to my website again and navigate
48:15
through the third part of this flask series and bring these items list of dictionaries called snippet now as you can see we are only having a long list with three dictionaries here so let's copy this up and paste this inside our market page now let's have a quick look in this long list here basically what we are having is three dictionaries that they are happening to have the same keys so we have id for this and this and that
48:46
and also the name key and as well as barcode and a price now once i have copied this out it might be a better idea to change our send information in this renderer template and i will basically delete this item underscore name equals to phone and i will change this up to items equals to items so now we will be able to access this entire list of items with calling the variable of items because this is what we have named
49:18
over here now to test this out again we can basically go to our market.html and change this to items so if we save our file and refresh our website then you can see that we see this exact dictionary i mean the list of dictionaries over here now you can pay attention that this looks quite ugly so to style this up i am going to insert these values inside a nice designed bootstrap table
49:50
so let's go ahead and do this all right so we will go back to our market.html file and in here we will just delete this paragraph for now and we have to use an html tag that is named table and inside here i have to provide some information regarding to my tables rows and columns and to save this work from us i already have generated a table that is going to look quite nice and we are going to add to it some extra information
50:20
to design our rows and columns so to bring this code snippet here we will go to my website here and we will bring this bootstrap table code snippet from the third part so i will get this html code snippet and here i will just replace this with those table tags so if we copy this then we can see that we have here the table tag again but we have an attribute that we did not talk about it before basically when you see the class attribute inside an html file
50:52
it basically refers to bootstrap classes that their main goal is to give a nicer design to your specific html templates so for example if we see a class that is named table hover then we should see a special effect when we bring our mouse and hover inside our table and if we see table dark then you can probably understand that this table is going to be in dark design so in here we have our table head and table body and as you can see i already commented
51:24
here that we have to create certain columns here now since our dictionary includes some more than one key values then it might be a great idea to create more columns to our table so this is why i will go down here and i will start copying and pasting this code snippet three more times and i will replace those by the values of the keys that we have inside our dictionaries so if you remember we had a dictionary with a key of name
51:54
and we had an id so i did not touch this column at all and i'm going to change this to barcode and i'm going to write here price as well so as we have done that the way that we can fill in rows to our table will be easily by going down to the table body and writing some extra information inside those table row tags so tr is a shortened version
52:24
of table row now as you can see we have here some more tag that is called table data and this is basically a reference to the first column that you see here so if we are happened to copy this out and paste this in then since this is the second table data inside this table row then this is going to be located right under the column of name so this is why it is
52:54
a great idea to change this to value for name and i'm going to repeat this two more times so this will be barcode and this will be um price okay so as we have done that let's test the results inside our website so i will go to my web browser and we will navigate through our market page and refresh that out and you can see that we see here a nice table and you can see that those are the headers as you can pay
53:26
attention that its color is a little bit more bold and we can see that we have here information that is inside our table so it is quite great achievement okay so now that we have done this we still don't display the real information that we have sent from our market page route so let's bring up this for a second to remember this so i will open back our pycharm and i will go to market.py for a second so if you remember we sent this items
53:57
list towards our market.html but we did not display the actual values of those dictionaries that are inside the items list so to do this we have to iterate over this items list over here and once we iterate over this list then we have to access each of those keys in some way so let's see how we can do this okay so let's go back to our market
54:27
dot html well i'm not going to touch the html code inside our table head because in table head we done a great job because we only want to display here the columns names so i'm not going to touch it at all so let's minimize the table head for a second and now as you paid attention each of our tr tags are responsible to create a new row inside our table so it might make sense to start to launch here a for loop and
55:00
start iterating over our items but how we are going to do this with the ginger template so if you remember the ginger template is that special template that allows us to access the information that arrives from the route so i'm going to write here new ginger syntax that we did not see so besides doing curly brackets twice i am going to replace the inner curly brackets with percentage signs and what that means it means that you are going to
55:32
call a logic code so if until now we were able to access variables that are arriving from ginger syntax this time when you see the percentage signs basically you can write a code that is quite looking like a python code but this time it is not going to be variable names and stuff like that besides those are going to be if statements for loops and stuff related to actual logic so in here i can go with
56:02
four item in items now the reason i write here items because this is accessible from the market route and to close our for loop here i will call those code blocks once again and i will right here and four together combined so this is the exact syntax of how you can bring in a for loop inside your html template and now i'm going to cut this entire
56:34
tr html block here and i'm going to paste this in inside this for loop that we have just created so once we paste this in let's organize the indentation for a second great so now we should see this table row three times and the reason we should see this three times because we have three dictionaries in our items list so if we save this and go here and refresh that out then this is the exact result that i was
57:05
talking about so again the reason we see this three times because we have three dictionaries inside our items list okay so our next problem is quite clear and the problem is that we don't see the values yet although we iterate over this items list so to access each of the keys that are inside those dictionaries we can basically go and open our pycharm back and replace those strings here that are inside the html tags with the actual value so to do this
57:37
i can basically delete this up and call the variable block again by typing in curly brackets twice and i can basically type in here item dot id now the id is the key name of the dictionary and the item is the variable that i'm iterating on so this is why i can access this item variable and i can change all those three table datas here to the same as this one so let's go ahead and do this so i will replace this with item dot
58:09
name and i will replace this with item dot barcode and i can replace this for sure weight item dot barcode and we will close our curly brackets and create a space here so sorry this should be price okay so we should change this to price and now we can go to our html page again and refresh it then you can see the actual information that we meant to display from the real
58:42
beginning okay so this is great achievement so if we are happened to add some more information inside our market.py then this page is for sure going to be updated automatically so one more final thing here to customize this page a little bit better we can add here a dollar sign or something that the customer that uses this website could understand that we are referring to actual money so we can basically go back here and add here the
59:12
dollar sign and see the effect of that over here all right so one more final thing that i'd like to do in this table is enabling our users the options of seeing more information regarding to a specific item and also the option of purchasing a specific item because we actually want to simulate a situation where we have items in market so to do this we can basically create one more column here and we can name it options and we can add two more buttons
59:43
in each of our item rows so let's go ahead to pycharm and do this so i will open my pycharm here and i will find the table that we have created so as you remember our columns are located inside an html tag that is called t head so we will expand this back and we will add here one more column so we will create a th tag and our scope will be col so this is a shortened version of
01:00:14
column and here we will add options and so we added the column here and now we have to add its value in each of our rows so to do this we can basically go here to our table body and find our for loop and add here one more td tag which is table data and over here i will basically hit enter so we can add more html elements and i will call the button element to
01:00:45
display a nice looking button to show our users the options that he can do so let's create here the button tag and over here i want to customize this button a little bit so i will call the class attribute and inside the strings here i will specify the classes so i will write in here several classes that i already know that they are going to customize this button a little bit better so we will write here button like this and we will also write button dash
01:01:17
outline and we will also write here button dash info now again those classes are made for specialize our styling in each of our html tags so let's go ahead and close our button tag and you can see that we already have the closure for this button and so now i want to write here a text like more info and i want to scroll down a bit so you can see what i am doing here and so now that we have completed
01:01:46
this button basically i want to repeat the same process to allowing our users to purchase that specific item so it will be the button tag again and this time our classes are going to be again to btn and button dash outline and that time i will type in here button dash success so the differences between button dash info to button dash success the button info is going to fade into our button a more blue color and the button success will fade in
01:02:18
the green color so when i go ahead and close those tags i can basically write in here purchase this item now let's go ahead and test this out so i will open my browser again and i will refresh our page and you can see that we receive the options right here so this is quite great now for sure if i click on one of those buttons nothing is going to happen because we did not configure the functionality
01:02:50
behind those buttons but we will do this in the future so don't worry about it right now alright so previously we were able to display a nice looking market page by writing this html code and it was responsible to display a nice looking page with several items now if you remember to display this nice looking page i went for my home.html and i copied the entire code from here and i pasted
01:03:23
in inside mymarket.html and then later on we gave it our own customizations now if we consider a situation that our website could be divided into 10 or 20 different pages that will mean that we have to copy and paste some basic html code every time that we want to come up with a new page and the reason is we want to keep certain elements in each page that we display so for example if you
01:03:53
see in the home.html we happen to have this long nav html tag now it is obvious that we want to display the navigation bar in each page that our users navigate on because we want to allow our users to see the pages that they can navigate so the main point here is to think about some method that will avoid copying and pasting a lot of html code and to overcome this we have something that is called
01:04:24
template inheritance now the idea behind that will be to have one base template html that we will always inherit from and that way we will save a lot of copying and pasting html code so in order to achieve this what we have to do is creating one more html template and it makes sense to give it a name like base layout template whatever you like to and then basically put in there some html code that will be always displayed to our
01:04:56
users so let's go ahead and do this okay let's go inside our template directory and create an html file that we will name it base so let's go here and select new html file and i will call it base as i said and i will delete everything from the auto generated html now as you could guess i already came up with a base dot html that is going to save us a lot of time from writing some base template html
01:05:27
now in order to get that base.html we will basically go to my website and bring it on here so we will go to the fourth part of this entire tutorial which is happen to be right there and we will select the code and bring in the base.html and for sure once i paste it i will go over what is going on here so we have our base template and in the next few minutes we are going to show how we can inherit the entire html code
01:05:57
from this base template now let's see what is going on inside the head tag now in the head tag we have the same tags that we were happened to copy previously in this tutorial from the bootstrap starter template so there's nothing really different in here only what i have done here is named our title base title so we can see the effects of it now if we close up our head tag and focus on what is inside the body then we can see that i already have commented out the location where we want
01:06:28
to see the navigation bar and also i also wrote here one more comment for the future contents that we are going to add to this base template so that way we can understand where we have to insert different html templates now down here again we see some javascript libraries that we import like we saw previously and this style here is again here to allow our site to be in dark mode so if you paid attention then we see that background color inside the body
01:06:58
and we also see the color which is the foreground color as white so let's also close our style tank over here now once we understood what is going on inside our base.html it is a great idea to go inside our home.html and try to inherit whatever is inside this base.html that we have just created so in order to ease our lives here i will use the future of pycharm to split some html files into two or three different displays so let's go ahead and do this very
01:07:29
quickly so i will click here split vertically and on our left pane we will keep our base.html and on our right pane we will display the home.html okay so now i will basically delete everything from the home.html and i will use some special ginger syntax to inherit the code that is inside the base.html so that will be by the code block syntax we saw previously so it will be
01:08:01
curly brackets and then the percentage signs in that case and then we will use a function that is called extends so we are extending this base template and basically here inside our string we can specify the name of the html file that we want to extend from because all the html files are located in the same directory that we called templates so i will go here and write in base.html and once i have done that i should expect to see pretty much
01:08:31
nothing in our home.html so let's go ahead and see this in action so i will go to our website and i will basically navigate for our home page and then you can see that we are happen to have this black page so now that we achieve this basically now we can decide which content we want to put inside base.html and which content we want our inside home.html so for example our long navigation bar html tags
01:09:01
are must located inside our base.html so let's go ahead and do that so i will go to our pycharm and let's actually bring this long nav tag from the market.html so i will locate our market.html over here so let's grab our navigation bar so that will be the entire tag that is called nav and i will copy that out and i will paste it in where we located this
01:09:32
command which is says navbar here so once i paste this then we should see a great result where our base template is having the navigation bar so let me customize the indentation a little bit and i think this looks okay so we will go to our website again and we will refresh that out and then you can see that our navigation bar is back up again now the beauty in that process is that no matter which html file i'm
01:10:03
going to create in the future all i have to do is using this extends method that we saw just a minute ago and then each time i do this then we will see our navigation bar so this is a quite great achievement okay so even though we have completed the inheritance successfully there are still some problems left that we have to understand how we can figure out for example one of them will be the fact that you see that our tab name is base title now we are inside our home page so it
01:10:34
does not make sense to display to our users base title each time so what i mean by that is that we have to figure out how we can differentiate between content that we want to display up on our each page to a content that is going to be unique per page so let's go ahead and do this so i will open my pycharm here and basically on the left pane we got our base template and on the right pane the home.html again and now what i can do is basically marking any area
01:11:05
in our template that is going to be unique per page so the way i can do that is as easy as going for example inside our title tag and write in here some special ginger syntax so it will be by using the brackets and then the percentage sign and then we have to use the function that is called block so i will use this function and i will give it a name like title and i will close our block by
01:11:37
using and block now if what i have done until now is quite weird for you i can totally understand that but you will get that in a few minutes so once i have done this then i am allowed to go inside our home.html and call this block of code by simply writing block title and then inside here i can write anything that i want and the content that i'm going to put in right after our blog title
01:12:08
is going to be replaced and use the content that we write in home page so let's see that in action so i will right here and block again just to close our block and then inside here let's write a text like home page and use the indentation here so it will give it a cleaner look and once i have done that we can basically save this and go to our website again and once i refresh it then you can see that our tab name is changed to home page so the ability
01:12:39
to mark certain areas in our base template as unique per page areas is quite great because it is going to allow us to write more organized code and now basically we can use this block functions in more areas inside our base dot html and then we can call those blocks in our different pages inside our project so i will go to our python and declare here one more area that is going to be as the area of our body in each page
01:13:11
so we can basically go here and use the block again and now we can name it something like content so let's fix our indentation here like that and then we can write again and block and once i have done that we can basically go back to our home.html and try to call this content block again and write whatever that we want to write
01:13:42
to display it inside our homepage so i'm going to go back to my home.html again and i'm going to use the block content and then i will close our block by simply saying end block and now we can write a text like this is our content for the home page and once i save this then we should see the this is our content for the home page
01:14:12
only in our home page so let's test this out so once i refresh that out then you can see that we see this text right here all right so now that we have applied the inheritance correctly for our homepage let's also do this for our items page so we will basically go to our market.html and take the same actions over there so i will open my pycharm in market.html and before i actually go ahead and delete everything from here
01:14:44
it is a great idea to copy the table that we have created previously and then later on we will paste it inside our blog content block so let's go ahead and do that okay so i will navigate down here and i will find our table and you can see that it is right here and then i will find the closure of this tag and i will grab the entire table and i will basically copy this entire html snippet and now i am pretty much ready to delete
01:15:17
everything from here and using the methods that we have applied for our home.html so i will start by writing extends base dot html and i will continue on here as using the blog title and the block and the end block again and then we should do the same process for block content so it will be block content
01:15:47
and again we have to close our block once again so once i have done that basically inside our title we just have to give it a text like market page and inside our content it is a great idea to paste our table back in so we can have pretty much the same page that we had previously so i will go in here and then create an indentation a little bit and then paste back our table so i think this should work let's test this out
01:16:17
by going to chrome again and refresh our homepage and then you can see that the behavior is quite same now i will navigate also to our market and then you can see that we still get pretty much the same result like we have done previously what we can do is basically adding a title like market page and we will just continue with the customizations in the future so this is a pretty much great results until now and i hope that the entire process of how we can use the template inheritance was pretty much clear for you
01:16:48
okay so there are still customizations left before we close this template inheritance topic and basically inside our navigation bar we currently don't have the functionality to navigate between different pages so to test this up if i click on home page nothing happens and as well as in our market over here so let's go ahead and configure them so i will open our pycharm again and we will open our base template and inside our navigation bar
01:17:18
we can basically look up for those a tags now those a tags are what responsible to navigate users to different pages and so if you look at the href attribute inside the a tags this is what is actually sending our users to different areas now we could have done here something like slash home so in that case it will navigate our users to slash home but this is not a great idea because you
01:17:51
don't want to hard code your urls in that way so what happens if in one day you want to change the route to something else then it is not considered as a best practice now again this is going to work i'm not saying that it is not going to work but it is quite wrong and we can even check this out if it works properly so we can go to here and refresh our page and click on home and then this will basically navigate our users to home page but we can do this in a more pretty way and i like to apply that okay so i'll
01:18:23
open back our pycharm and in here besides hard coding for slash home we can basically use a built-in function from the ginger syntax that is going to look like url underscore four so let's call this up in here and pay attention that i use the double curly brackets so in here i can close this function like that and between here the url underscore 4 expects for one special argument now the argument that we are going to
01:18:54
give for that function will be the value of the name of our route that we want to navigate our users so in this case if we want to navigate our users to the home page then we should type in here the name of our route that we have created to navigate our users to the home page and in our case if you remember our route name was home underscore page so we can basically go here and type in home underscore page
01:19:26
and once i save this let's go to our web page and test this out so i will basically navigate back to market and i will click on the home page and then you can see that it knows automatically to navigate our users to forward slash home now this would even work if i was to go inside our market dot py and change this to something else like home three times okay let's just do this for testing reasons and test that out so i will go to
01:19:59
market again and try to navigate back to our home page then you can see that now we were able to achieve a kind of a dynamic way to navigate our users to the home page so we only have to specify the name of our functions rather than specifying the hard-coded urls so of course i'm not going to leave this home home home so let's revert this back and i will delete this from here and that will be it so let's apply the same thing for the
01:20:30
market url as well so i will basically copy everything from here and i will paste it in inside our href where the market is located and since our function name was market page then i will basically change this to market underscore page and once i have done that let's test the results one final time so for sure now if i refresh then our flask could not find anything that is related to home home home so we will write in here
01:21:02
home back and click on market then you can see that the behavior is quite great so the url 4 is quite useful in that case okay so just a quick reminder here this is the final situation that we have reached until now on our website so if you remember those items that you see on the slash market page was basically because of the list of dictionaries that is arriving from here and is sent
01:21:34
directly to our template and now we want to look for a way to change this behavior so we will be able to store information inside an organized database so the way we are going to do that is by configuring several configurations on our flask application and we are basically going to use a real database that is going to store our information inside tables now if you never worked with databases before basically it allows you to store organized information within tables where each table describes
01:22:05
some data that you want to store so for example you may have a table that its name is item and it may have a columns such as name barcode and price and this is exactly what we are going to do in order to store organized information inside an organized database so just a quick brief for the way that we are going to implement this basically we are going to use a new file and that file is going to store all our information now normally
01:22:35
when you want to store a large amount of information you should execute a database service that is running in the background of your machine but we are not going to do that because we are only working on a local environment and currently we don't have any case where a lot of users are going to cause traffic on our website so this is why we can allow ourselves to use a minimal database and we can store our information inside a file besides running a database service on our machine so the way we are going
01:23:05
to do this is by using sqlite3 so sqlite3 is an extension of a file that allows to store information and we are going to connect that file to our flask application so let's go ahead and do that okay so first of first we need a flask tool that allows to create tables within that database that we are going to work with with using python code now when it comes to developing websites with python basically you can create your database
01:23:36
tables with python classes so in order to use this feature we need to go ahead and install some flask tool that allows us to do so so we will basically go ahead to our terminal and stop our website for a second so we will basically go ahead and write in pip install flask dash sql alchemy now this is the exact package that will allow us to write database tables
01:24:07
with python classes and we are going to see how we are going to do the conversion from python to actual database information just in a few minutes so let's go ahead and install that and once i click in here then we can see that we receive a successfully installed flask alchemy message and if you do not receive any errors here then you should be fine now let's clean our screen here just a minute okay so now we can go basically back to our pycharm and continue on with the
01:24:37
configurations that we should apply okay so once we install it we can basically go ahead and import that flask underscore sql alchemy so let's make our phone a little bit bigger here and we will basically say from flask underscore sql alchemy import sql alchemy like that and once we have done that basically we can go ahead and create an instance of that class that we have imported now the convention here would be to call
01:25:09
that variable db because this is going to be our database instance and we are going to rely on that in the future so we will type in here db equals to sql alchemy and we will close parenthesis to initialize an instance of that class and once we have done that we need to pass our application as an argument to that sql alchemy class so we will basically type in here at and if you remember that arrives from here where we created a flask instance so it
01:25:40
is important to complete that line by writing in here app now once we have done that basically we can start creating our own classes and later on they will be converted into database table now those special classes that are going to be converted in the future to database table are called models so we are going to create one module that its name is going to be item and we are going to define several columns that are going to be inside our database in the future
01:26:11
so just basically let's go ahead and see what i said with a python code so we will go down here a few lines and we will create here a new class and we will name it item and once i have done that basically i should import from a special class that is going to say to our flask application that this is a model that is going to be table inside our database so this is why i will open up a parenthesis here and i will inherit from a class that is called db
01:26:43
dot model so we will basically start by creating some fields and we will start by creating a field that its name is going to be named because it quite makes sense to describe our items with a name so we will go ahead and type in here name equals to and the way we are going to create a column will be by db.com and you want to close the parentheses so we can understand that we are creating an instance of this column class and once i create this then we should pass in here some extra information in
01:27:15
order to create this column successfully now one of them will be the type of the column that you want to create so we want to make it in string type so this is why i will go ahead and type in your db dot string and i will close the parenthesis here as well now inside the string we can basically limit the amount of characters that we should put in each of our names so i can limit it to 30 characters by basically typing in here length equals to 30. so when i go ahead
01:27:46
and do this basically i am not allowed to create an item instance and describe a name with more than 30 characters and this is something that you want to do because you probably want to avoid the situation where you allow your users to create items with a large amount of characters because this could cause from database to store too much information and you probably don't want to do that so 30 characters for a name should be enough okay so once i have done that i can
01:28:17
basically go outside of our string class in here and pass in here some more arguments right there so one of the first arguments that we want to pass is to describe to that column that we don't want to have null fields so we can go ahead and do that by passing in here nullable equals to false and the next argument that i'm going to specify here is going to allow our names to
01:28:46
not have the same name when it comes to storing a large amount of items so you probably want to avoid the situation where you have two or more items that their name are iphone 10 for example so you want each item name to be unique and you can do that by easily saying unique equals to true now if you remember we also had some more fields that are describing our items in this website
01:29:19
so if you remember from the dummy information that we have generated from that list we also had barcode price and also id so let's go ahead and create those columns as well so i will basically go in here and create price equals to db dot column and that time we want to change our type of column to db dot integer and this will allow our column to store integers and not strings like we did previously so now we
01:29:50
don't have to pass in length for example because this is an integer and so we can also continue on by typing in here nullable equals to false and by the way if you never heard about the null keyword before basically this is just another way to say none so if you saw none from python then you should be fine to understand null as well because this is just quite the same okay so i will delete that from here and continue on creating some more fields now one more field will
01:30:20
be the barcode that we also want to create so it will be db dot column and although it is going to contain some digits i still want to pass it in as strings because i'm not going to do any calculation with this barcode i'm just going to store 12 characters that they happen to be digits so i will go in here and create string and we will just pass in here length equals 12 so each barcode will be 12 characters and again we will type in
01:30:52
nullable equals false and this should be unique as well so we will type in here unique equals to true like that and once i have done that i also want to add one more field that we did not see before and this is going to be like a paragraph that is describing what this item is about so it makes sense to go down here and type in description equals to db dot string excuse me db
01:31:22
dot column and now we will pass in here db dot string and now we probably want to give a huge amount of length in here something like 1024 something like that just because we want to probably describe our items with a nice paragraph so once i have done that i can continue on to nullable equals false and we can create unique equals to true here as well but i am assuming that we are not going to have the same
01:31:54
description for our items if their size are almost 1000 characters but again the best practice will be to create unique equals true and now i also want to create one more special field that is quite required when it comes to sql alchemy now the one more field that you want to create is called identifier and this is a type that is called primary key so this is just a convention column that you should create when you create your
01:32:25
models when it comes to creating models with the flask framework so we will go ahead and do that as well and we will type in here id equals to db dot column and its type will be db dot integer and we will basically go ahead and type in here primary underscore key equals to true now if you not quite understand why i'm doing this basically this is a convention to our flask models
01:32:55
so it can understand the unique objects that are going to be inside our items so it is a must thing that you should do when you create modules with flask okay so there are still some steps left to see that item table within a nice looking database and we need to add several configurations to our application in order the flask to recognize a database so the way that we can do that is by grabbing the app object and adding in some new
01:33:26
configuration so it will be add dot config and basically this statement here is a dictionary that is going to accept some new key values from us so we will basically go ahead and pass in here some new key value and we can do that by typing in here sql alchemy underscore database underscore uri and then we will point it to where we are going to store our
01:33:58
file which is going to be the database file so we can do that by referring this configuration to a sqlite 3 file so i will basically go ahead and type in here sqli3 and this is going to be like a url but not besides it is going to be uri and i will explain the differences just in a second so i will basically type in here sqli3 column slash and we should add two more four slashes here as well and once i have done that we will just give a name to our database
01:34:29
file so it will be market dot db okay so i know this line might confuse everyone here so let's go ahead step by step to understand this so first of first we see this app flask equals to double underscore name that we have created in the very first steps so we use this app object and we add extra configuration so our flask application can recognize its database and the way you can do that
01:34:58
is by adding key values that are considered as conventions so the flask application can understand where the database is located at so the convention will be to create a key that its name is sql alchemy underscore database underscore uri so uri stands for uniform resource identifier and this is different from url that you probably saw everywhere because this is not a link to a website this is why we see the l at the end of this statement this is an
01:35:31
identifier that is just a file that is going to be identified as database and basically the way that flask application wants us to do it is by passing in here sqlite colon three four slashes and then just give a random name to the file that you're going to create okay so once we have configured this successfully then we should go ahead and execute some commands in order to create this actual file and then we can see it visible inside our project directory so i will open our terminal
01:36:02
here and inside our command line we want to enter to python shell because we want to import the information from our market dot py file so i can basically go ahead and type in here python and make sure that you do that in the same directory as your project so you will not receive any errors so once i have done that basically i can import our market.py file like a python module so i will type in here import i mean from
01:36:33
market because this is the name of our python file import db now the reason i want to import db it is basically because i want to take several actions within that db variable that we created previously now once i will execute this you might receive a warning about some of the features that are going to be disabled in the near future but don't worry too much about that this is not an error so you are totally fine if you see this output now i want to split our display a little
01:37:03
bit just to see you the result of what happens when i run the following command so i will basically locate our terminal in here and we'll make it a little bit bigger like that and now i will go ahead and create our database now the way that we can do that is by saying to our shell to create all our tables that we have created inside that python file and if you remember our modules are
01:37:33
what considered as database tables to our flask application so i will run here db dot create underscore all and if you do not receive any errors after this command then you should be totally fine now once i have executed this then you should see the market.db file right here inside our project directory so that means that we have created database successfully so this is quite great now
01:38:06
currently our database is totally empty from information so we probably want to go ahead and create some items inside our database and the way we can do that is by accessing our database like python code so this is what exactly sq alchemy allows us to do so if by any chance you come from django world then you should understand that the sql alchemy is quite like the object relation mapper of django so this is why we work with the sql alchemy okay so let's go ahead and create some items in here
01:38:37
so i will basically import the item model that we have created so it will be from market import item and once i do that then i can basically go ahead and create an item like that so let's create a variable and it will be equal to item one and this will be equal to the item class so we will initialize an item and we will pass in here name equals to phone let's call it
01:39:08
iphone 10 like that and we will also pass in price so it will be 500 and we will also pass in some barcode so if you remember this is a string so i will just create some random numbers in here and we should have 12 characters so this is quite great and we should also pass in description and this will be equal to just let's pass in a short description
01:39:40
now once i enter this then we should be fine now you probably have noticed that we did not pass in anything about the id over here and the reason we did not pass anything about the id it is because the fact that we passed in here primary key equals to true so if this item is happened to be our first item in our database then its id is going to be one and we are going to see that just in a second
01:40:11
okay so let's go back to our shell here and once we have created an instance of item then we want to save our changes to our database so the way that we can do that is by going ahead and typing here db.session dot add and we should pass in here the argument of the object that we have created which is item one and the next line here will be db dot session dot commit and you should close the parenthesis here
01:40:42
like that and this should do the job of saving information inside our database now to verify that you already have one item inside your database then you can basically run a command like the following and the correct command for that will be item.query.org and once i run that then we should see a result of one object that is located inside our database and let's actually show what happens if we create one more item
01:41:12
and commit our changes to our database so we will just type in here item two equals to item and we will pass pretty much the same information like we did previously so it will be name equals to let's type in here laptop and price would be 600 and this time the description again will be just a short description like that and what else we got we have to pass in barcode so let's pass in some
01:41:44
random 12 digits like that and again we can basically go ahead and add this object to our db session so it will be the following command and we can basically run here db.session.com so it will commit our changes and again now i can execute the item dot query dot all and this should display us two items now you may notice how the objects
01:42:16
are defined as the model name space the identifying number that i talked about now this is something that you can actually override and you can give your own customization to the way that you want to see your items when you try to query them by the python shell so let's go ahead and see how we can do that okay so i'm back inside our pycharm and this is as easy as overriding a magic method
01:42:48
that is called dunder or epr now if you don't know what dunder repr is then i have a video on that special magic method and basically you can check my channel out to see the thunder r apr video okay so besides returning the default option that we saw previously we can basically return a formatted string and it will be item and then we will just pass in here self dot name inside curly brackets just to
01:43:20
refer to that variable okay so once i save my changes here then we should load our information again from the beginning so i will exit our shell here and i will enter it back but before i will clean our screen and i will type in here python and i will go here and write form market import db and as well as we will throw market import item and now if i'm executing the
01:43:52
same command like before so it will be item.query.org then you can see the differences from the previous result as we see our objects that they are defined in a different way so this is quite great okay so i just cleaned my screen here to show some more examples now i'm going to show how you can iterate over all of your items for example so it will be four item in item dot query dot all
01:44:23
because this is the exact statement that returns all of our objects and once i iterate over it then we can access each field like the fields that we have created within our item model so it will be for example item dot name and it can be also item.price and it also can be item dot description and as well as item dot id and also item dot barcode now once i hit
01:44:53
enter here then we should see all of our results that being shown like here so just remember that you can access each of your fields like we defined them inside our model okay so if we want to filter our objects by some specific condition this is something that is quite possible as well so let's go ahead and show that but just before let's clean our screen here so we can have a better look like that okay so the way you can
01:45:24
filter by some condition would be by item dot query dot filter underscore by now the underscore by is actually referring to some key value that you want to specify in between those parentheses now let's say that i want to filter by items that they that its price is 500 so it could be basically price equals to 500 and once i click enter then it returns us a base query object
01:45:55
like that now the reason you see this it is basically because you may have more than one result by executing that command so to see the actual result of what this exact statement returns you then you should iterate over it so it will be full item in item dot query dot filter underscore by and again i will just type right in here price equals to 500 and once i do that
01:46:28
then i am allowed to access each of our items that their price are 500 dollars so we can basically type in here item dot name and once i execute this then we can see that we only have one item that its price is 500 and its name is iphone 10. now again just remember that you will receive this result because the filter on the score by can return you more than one option that this condition is actually a true
01:47:00
statement for those objects okay so now that we pretty much understood everything that is relating to modules and databases it makes totally sense to scroll down here and change this dummy information to something else now you could probably guess what i'm going to write besides this long list that we have created so it will be as easy as typing in here item dot query dot all because this will
01:47:32
basically return all the object of items that we have stored inside our database so once i save this and go back to our shell here and let's actually exit from our python shell and execute our server so it will be set flask underscore app equals to market dot py and it will be also flask underscore debug equals to one and we can execute here flask run okay
01:48:04
so in here as you remember those three items are used to be the information that we have passed in as a dummy information now if i refresh it then you can see that it is updated with the information that is stored inside our database and this is the behavior that we want to reach when we want to display some information inside our website so this is totally fine and it works correctly so this means that we have done a great job by creating a database that is
01:48:35
connected to our web application okay so one final thing that i'd like to discuss about is the option to inspect your database in a visual graphical user interface now because we use sqlite 3 as our database engine then we can download a browser that knows how to display information when it is done by sqlite3 so basically you can go ahead and search in google for a db browser for
01:49:06
sqlite and then you can see that it has a lot of options for any kind of operation system so if i'm clicking here for example then you can see that it has download links for mac os and as well as for windows applications but basically this is something that you'll maybe want to do because you want to really have an actual look for what is inside your database so since i'm using windows machine currently then i already have downloaded this software and then i'm going to display you how
01:49:38
you can browse your information in a visual graphical interface so let's go ahead and have a look okay so i will open our sqlite3 weaver and in here what i have to do is only browsing the file of our database files so once i click on file and choose the open database option then i should point it to the file that we have just created and as you can see i'm inside the directory of
01:50:08
our project and what i have to do is just selecting this and click on open now once i do that then you can see that we have in here our tables and we have only one table that its name is item now if we want to see its columns then we can basically click here on that arrow and this will display you the columns that we have created to create this table so you can see that we see all the columns in here and if you want to see the actual information inside
01:50:40
that table then you can go easily by right clicking and click on browse table and you can see here that we have actually stored information and you can see the exact information that i showed you from the python shell so this is something that is optional for me this tool was very comfortable when i developed some flask projects and i really recommended to look up for such a tool that will display the information for you visually so it will make your lives easier in
01:51:11
certain cases all right so now if we take a look to what is inside the market.py file currently we have a model here and down below we have several routes that we have created now we are going to create more models and more routes in the future and so it might be a great idea to have a python file that its name is going to be models.py and also routes.py where we will store all the routes now we are going to spend a few minutes on how to reorganize our
01:51:46
project because it is not going to be as easy as grabbing the models to a models dot py file and import stuff because we are going to end up with a forbidden import and we are going to explain that in a few minutes so let's actually try to split our different flask elements to different python files so i will start with creating a new python file and for sure i will name it modules dot py and in here i will grab our single item module
01:52:17
and i will try to paste it in inside our modules and currently i will allow myself to ignore that db variable that is not existing here and i will go back to the market dot py and i will do the same process by creating routes.py and then i will go back to our market.py and i will grab in everything from here and paste this in over here so we could pay attention that we have several arrows because several functions are
01:52:49
not loaded inside that particular file so how we are going to get out of this so let's first go back to our market dot py now as you know in python when you use the import keyword to import some file then what python does it executes the entire file line by line so if you remember before we actually moved the routes and the models we used to have a market.py file with modules over here and with routes down below
01:53:20
now we could basically go ahead and use here import modules and import routes but we still have to figure out how we are going to give these models.py the db variable that it's missing so again we could try to solve that by moving that line to modules dot py so i will paste this in inside here now we also end up with missing the sql alchemy
01:53:52
instance so again we could grab this in from here and paste this in above here but we are never going to get out of this because there is always going to be something missing in each file and then we will end up with something that is called circular imports now what secular imports are it is basically two files are trying to import from each other and it is
01:54:24
something that is forbidden in python because each file will end up with some missing variables when it tries to load some variable from python memory so in order to avoid this python comes up with something that is named packages now we can basically package our entire application inside a new directory let's call it something like market and then we can create one more python file for example we can name it run execute
01:54:55
start something like that and then that python file will know how to import everything step by step and the only thing that we will have to do is calling that specific file and then that python file will take care of the rest so this is the design that we are going to implement in that video and so by the end of this video every file will be at its own place and everything will totally make sense for you so let's actually get rid of those lines
01:55:25
that i just pasted in over here and revert them back inside our market dot py and then we will remove those again and then now we will basically go ahead and create a package and then we will name it market so let's see how we can do that great so first of all we will go ahead inside our flask market directory and we will create that single file that is going to take care of everything that i just discussed about and i will name it something like run okay so it is going to be responsible to execute
01:55:57
our application and what i will do now is grab everything from our market dot py and i will cut everything from here and i will basically paste this in over here now as i have completed this basically i can allow myself to delete the market.py file because the routes are here and then the models are here so the market.py is quite empty and i can allow myself to delete that so let's go ahead and delete that
01:56:28
i will use the safe delete option all right and our next step here will be to create new directory and move our templates modules and routes dot py into that directory so we are packaging every flask element into a new directory that is named market so let's go ahead and create a new directory here and i will name it market and then we will basically move everything from here
01:56:59
to that market directory so in python that will be as easy as grabbing it and just hovering it inside the market here then you can see that pycharm auto completes me by asking if i want to move some files into that directory so i will basically use the refactor option here and then you can see that our modules for example is located inside the new directory now i will do the same with routes and also with
01:57:31
our templates great and last we will also move in our market.db okay so let's close each file over here so our structure right now is that we have our market directory and we have our run.py python file which is outside of that market directory so let's see how we continue from here okay so if we actually take a look to the lines that are left inside our run.py file they are basically
01:58:03
some initialization lines that contains very important information about our web application now what we must do with those lines of code that are left over here is to move them to a special python file that is called double underscore init now when you work with python packages every python package that is considered as a regular package is going to include one special python file that its name is always going to be double underscore
01:58:34
init double underscore and what is so special with that file is that when you import it then before it loads what you want to import to your file it is basically going to execute that particular file that is named double underscore init double underscore so it totally makes sense because whenever we want to import some objects or variables from our application then we probably want to execute those lines of code because those lines of code are what responsible to start our
01:59:06
flask application so we will go ahead and do that so i will basically go inside our market directory and i will create an initialization file that will be responsible to define this directory as a package so i will name it double underscore init double unscore as i said and i will move in whatever is inside that run that py to that double underscore init double underscore file
01:59:38
now what is so special with the process that we have done until now is that if we are going ahead from our run dot py file and we try to import market then it is going to recognize it as a package because we have included that double underscore init file so if we were to try to import that app variable that we have created then it is going to be perfectly fine because it recognizes that variable from our double underscore init file and
02:00:08
anyway it is going to execute it as a first step because this is why we have that double underscore indeed file and actually the next line that i can allow myself to do here is using app.run and this file is going to be that pointer file that is going to do the rest of the job of importing everything so this is how it is going to work right we are basically going to import our application from market package and then we are going to run it but before we actually try this out
02:00:38
let's add here one more argument and it is going to accept some arguments that we already familiar with and it is going to accept here debug equals true so we don't have to set up those environment variables anymore and one more thing that i'd like to add here as a convention in python is to test out if this run.py file has executed directly now the way that we can check that is by writing the conditional of if double underscore
02:01:09
name is equal to double underscore main and again if you don't know what this conditional is about i have a video on my channel that you can definitely check out what this special if name equals main does but basically it checks if our run.py file has executed directly okay so now let's go ahead to our terminal and try to see what will happen if we execute that run.py file now i know that there is a great chance that we are going to
02:01:41
fail and receive some errors but i want to show you step by step how we are going to overcome those errors now that we have our package set up so i will open my terminal and basically the only thing that i have to do now is going ahead and execute that run.py file now our web application will start and if we actually try to access it then you can see that we receive errors that the root url is not found now that doesn't make sense because if
02:02:12
we take a look to our python then we can see inside our routes dot py that that we have the route for our root url but the reason this fails it is because the double underscore init file does not recognize the routes that we have created inside that route dot py file so our first step here is going to be to complete this dunder emit file by saying from market
02:02:43
import routes and as you remember if we import certain file then python is going to try to execute what is inside that file so now we can go back to our web browser and the test results out now you can see that our web application is probably down right now because we see that this site can't be reached and as you can see we started to receive certain errors about the import so in that route.py file
02:03:15
we don't have the application defined so let's go ahead and fix that so i will go to our python and i will basically type in from market import app and as you can see that app errors are started to disappear but we still have left with the render template error so we can also go ahead and fix it by saying from flask import vendor
02:03:45
template and then we also have one more error that we must fix in here and that will be the import of our models dot py because as you can see we have a line here that says item.query.org and it doesn't know anything about it because it is not a recognized model and i can basically import it like we can import from a regular package in python and that will be by saying from market dot models import item so now we have pretty
02:04:18
much everything set up in our routes dot py and if we have a look inside our models dot py then we still have some errors over here left over so i can basically fix it by saying from market import db because we can import it from our dander init file and now everything should work so we can basically test this up by going to our terminal and re-run our application and i will clean my screen
02:04:49
again and i will try to run that py file again and now our website is up and running and i can basically test if everything works properly and if i refresh it then you can see that we receive our web application as it's supposed to now if i navigate to that market page then you can also see that everything is quite great so this means that everything works great and we have completed our packaging successfully now i know that there was a lot of
02:05:19
information that will probably have to sink in but i hope that the packaging process was clear and you pretty much understood everything about what i have done here so again the main idea was to package everything that is related to market and then having one single file that we basically can execute it and then this file will be responsible to do everything for us now i just realized that i did not specify a lot of times throughout this tutorial that our code is available from the github and you can definitely go
02:05:51
down below to the description and bring the link for the repository that includes the code of that tutorial and you can download it in the way that you like them so you can also use the command of git clone or you can download it as a zip file up to you but basically it is a great idea to go to that link and follow the code that i'm writing throughout this tutorial okay so let's go ahead and continue so i will basically have to deal with a way how i can accept users to our website
02:06:23
and the way that we are going to do that is obviously by storing some information regarding our users in a database so it totally makes sense to go ahead and create a new module and then we will store some special fields like username password and stuff like that that is going to be our columns within that model so let's go ahead and do that so i will go up top here basically i'd like to remain the item as our second module and i will write in top here class
02:06:55
user and it will inherit from db.module like we did in our previous modules and our first column would be the id again so as you remember i said previously that it is a convention and it is a must thing to have that id field because this is how the flask wants to identify each of your objects by their id numbers so i will allow myself to copy this line from here and paste this in as a first line
02:07:27
over there and now i can allow myself to continue and creating some new fields so i will go ahead and create username equals to db dot column and i will make that to be equal to db dot string and i will close this out and it is a great idea to limit our users by saying length equals to 30 so it will be maximum 30 characters per each username and this is something that we want to keep unique
02:07:57
because we probably don't want to let our website users to have multiple usernames that they are the same so unique could be true and we will also specify nullable equals false and just to follow this exact same order like we did previously i will go here and type in nullable equals false and i realize that i missed the comma here so let's complete that out okay so this is our username field and as you know in most of the websites
02:08:29
we also have to provide our email address when we register to a different site so it is also a great idea to have an email field so it will be email address equals to db.column and this time i want to limit this email address as well but i have to raise our limit a bit so if there is a username with a length of 30 characters then it might be a greater idea to give our email address a limit of 50 characters
02:08:59
so there is a lot of space for at email.com something like that so i will also make that nullable equals to false and also unique equals true that is quite making sense and our next field here would be our password now i'm going to name this field a little bit different because we are not going to store passwords as plain text inside our database now doing something like this could lead to a lot of security risks and that is something that is basically called make hackers life easier
02:09:31
to pull some information from your website's database so you'll probably want to avoid this by storing the password not as plain text but besides you'll want to apply some hashing algorithm or some another way that will encrypt that password so even if there is a hacker that is going to steal some password information from your website he doesn't have a lot of things to do with that because it is encrypted so i will name this field by saying password underscore hash and that will be equal to db
02:10:01
dot column and we are going to receive here string again now i'm going to give this length 60 because the mostly used hashing algorithm that flask allows us to use will always convert the passwords to being 60 characters so this is why i'm going to specify here length equals to 60 and i will continue on by saying nullable equals to false and i actually don't have to write here unique equals true because it is totally fine if two people have
02:10:34
the exact same password in our website now this is the password field we still have some more fields to set up for our users and the next one will be the budget now if you remember from the very beginning of this tutorial i said that we are going to apply a budget system for our users so it totally makes sense to describe our user's attributes by one more attribute that its name would be budget so i will go ahead and say budget equals to db dot column
02:11:05
and that time this will be equal to db dot integer and we will go here and continue by saying nullable equals false and we are also going to set a default value when this user object is created now you'll probably want to give some amount of money for your new users to start buying and selling stuff from the market so we will set the default value for that for example to 1000
02:11:36
so the users can at least have 1000 coins at the very first registration attempt okay so it totally makes sense to set up a value like that and one final field that i like to add here before we close up this module will be a field that is going to be related to our items module now what that means it means that we want to allow our users to own several items because this is what this website is going to be about so in database definitions this is
02:12:07
something that is called relationship between a two tables now in our case we use modules because we work with python but we have to use some special field that is called relationship and inside that relationship field we are going to describe several arguments to make the model to understand that the user can own some items okay so let's go to here and write in items equals to so we will type in
02:12:39
db dot relationship like that and we will close our parentheses and the relationship is going to be with our item model so we will say that by writing the model name inside a string like this now continuing from here i am also going to type in back riff equals to and we will open a single code and inside here we will say owned user and what backref does it is basically a
02:13:10
back reference to that user model so for example if we have one user and then we want to know the items that this user owns we are basically going to grab the object of the user and we will access the attribute of items but let's consider a situation that you have an iphone item inside your database and you want to know its owner now you are going to grab the item object and then you will access it by the attribute of owned user and that is because you specify the back reference
02:13:42
of that item so it is quite important to provide this back reference because it will allow us to see the owner of specific items so the last argument that i will say here will be lazy equals true and that is something that we also have to set up here because if you don't set up the lazy equals true then the sql alchemy will not grab all the objects of items in one shot so it is quite important to specify the lazy equals true in that case now i want you to take a look how
02:14:14
this db is not actually a column besides it is a relationship so what that means it means that this is not actually going to be stored as a column when we try to inspect inside our database so it is quite wrong because we also want to store information about certain users that are owning some items now the way that we are going to do that is by saying to our items module which user is owning it so we will go back to our items module and
02:14:45
specify one more column that we must create in order to make this relationship to work successfully so we will go here and we will type in owner equals to db dot column and this will be an integer and the next thing that we want to write here is the relationship to the user model so i will say db dot foreign key like this now what foreign key does it search for the primary key of your model
02:15:17
from the module that is related to now if you remember i said previously that there is a great reason that we have to create this id in here in order to the sql alchemy to understand each row that is going to be stored inside our databases so now if we go ahead and create foreign key we can basically say that this foreign key is going to be related to the other modules primary key so we will say in here user dot
02:15:49
id and this is related to the each unique row that is going to be stored in that id so it is quite important to write here user dot id in lowercase okay so now i'm back at my terminal and i like to create all the tables from scratch inside our database so we will go with python and we will use here from market.modules import db and then we can basically
02:16:21
say db.drop all now this will delete entire information from your database including all the tables so we will say that and then we will recreate everything now i'm doing this just because we want to clean our information before we test new things out but in production when you add a new table you don't always have to delete the entire information basically you could also execute create underscore all but i just wanted to show you that there is the option of drop underscore all as well so now if i
02:16:54
go ahead and create everything then if i don't receive arrows then it means that everything looks great now we can continue by importing the modules so we will say import user and item again from our market dot modules now we can basically try to create a new user to see if everything has worked properly so we will say u1 equals to user and we will specify the username this will be equal to jsc for example and we will write in
02:17:25
password underscore hash this will be equal to just random string of numbers and we will also say email equals to something like the following now if you remember we also have the fields of budget and the owner now i did not specify nullable equals to false on both of those so that means that it should be enough now i guess i missed the email here so we should fix that to underscore address and now we are fine
02:18:00
now let's clean the screen a bit we will say os dot system and we will execute this cls inside here and now i can basically go with db.session.ad and we will add the u1 in here and we can commit our changes by saying dot db.session.com okay so now this should be enough for our user to be stored inside our database now to see this we can basically execute
02:18:33
user.query.all and then you can see that we have one user with the user one statement right here so it means that everything worked great okay so i cleaned the screen a little bit here so i also want to test up the relationship if it works great so we can basically create several items quickly and set their owners to the user that we have just created and see if everything works well so i will go ahead and say i1 equals to an item and i will go
02:19:03
by saying the name equals to iphone 10 for example and we will type in description and we will just write in a short description here and we will say barcode equals to a string like that and we will type in price equals to 800 for example so i just missed up the desk we should create the description like that okay so everything works great and i will go
02:19:34
by saying db.session.ad and i will add i1 and i will now use commit so we will commit our changes now let's repeat ourselves with another item so i will clean the screen here quickly and i can load the previous commands by using the arrow signs so i can basically change this to i2 and this to laptop and i will change the description to description too and the barcode here will be a little
02:20:06
bit different and the price will be 1000 that time and we can repeat ourselves again by saying [Music] like that okay so now we have two items stored inside our database so we can verify this by saying query dot all and now let's try to assign an ownership to the iphone 10 item so we have to go and filter this specific iphone 10 object and we can do that by saying
02:20:40
item.query that filter underscore by and i can filter by name equals to iphone 10 like that okay so it also makes sense to assign this into a new variable so i will go ahead and with item one i will assign it and now if i access item one then you can see that it returns us a base query and now we can basically use this first method to grab the specific object itself so now
02:21:12
i have the item1 object in here and now i want to test up the results if i try to access the attribute of owner and now you can see that it returns us nothing because it doesn't have a owner now to continue from here i can basically say that i want to assign the owner of item 1 to the specific object of the user that we have just created previously with the username of jsc so it will look like something like the following so it will be
02:21:43
item1.owner and this will be equal to user.query.filter underscoreby and i want to filter by the username equals to jsc and if you remember this entire statement here returns us a base object and we have to access the actual object by saying that first and as i have done that then i can continue on to db.session.com and i can assign the item one and now sorry i should have
02:22:16
type in here add great and then i should have continue to commit now as i have done that then we can see a several errors over here now i can see that we have this update item set owner where item.id equals to a question mark now i have a feeling that i know why this happened and it sometimes that always may confuse every one of us and the point is we have to understand
02:22:46
that the only way that we can assign the attribute of owner is by specifying the id of the user so if you remember our foreign key is only going to accept the attribute of id so this is why we have done a great job by filtering the specific user but only we had to give it the attribute of id so let's go ahead and fix that so before everything let's clean the screen for a minute so it will be cls inside os dot system and before i actually take different
02:23:18
changes inside our item one we have to execute this command which is going to look like db.session.rollback so we can roll back our previous changes and commits and once i execute that if i did not receive any errors then it should be fine and now i will just type in the exact same command that we wrote previously so it will be item1.owner and it will be query dot filter underscore by
02:23:48
and we will filter by jsc and after the dot first in here we have to give it the attribute of id and once i have done that then i can basically add it to our session which is clean because we have rolled back the previous commits and now we can try to execute the commit and this should work so if i was to go ahead and see the owner then you can see that it returns us
02:24:19
one and the reason it returns as one it is basically because this is the foreign key of the owned user now we can also test this by filtering the item specifically so we can go with i equals to item dot query dot filter underscore by and we want to filter by name equals to iphone 10 like that and now we can basically try to see the back reference of the item that i talked about so if you remember we had that
02:24:51
backref attribute set up so if i was to go ahead and execute i dot owned user then we would receive some errors because again i missed the dot first in here and now i can run in on user then you can see that it returns us the actual user that owns this item so this is quite great and this is a great achievement that we have done until now so so i hope you understood everything about how relationships of databases
02:25:24
working because it is quite important to be aware of that situation so this is the actual idea of our website right we want to own items as users inside our web application okay so previously we have created our user module but we currently don't have any special way to create users to our website besides the only way to do that will be by our terminal and we are probably looking for a way to customize a nice looking html page for our customers so they will have the ability to
02:25:56
register to our website so the way we can do that is by customizing an html form now we probably want to make this form smart enough to check certain things to see if this information is valid so for example you can't create a user if there is already a user with the same name or if your password linked does not meet the requirements of your website or anything else that is quite dealing with validating stuff when it comes to
02:26:27
register to a website so in order to create our forms to register smart enough flask delivers already a built-in package to create phones and this also allow us to display it nicer on our html templates so in order to start working with this we need to go ahead to our terminal and install some packages so this is why i will open my terminal here and i will basically type in some pip install commands so the first one will be pip install
02:26:58
flask dash and this is the first package that will allow us to create nice looking forms and then later on to display them on our html templates so i will clean the screen here and our second package will be pip install wt forms so you can see that it is already installed probably this was a secondary package under the flask wtf so anyway just write this command as well for safety and let's continue from here okay so as i said previously the forms
02:27:31
are going to be a quite different element in our flask application so this is why it totally makes sense to create a python file that we will name it phones.py and then each form that we are going to create for some situation will be stored there so let's go ahead and do that so i will go under my market directory and i will create a new python file we will name it forms and here we will write our forms that we want to display them on our html templates
02:28:02
now the way that this is going to behave is quite similar to models because we are going to create classes and then we are going to create some fields inside our classes and then that way those fields are going to be the required fields for our customers that they have to fill in in order to register to our website so let's go ahead and do that but the first step is to actually import those libraries that we have just installed in order to create those forms so i will basically
02:28:33
go with form flask underscore wtf import flask form and then we also want to import some special fields that are going to be recognized by a special type of field so for example we might have an integer field for our users if we want to ask them about the year of birth or we might have a string field if we want to ask them about their name so this is why we should go ahead and also import the special fields by saying
02:29:05
from wt form import string field now we can also go ahead and import more types of fields but currently we will only start with the string field okay so we will start by creating our register form so it is going to be by saying class register form and this will inherit from the flask form class that we have imported over here so this is why i will type in here flask form so the next thing that i will do here is creating some fields
02:29:37
that they are going to be recognized as our form fields so i will start by creating a username field because it totally makes sense to register our users to ask for a username so it will be equal to string field because this is a string and then there is a convention to give a label for each of our fields so i will provide in here label equals to username and i think that will be it for the username field now we are also going to ask the email
02:30:07
address from our user so i will go ahead by saying email underscore address equals to the string field again and that time i will label it by email only so this should be enough now i am also going to create two different fields for our passwords so it will be password one and also password two now the reason you want to do this because mostly in each website you see a field about the password and also about the confirmation of that
02:30:39
password so this is why it makes sense to create two separated fields and then later on we are going to write a validation that is going to check if password one is equal to password two so we can submit the register form successfully so to create this a string field is not considered as a best practice because the wt forms has a dedicated field for password fields so i will go here and i will import it by saying password
02:31:11
field and then i will create it as a password field over here like that and i will close the parentheses and the same will be for the password tool as well so i will create it as a password field now let's give it their labels as well so it will be password1 for the label of that and for the label of password2 it will be password2 alright so now that we have created those fields we also have to create the field that
02:31:42
will allow the users to submit their actual information now when you see some forms not only you'll see areas where you have to fill in some information but you also see a button that you have to submit your final information so this is why i will create a field that is going to be by the type of submit so i will go to our second line here and i will import that submit field and then i will create one submit field so it will be submit equals to submit field
02:32:13
and again its label is going to be submit so i think this should be enough for now for our registered form later on we are going to go back to that register form to write some validations in order to make our form more secure okay so now it is a great idea to import this registered form class from our routes now we currently don't have any route for our registration page so let's go ahead and create one so i will go to my
02:32:44
routes dot py and i will zoom in the phone here and i will start creating a new route for our register page so it will be at act dot route and i will navigate our users to forward slash register and then we will create this register page route by calling this function register page now the first step here would be to import that form from the forms dot py so i will go up top here and i will
02:33:16
import it by saying from market dot forms import register form and inside that function i will basically use the register form class to create one instance of it so it will be form equals to register form and i will close this up like this now as we have completed that we have to look up for a way to display the fields of that phone inside an html page now the way that we
02:33:47
can do that is for sure by rendering a template with the name of register for example and then we can pass as information our form instance so we will say here return render underscore template and then we will send our users to a template named register.html and i know that we did not create it yet but we will do it very shortly and the information that we want to send to that template will be that form instance that we have
02:34:17
created here so it will be form equals to form and i think that will be enough for this stage and now let's go ahead and create this register.html template so it will be here and i will basically create a new html file we will name it register and then we will replace it with some html code that is going to be responsible to display that form in a very nice way now i will delete the auto generated
02:34:47
html and i will start by for sure extending our base template so if you remember we have our base template that we have to inherit when we create a new template so it will be curly brackets and then the percentage signs and then the closure for our curly brackets and between those we will type in extends and then we will extend our base.html now as i have completed that we have two blocks that we should use and then
02:35:18
contain some information inside there so if you remember we had inside our base dot html a blog title and also a blog content so i will copy the blog title and i will paste this in and i will also copy the blog content and i will paste this in as well now let's fix the indentation here a little bit and we will continue from here now if you
02:35:48
remember in the blog title we are allowed to provide information that is going to be displayed as our tab names so it makes sense to type in something like register page and in here let's actually give a random information currently to test if everything works properly so i can validate myself by only writing some basic html code so let's write in here register form inside the h1 tag all right so we have one more step to complete before we can go ahead and actually test this out
02:36:19
and that will be to create a special secret key that is going to be identified as the secret key of our flask application now the main reason that you want to do that in this stage it is because if you go ahead and test the form out right now nothing is going to show up because when you create forms in html you actually have to provide one more security layer in order to show this form up and that is simply because we change our request type to our clients so until now we were able to display
02:36:51
html pages for our clients but when it comes to forms now our clients are going to be able to submit actual information towards our database so this is a quite different action that must be secure enough so this is why we have to create a secret key for our flask application so the way that we can do that is by generating some series of characters that is going to be used as our secret key so i will open our terminal and i will
02:37:23
go inside python and i will import the os library because simply we can generate there a hexadecimal random characters so it will be by import os and then we can basically go ahead and say os dot u random and then we can provide here the value of 12 so it will be by the value of 12 bytes and then we can basically go ahead and convert this to hexadecimal values and then the value that we'll be
02:37:52
receiving back would be the secret key that we auto generated for our application now there is nothing wrong with going ahead and generate more secret keys but just make sure that if you use one then stick to it throughout the development of that application so let's grab this secret key and go back to our python and navigate inside our init.pi and then here we have to write in some new configuration so it
02:38:23
will be app.config and then our key here will be secret underscore key and if we paste this in right there and this should be inside single quotes as well then this should be enough to display the form that we just created so i will go back to my terminal and we can exit the python shell now and we can basically execute our application with python run.py and then we can navigate
02:38:54
back to our website and try to see what will happen if i go to fort slash register and then you can see that we have our page up and running so this is quite great now one more thing that i like to do before we continue is to actually configure that navbar button where we can click on it and then this will lead us to the route of the register page so if you remember previously we learned about the url underscore 4 built in so let's go ahead and configure
02:39:25
that so it will be as easy as going to our base dot html and identify that register page which is right there so this is the anchor tag for our register page and if you remember from previous examples for example for the home page we use this built-in url for function so i will allow myself to copy the exact statement and paste this in inside our href attribute and then this could be
02:39:56
changed to register underscore page and now we can test this out by refreshing our page and for example navigate to our four slash home and we can click on slash register then you can see that it works great so now we can continue on customizing that form okay so i'm back in my register.html and in here you could notice how i deleted the code inside our blog content now inside the content we are going to
02:40:26
put the form itself and the way that we can access the form instance is referring to the variable that is passed from our route with jinja syntax so it will be by saying form within double curly brackets so just to check if this works properly we can basically navigate back to our website and see what happens if we go with fold slash register then you can see that we see the object itself of the form so this means that we can access the
02:40:57
form itself now to access the actual fields and to visualize them better we are going to take some different actions in here so we have to create the form tag which is a built-in tag in html syntax and we also have to specify some more attributes in order to the form to work successfully so one of them will be the meta type now i did not talk about request methods before but basically when it comes to websites you have a lot of request methods that
02:41:28
the clients can provide and the most known request method will be the get method where clients are requesting to display some information on different web pages but there is also one more different request method that is called post and the post request is a kind of request that is going to affect the database of your website so since this is a critical action to take as a website client then you have to specify that the method
02:41:59
is going to be post so it is important to provide this kind of information in here and i will continue on by saying class equals to form dash register and the last attribute in here will be the styling so we want to style our foreground color to white so it will be color column white so i'm doing this because we are working on dark mode and it is quite important to have the foreground color
02:42:29
set as white okay so inside our form tag we can basically refer to our form fields by saying so i will open the curly brackets one more time in here and i will first call the label of our form fields and then i will call the field itself so you will see the effect of that just in a second so i will say form.username dot label and i will open and close the parenthesis here
02:42:59
and below that we can say form dot username and i can open the parentheses and close them up here again now what is so special with that flask forums is that this statement is going to accept attributes like in real html code so we could say here class and then we could basically give it a bootstrap class so i will say form dash control so it will be responsible to display that field a little bit nicer
02:43:30
and we can also give it a placeholder so our clients can understand that this field is designed for providing the username so we can say first of all let's add a comma here and we can say placeholder equals to user name like that and let's see the actual results of a code like this so if i'm going to our web browser and refreshing that out then you can see that we see an empty field where we can provide some
02:44:02
information now i know that this looks quite ugly and in most of the websites the information of filling a form is starting not from the left position so we can fix that by containerizing those fields inside one more special html field so let's go ahead and do that so i will open our pycharm and in here we can containerize our
02:44:32
form inside div tag so i will allow myself to type in here the class container so i will allow myself to paste this form inside those div tags and let's fix the indentation here a little bit and then let's test out the differences so i will refresh this out now you might be bothered by the results from that username in here but this is something that we can change in our forms dot py so this is the
02:45:04
label of our username field so we called basically open our forms dot py and we could change the label so now you can understand what the label does it basically gives a kind of secondary title for our fields so we called say here user name like that and we could also change that to email address like this and we could also add here password like the following
02:45:36
and we could also change this to confirm password like that so it makes a lot of sense to display the label of our password tool as confirmed password because it probably looks nicer to our clients so let's see the results of that so if i refresh it then you can see that we have a nice secondary title for that field now the way that we are going to continue is going to be by copying and pasting those form labels and the form fields itself
02:46:08
so we can basically copy and paste ourselves four times and we can change this to email we can also change that to email as well and we can change the placeholder to email address like that and we can do this for our passwords as well so i will paste this in over here and this will change to password one and this is going to be changed to
02:46:40
let's scroll down password in here and this is going to be password one as well great so now i can duplicate this one more time and we can change this to password tool we can change this to password two and this will be confirm password now to test the results of that we can refresh it you can see that we receive an error and that is fine because
02:47:11
we defined the email field as email underscore address so let's fix that quickly so it will be underscore address and underscore address as well now you can see that i trained to not cut the arrows that i received throughout this video sometimes because i really want you to be aware of the possible arrows that you can meet throughout the process of writing any html code or any python related code so this is the reason that i'm okay with the arrows and handling
02:47:44
them on the fly okay so i will refresh that out then you can see that we receive a lot of nicer form in here now i want to give a nice image for this form and i also want to give a h1 tag so the users can see a nice big title now the code that i'm going to paste in here you can find it from my website because i put all the code snippets in the flask tutorial section which you can find in my courses so i will paste it in over here and
02:48:16
you can see in the first tag here that i have an image tag which is going to be responsible simply displaying the logo of my website and the h1 tag in here that is going to say to our users please create your account so let's just fix the indentation in here and i think this should be it and i also want to add here a break line tag so we can have a separation between our header to our fields
02:48:47
okay so if we test the results then you can see that we have a great result where we see the logo of my website and we also have a nice title now it could be a lot better if we could centralize these objects so this is something that we also can apply and the way we can do that is by going in here and overriding the body tag of our html
02:49:17
file so i will allow myself to make the font a little bit smaller here and what we can do here is basically wrapping the entire div with a body tag so we can say here body and then we can basically use the class of text dash sender and we can close this out and we can move the closure of our body to the very last line just above the end
02:49:49
block and now if i refresh that out then you can see that we receive a nice looking form where everything looks pretty clean in my opinion now there is one more thing left that is remained to close out this form and this is the submit field that is missing in here so we can basically go back to our register.html and we can add it in here so i will call the ginger syntax in here by using the double curly bracket
02:50:20
and i will call the submit field so it will be form dot submit and now in here we can provide some bootstrap classes as well so it will be class equals to and then we will type in the classes that we want to include to customize this submit button a little bit better so it will be btn and i will type in btn-lg which will responsible to display this button larger and i will also say btn-block and this will expand the button to the entire forum and i will also type in
02:50:52
btn-primary so this should be responsible to display the button in a nice blue colored version so i will save this out and i will also add in here one more vr tag so we will have a nice separation between those and okay so now we can basically test the results by refreshing this page and now you can see that we got the submit button but we have the annoying submit text with all the lowercase now this happens because of the labels
02:51:25
that we have created for each of our field again so we should change this to something like create account and once i have done that then i can verify myself by refreshing it now you can see that we receive a nice button for the create account now nothing is going to happen when i click on create account and when i fill in some information and actually this is something that we have to handle in a separated way inside our routes.py and we will do that
02:51:56
very soon all right so until now we were not able to configure the behind the scenes actions of what happens when we create the create account button now to do this we have to go to our routes.py file and then we have to go for the route where the register form is located and then write some pure python code over there so to do this i will open my python and in here i can basically handle what happens when the user submits on
02:52:28
the create account button so the best practice in that case will be to start by this conditional so it will be if form dot validate on submit now there are two main reasons that you want to execute this conditional before you actually go ahead and submit changes into your database okay so the first reason you want to execute that is you'll want to verify that those comments that i'm going to write in here are only
02:52:58
going to be executed when the user is submitted on that button so this on submit part is actually checking if the user has clicked on the submit button of that form and the second reason you want to execute this it is mainly because we are going to write some validations that are going to check for certain requirements before this form becomes valid so i'm talking about conditions like you see in real register pages in real websites for example your password
02:53:29
should be matched or your user name should not contain more than 20 characters and stuff like that so this is why it is very important to execute this conditional in here and once this returns true then i can basically go ahead with user to create like that and i will make that to be equal to an instance of user and it is a great idea to import it from the market.models in here so i will basically add a comma and i
02:54:01
will import the user and once i have done that then i can basically give the arguments that are required to create a user so i will start by saying username equals to and in here i actually want to provide the value that is received from the username field within the form so i can do this by saying from dot username dot data so this is the way that we are going to pass our fields from the form and i will
02:54:31
continue on doing this with the email address as well so i will say email underscore address equals to form dot email underscore address dot data and i will perform the exact same action with password so it will be password equals to form dot password one and in here i'm passing password one by purpose and you will see in a few minutes why i am doing this so i will say that data in here again
02:55:02
okay so this should be enough to create the instance of our user and once i have done that then i can basically execute the same commands to submit the changes towards our database so it will be db session dot add and i will pass in the argument of user to create and i know that we did not import the db variable in here so it is a great idea to import it now i will go down here and
02:55:32
i will say from market import db now the reason i can import it directly from the market package it is mainly because it is located in the under init file so i don't have to go inside dot something okay so it is quite great to import it that way and now i will go back to our route and i will say dot db.session.com and this will save our changes to the database and once we have done that then we probably want to redirect
02:56:05
our users to a different page now it quite makes sense because now they are registered to the website and now we can show the user the items that are available on the market so i will use the built-in redirect function that the flask package offers us so i can go up here and i can go for that line and i can basically import the built-in function which is called redirect and i will also import the built-in
02:56:36
url underscore four function that we used previously in our templates so we will go down here and we will see how we can redirect our users to a different page after the user is clicking on the create account button so i will go right after our commit command and i will say return redirect and in here the redirect function expects for an hard-coded url now if you remember previously in that tutorial we said that it is not
02:57:09
a great idea to give arguments as a hard-coded urls so besides doing this i will say url underscore form and i will give the url underscore for the name of the route itself so it will be market underscore page and this should send our users right to here so it is quite great okay so we can just test this out by going back to our chrome browser
02:57:39
and refresh that out and then now let's try to create a random account and see what happens okay so we will say here jsc 2 for example and we will fill in some dummy email and i will just type in very basic password and i will try to create account now you can see that we receive method not allowed and actually there's a reason that i wanted us to see this message because it is quite important to apply the step that i'm going to talk about now when it comes to web requests we
02:58:11
said that we have several request methods and we should allow our routes to handle post requests and the way that we can do that is by customizing the decorator of our route function so i will go right here and i will say methods equals to and i will open here a list and i will insert two elements and i will give get and i will also give post okay so it is important to apply this step so our
02:58:42
route could handle post requests and before we continue sorry about that but i think that we mismatched this line in here and this should be password underscore hash equals to form.password1.data so make sure to fix that before you continue alright so once we have enabled the post request in that route then there is one more important step that we have to configure before we test this out now when you send information from client to a server
02:59:13
then it gives a huge opportunity to the hackers out there to steal that information and one of the known malicious attacks is called cross site request forgery and this attack is basically just a way to steal or perform actions against your database that are unwanted and to protect our website from such an attack flask delivers us a very easy future to apply a protection so the way that we are going to do that is as easy
02:59:44
as going to our register.html and right under our form method post html tags we are basically going to say so we will open our curly brackets to refer to ginger syntax and we will easily say form dot hidden underscore tag and what this is going to do it is going to protect us from the attack that i was talking about by generating some token that is basically again just going
03:00:16
to protect us from such an attack and okay now we can save that file and once we have completed this let's actually test if our website is up and running and we will now go to our website and we will navigate to our register page and we will try to create a new account so it will be jc2 for example and we will try to provide in some random email here and we will try to fill in some password and now if i'm going to press on create
03:00:46
account and going to be redirected to the market page then it means that the user has been created and if i click on that then you can see that this is the exact result so that means that we have created this account and we can test this by easily going to python shell and type in user.query.org and this will be responsible to give all the users and we probably will see the jsc tool account that we have just created okay so although now we have the ability to register
03:01:16
users we did not set up any special policy regarding to how we want to register our users and what i mean by that is you saw previously how i created a user with a password that only contains six characters and we did not even write a python code anywhere in our project that verifies that the password and the confirm password are match so this is very wrong when it comes to web applications and not secure
03:01:48
and actually this is a huge bug now to solve this we can basically write in some validations to solve that problem and then those validations are going to be executed before the form is submitted and the way that we can do that is by the flask validations package that is offered by the flask itself so let's go ahead and try to apply some validations to see that the data that we are receiving is actually
03:02:19
valid so i will make the font a little bit bigger here and i will say down here from wt forms dot validators and in here there are a lot of built-in classes that are going to check for certain validations so let's say that we want to validate that the username length is maximum 30 characters and minimum two characters so we can do that by importing a built-in class that is called linked
03:02:51
and now once i have done that then we can go inside our username field and we can call the validators argument and basically we can say that we want to validate the length so it will be length and then i will open the parenthesis here and i will say minimum equals to 2 and i will also say max equals to 30. so what this line of code does it basically
03:03:22
verifies before the submission that the username value includes between 2 to 30 characters and we can write more validations like that in each of the fields that we want so let's say that we want to apply the exact same step for our passwords so it will be as easy as going to our password one field and say valley datos again and this will be equal again to a class of length
03:03:52
i mean an instance of the length class and we can now provide here minimum equals to six and i actually don't want to set a maximum value for our passwords because if our users want to have a huge password then it is quite okay now we could copy the exact validation to our password tool as well but we probably want to avoid that because if this validation is going to be executed on password one then we probably don't need to execute it again on our password too
03:04:24
because we want those fields to be matched and as i said that how we are going to verify that password two matches password one well the way that we can do that is by importing one more class from the wtforms.validators and we can basically check if password2 is equal to password1 when the form is submitted so it will be as easy as importing the equal to class here and go to our password
03:04:56
tool and say validators equals to equal to and then in here we will pass in as a string our field that we want to verify that it's equal to so it is password one and it is quite important to write this down because that is what is going to verify that the password and the confirm password are match now if you remember the password too is the confirm password and you can
03:05:26
memorize this because we have this label in here so this is actually a very important validation okay so some more validations that we want to provide in here is probably to check if the ad sign is located in the email address and the way that we can do that is also as easy as importing the email class from the validators and we can just say validators equals to email and this is easily going to check if the
03:05:57
given value in the email address is actually an email address and one more thing that we can do with the validators we can basically give one more validation to each field and it will be as easy as converting the validator's value to a list in each of our fields so let's go ahead and do that we will just add square brackets in the end and in the beginning of each our values so i will do that in here and i will also do that in here and i will do that
03:06:29
in the password too as well now there is one more reason that i have done this because we also want to verify that each of our fields are filled in with some information so i can basically import the data required class here and i can add one more validation by going here and press comma and now we can type data required and close this up like this and we probably want to copy and paste the same validation for each of our
03:07:01
fields because we want them to be filled up so i will copy this out and i will paste this in in here and as well as in here and also in here and i will just go back to here and i think we are pretty much done with all the validations that we want to apply okay so now that we have completed this let's see in our routes dot py how we are going to handle those validations so we will open
03:07:32
our routes dot p y and we will zoom in here a little bit and down here we want to check if some of the validations are failing or not so for example let's say that we had a user that provided a username with only a one character well in that case it is quite obvious that