Python Flask Tutorial: Full-Featured Web App Part 9 - Pagination
31:21

Python Flask Tutorial: Full-Featured Web App Part 9 - Pagination

Corey Schafer 04.05.2018 172 747 просмотров 4 101 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Flask Tutorial, we will be learning how to use pagination within our application. Pagination allows us to only load a select number of items at a time so that our application doesn't get bogged down. We will also learn how to display links to different pages at the bottom of our page so users can quickly navigate to the page of their choice. Let's get started... The code for this series can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Flask_Blog The JSON for the posts I created can be found here: https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Flask_Blog/snippets/posts.json ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python #Flask

Оглавление (5 сегментов)

Intro

hey there how's it going everybody in this video we're gonna add a little more functionality to our application and to our post so we're going to add some pagination so that we aren't pulling down too many posts at once and also we're going to learn how to sort posts by newest to oldest so let's go ahead and get started so first of all since we're going to be working with pagination I'm going to take a second to add more post to our current application from a variety of different users that way we have enough post to see what the pagination looks like so I'm going to fast forward through this so that you don't have to watch me enter a lot of different data now if you'd like to follow along then you could create some additional posts of your own you only need about ten or so to see this in action and also leave a link in the description section below to the JSON of my sample post that I'll be creating here if you want to use those sample titles and content that I'm going to be using in this video so I'm going to add some new posts now and pick up the video when that is complete okay so I have

Pagination

added some sample post to our application and should have a total of 25 now and we can see that if I scroll down through these so I'll scroll all the way down here towards the bottom then it's kind of a lot of information to have on a single page now if these posts had images included in them and things like that then loading them all in at once like this could really slow down our application it would be better if we could paginate this so that we can load a certain number of posts on one page and then display links at the bottom of the page to the other pages of the post so luckily flask SQL alchemy makes this easy for us with the paginate method so let's open up our routes and see how we can get this to work so I'm going to pull up our application here and I already have my routes that py file opened so we can see that currently in our home route we're simply doing a post query all to get all of the posts but we want to paginate these so in place of using the all method to run this query we can use the paginate method so let me run this in the command line so that we can see what this looks like so I'm going to pull up my command line here and shut down our development server using control-c then I'll clear the screen and I'm going to start up our Python interpreter so now let's import our post model so I'll say from flask blog dot models import post and now let's see what this paginate looks like so let me clear the screen here and we've currently been doing it queries like this so we've been saying post is equal to post query dot all and then we can loop through the post by saying for post in posts and then let's just print that post so we can see here that we get all 25 of the sample posts that I added but now let's see what we get when we do a post query dot paginate so I'm going to clear the screen here and I'm going to go back to where we did our query and instead of using dot all I'm going to use dot paginate and now let's look at this post variable so it says that this is a pagination object now let's see what attributes and methods this object has so if we use the dir function then it will print all of these out so if I run that then we can see here that there aren't very many and some of these are hard to read because they get cut in half off the screen but we have hasnext has previous items page and things like that so this is an object that gives us information about the current page that we're on how many posts there are per page and all kinds of information so let's look at the per page attribute so I will say post dot per underscore page and we can see that results in 20 and 20 is the default per page since we didn't pass anything in so if we look at the current page so I'll say post dot page and we can see that the current page is 1 so we're on the first page so we'll look more at these attributes and methods in just a second but the important one here is the items for this page so to print out the individual posts like we did before we can now say for post in post dot items and then we can print out the posts and if we were to count up these posts then we would count that there are 20 of them here and the last five or on the second page now if we wanted to get that second page of items then we could run the same query again but specify the page being equal to two so I will hit up until we rerun that paginate query and let me clear the screen here so we're rewriting that paginate query but instead let me pass in an argument of page equal to two and run that and now let's rerun the loop where we're looting looping through the items so if I look through those and print those out then we can see that we only get five posts and that's because this is the second page so that first page has 20 posts and then this second page only has the last five posts now if 20 is too much then we can actually get fewer per page if we wanted to so if we reran the query so instead of passing in at page equal to two I'm going to pass in a per page equal to five and run that and actually let me clear this out so it's a little easier to see and I'll rerun that query where we have five per page so now let's see what page we are currently on so we can say post dot page and we're currently on page one and if I print that first page so I'll loop through those so I'll rerun a loop and print out the post for those items and we can see that we get five values and these are the first five posts that are returned now I can pass in a page equal to two to get the next page of five so if I rerun this query and pass in a page equal to two and now if we check the page and we can see that we're on the second page and if I loop through these again and print those out then these are five different posts now if we wanted to see the total number of posts and all of the pages then we can use the total attribute so if I clear this if I say post dot total then we get 25 okay so now let's go back to our app and see how we can use this so I will go back to I'll stop py file so now let's actually use that in our application so instead of doing a query for all the posts we're instead going to do a paginate and use the paginate method and we'll set the number of post per page equal to 5 that way our pages don't get too crowded so I'll say per page is equal to 5 and right now this will always get the first page of posts since we're not specifically asking for a specific page and in order to get other pages we'll do this by passing query parameters in the URL and we've seen that earlier in the series when we did the login redirect query parameter so to grab the page that we want let's just get that from a query parameter in the URL by saying page is equal to and that is request dot args dot get and we want to get the page and also that is an optional parameter in the URL so let's also set a default and we'll set the default page of 1 and let's also set a type equal to int and setting the will cause our site to throw a value error if someone passes anything other than an integer as a page number and now we can pass that page into our query by saying page is equal to page and then we'll just keep that per page of 5 there okay so now let's also make a change to our home HTML template so I'm going to open my templates here and open this home dot HTML template and instead of saying for post in posts remember that this is now a pagination object and instead we have to say for posts and post dot items okay so now let's save all of this and see if it works in the browser so I've saved these files and now let me open up my command line here and I'll exit out of the Python interpreter and now I will run the development web server by saying Python run PI open this up in the browser okay so I reloaded the home page and if I scroll down then we can see that I only have five posts on our home page now we don't have any links to get to the next pages but we'll fix that in just a bit but for now if I manually pass a URL parameter then we should be able to see the other pages now this might be hard to see but in my url bar here I can pass this URL parameter by saying question mark page is equal to two and if we run that then we can see that now we get the next five posts so this should go all the way up to page five so I saw if I typed in page five here then we can see that I have a latest post down here at the bottom if I type in a page six that we can see that is not found because that page does not exist so I'll go back to our home page now so now let's update our template so that we can see the links to the other pages now just to demonstrate how these links look I think I'm going to want a lot of pages to link to because right now we're only going to have five pages and I'd like to have a lot more than that so in order to get a lot of pages just temporarily I'm going to temporarily change our per page argument here and I'm going to change that from five to two and save that now that should give us around let's see I think thirteen pages of two posts and I'll change that back to five after we have everything working and just to show how this is going to work let me jump back to the command line again and I will close down our terminal there our development server and I'm gonna rerun the Python interpreter and now let me import the post model again so I'll say from flask blog dot models import posts and now let's do a another pagination query and I'm going to run a query where we're on about page six of those thirteen pages so I'll say posts is equal to post dot query dot paginate and I will say that we're on page six and that will be a per page of two so now let me clear the screen here and now I'm going to see what is printed when we loop through this method called it err pages so I'm gonna say for page in post dot it err underscore pages and then I will print out that page variable so this may look a little strange but it prints out a one two and then a none and then four through ten and then another none value and then twelve and thirteen so you may have seen on websites before where if there are a lot of pages the website will just show you what page you're currently on and then a few pages before and after with an ellipses or something like that and that is what this none value represents so this will make a lot more sense once we actually render this and our template and we see what this looks like but basically these numbers that is showing here will be links to other pages that we can navigate to now I personally think that this is too many links here and we can narrow this down by passing in arguments to the inner pages method and we can specify how many pages we want to see at the beginning and the end as well as how many pages close to the current page so let's add this code to our template and this will be more clear so I'm going to open back up our home HTML template and below our post I'm going to add another for loop to loop over these pages so I am going to open up a for loop here and also close this this for loop will say for page num in post dot itter underscore pages and then inside of this loop will create links to these pages and remember there can be none values here as well and we'll just display those as ellipses so we'll say open up a code block here and say if page num then we can end this if statement here and let me also indent this where it's obvious that we're inside the for loop and I'm also going to want an else statement for this if so I will say else now if page num then we want to put a link to that page number but if page num is none then it's going to fall down here to this else statement and that is where we will put the ellipses but if a page num is not none then we want that to be a link to our page and we can add that by saying that we want an anchor tag and this anchor tag can link to and I'm going to put in double curly braces here to put in some code and we want to link to the URL for the home page and we also want to pass in the page equal to the page num that we're currently on and we want the text for this link to be double curly braces again and pass in that page num and let me also add some classes to this anchor tag as well so that this looks a little nicer so I will add some classes here I'll add a class of button and also button outline - info which is a nice bluish color and will also give these a margin to space them out a little bit so we'll do an MB - 4 and save that ok so if we save what we have and reload this in our browser so I have everything saved I'm going to exit out of the Python interpreter and rila rerun our python development server and pull up our website here so if I reload our

Testing Pagination

home page then we can see that we only have two posts per page and the reason that I did that is so that we'd have 13 pages here and now I'm going to go to page 6 so we can see that these pagination links are working down here in the bottom if we click on one of these pages then it goes to that specific page up here in the URL we can see that it is passing in a page parameter of page equal to 13 this is page equal to 2 and 6 now we can see down here at the bottom it's giving us a lot of links to a lot of different pages and the reason that the ellipses are useful is because if we had hundreds of pages then we wouldn't want to display hundreds of links we'd only want you know some at the beginning and also some around our current page now I personally think that this is too many links but like I said we can customize this by passing in some arguments to the inner pages method also it'd be nice if the current page had a different style so that it was more obvious what page were on because right now we're on page six but we can't really tell just by looking at this list here so let's go add those changes and we will add those to our home template so I'm back in my home template here and down in our inner pages loop and now let me pass in a few arguments here to it err pages so I'm gonna say left underscore edge is equal to one and that is how many will show up on the far left of the links I'll say right underscore edge is equal to one and that's how many pages show up on the right side of the links so I'll also say left underscore current is equal to one and that is how many pages left of the current page will show up and we'll see what all this looks like in just a second and then I'll also say write underscore current and I'm going to set that equal to 2 because the write current includes the current page so that should limit how many links are actually showed at the bottom of the page and also let's add another conditional to style our current page a little different than the other links so we can come down here into our for loop and I'm going to paste another conditional here within this if page num so if we have a page number then I'm going to put another conditional and say if posts dot page which would be the current page is equal to the page number then we want to style that link a little differently but we also have to put in an else statement here and also end that if so I will copy all of those and put those in so let me copy this link here and also put this into our else block of this if conditional and now if the page that we're currently on is equal to the page number in our loop then we want this to look a little different so I'm just going to have that be a filled in button so to do that in bootstrap the button outline info will be what we saw earlier that outlined a bluish color if we take away the outline part and just do button - info then that will be a solid blue color so that should be good for filling in our current page okay so now if we save that and reload it and our browser so let's make sure our web server is still running and it is and now let me reload page six here and if we go down to the bottom we can see that now page six is filled in so it has a different style than the other pages and you can also see that we don't have so many links down here at the bottom anymore we only have one on the left which is that left edge one on the right which is that right edge and then shows one to the left of the current page and one to the right of the current page so that's a lot better and if we wanted to see what this looked like in different conditions then we can just click through and see what different pages look like okay so

Post Order

now the pagination is done so now let's change the post per page back to a higher number so that we don't have these two posts per page like this because that's just too few so I'm gonna go back to our routes and I'm gonna change that per page and set that back equal to five because I think five post per page is usually pretty good okay so now that pagination is complete let's add another useful feature so if I navigate to the first page of our web app and reload this then for those of you who have followed on with this series you might notice that the post here at the top is the very first post that I wrote so that means that the oldest posts are being shown at the top and the newer bottom and this likely isn't how you'd want an application like this to work you'd likely want the newer posts at the top and the older ones at the bottom so getting this to work is super simple all we have to do is reorder these in our query so if I wanted the newest post to be first then if I change these around if I go to the very bottom here then I have a post here that says my latest post and I want that to be the very first on my website whenever i reorder these so in order to do this I'm going to open up our routes dot pi and then we can go to where we're doing our query and right before we do the pagination query here I'm going to add in something else so I'm gonna say post doc query dot order underscore bi and I'm going to pass in what we want to order by here and post dot date underscore posted dot descending and that descending is a de SC with the parentheses there so now that we have post that query dot order by with what we want to order by then we can just add our paginate on to the end of that so all of that and then dot paginate with our options there at the end so if I close my sidebar down here then we should be able to see this whole line there we go so now if we save this page and reload it in our browser then our web server is still running so that's good and now let me rerun our application and now we can see the Lotus post that I made is titled my latest post at the very top and it's now the first post that we see so this is how you can sort your results through SQL alchemy okay so there's one more thing that I'd like to do before we finish up this video so if we look at the application that we have so far then we can see that the user name of the user who made the post is currently a link but it doesn't actually go anywhere so let's build a route that will display only the posts from these particular users when you click on those links so first let's create a route and this will be similar to our home route so I'm just going to copy that as a starting point so here in our routes I will copy this home route and I'm just going to paste this down here at the bottom of our routes to create a new route here and now we'll change this to the route that we want it to be so I'm going to get rid of one of these app dot routes I only meant to grab one of those and so we will make this route Ford slash user forged slash and now the users username now this is going to be a dynamic parameter here so just like our post ID we will create a variable and this is going to be a string instead of an integer so we'll say STR: and now the variable name so this will just be username and we also need to post this in to our route now and we also need to change this function name so I'm going to user underscore post because this is going to be a route where we just show all the posts for this specific user name now the query that we're using is going to be mostly the same but we're going to need to query for this specific user first and then grab the post only by them so first I'm going to get this user so I'll say that the user is equal to user dot query dot filter by and we want to filter by the user name being equal to the user name that is going to come from the route itself and now instead of doing a dot first this is going to be like that dot get or four this is going to be dot first underscore or 404 and basically that just says get the first user with this username and if you get a none then just return a 404 not found error and like I said that's very similar to the get version that we saw of that in previous videos except this isn't searching by ID so now that we have that user now we can filter our post by this username if one was found now we're going to add to our post query here but this is getting a little long so we can actually break these up if we put a backslash at the end of the line here then we can break these up onto multiple lines and I'm going to do this before our order by as well because we are going to put in a filter there so we can say post query dot filter by and we can filter by the author equaling the user that we just got then we're using this backslash to break this up onto a different line since this was getting a little long and then we're doing and order by with the post in sending order by the date posted and then another backslash to break it up on another line and then we're doing our paginate query there so kind of long query but that should work so now instead of sending these posts to our home template let's create another template for this specific user and I'll call this template user post HDC but I'll go ahead and render this template now so I will render user underscore post and then we will pass in the post to that template like we're already doing and we also want to pass in the user into that template and I'm going to open up our sidebar so that I can create this template and I will create that now so I'll create user underscore post dot HTML and like I said this is going to be similar to our home route so I'm gonna copy our home template and paste that in as a starting point so I'm going to grab all of that and paste it in to our user post page

User Page

and the difference here will be that I'll be adding a heading at the top specifying that this is this users page so I'm going to do this below the content block but above our for loop here so I'll just set this equal to an h1 and I will give this a class to give it a little bit of padding so I'll say margin bottom with a value of 3 and now within this h1 I'll say posts by and then double curly braces to specify a variable here then we'll say user dot username and then in parentheses here I'll also put the total post that this user has so parentheses and then double quotes again and we will say if we remember this says post dot total and that will give the total number of posts even over the paginate 'add links now the post for loop will mostly stay the same but we can actually set the href for the user to now go to the user post route that we just created so down here on line 9 where we have this pound sign as the href let's actually do a double curly brace and do a URL for and we want this to be the URL for that user post route that we just created then we want to pass in a comma and also pass in the username variable and the user name will be equal to the post dot author dot username and we have this link in our home and our post template as well so we have to change those they're also now having that code repeated in multiple locations isn't best practice and it's for that specific reason because you have to update it in multiple places but we'll fix that in a future video when we see how to use sub templates for repeated sections like this so we are going to get around to improving that but for now let's go ahead and just update those templates so that was the home template and the post template so we need to change that URL there as well so right here where we have this post user name I'm going to paste in that URL for the user post with the username set to that post author user name and save that I'll also change that and our post dot HTML template and that is going to be here on line 7 where we have that poster user name I will paste in that URL for link now if I go back to my user post template here then we also need to change something with the pagination links at the bottom as well because these pagination links should no longer be linking to our homepage because these are paginating links for this users specific posts so we need to change both of these to be linking to the user posts route and we also need to pass in that user name like we've just did a second ago and set that equal to user dot user name put in a comma there and I'll also paste this in right below here okay so now let's save this and open it in our browser and see what this functionality looks like so let me make sure our web server is still running and it needs to be reached ardan okay and it looks like we're getting an error when we're trying to start up our web server this time and I think I know what this is this says STR does not exist and this is because in our routes whenever I specified that type so I'll go back to my route this should actually be string spelled out and not STR so that was my mistake so let me try to restart our development server now and now we can see we're not getting any errors and our development server is running so let's reload our web page here and now let's try to go to one of these specific users pages to see all of their posts so now we can see at the top of this page it says post by Cory MS and that there are 16 total and the pagination here should just be the pagination for this users post so you can see that we don't see any of the other users posts on this page if I go back to the home page and go to this users page then this user has a total of nine posts so he should have two pages total so if we go down here to the bottom we can see he has two pages click on that and he has four posts on the second page so we can see that those user pages are working well and that they also have pagination working for the posts on those pages also okay so I think that is going to do it for this video I hope that now you have a good idea for how you can get pagination working on your website and the different ways in which you can create links and handle the logic for those in your application and also we learned how to sort our posts by either the newest or the oldest entries and also created a useful route for post written by specific users now in the next video we'll be learning how to send emails and how we can use that to reset a user's password but if you have any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that the easiest way is to simply like the video and give it a thumbs up and also it's a huge help to show you these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник