What you'll learn
- Set up a Flask project with a virtual environment and run the server with the flask --app run command on localhost port 5000
- Explain how passing __name__ to the Flask constructor sets the base directory for templates and static files
- Add multiple routes to a Flask server and verify each one from the browser and the server console
- Enable the --debug flag so Flask reloads automatically on code changes, and explain why it stays out of production
- Return JSON data with make_response and inspect the status code in the browser's Network tab
- Render HTML pages with render_template using double curly brace placeholders for title and content
Free 51-minute video lesson with a full transcript and knowledge checks. No account needed to watch.
Overview
Join Shaun Wassell as he walks you through the basics of creating and running Flask servers in Python.
Recommended Experience
- 1 to 2 years of software development experience
Related Job Functions
- Software Developer
- Software Engineer
- Software Development Engineer (SDE)
A former full-stack developer, Shaun Wassell brings a wealth of web development and programming experience to his training.
Introduction
Join Shaun Wassell as he lays out the topics that we'll be discussing in this section.
Creating and Running a Flask Server
Join Shaun Wassell as he walks you through the basic setup of a Flask server and shows you how to get one up and running.
Knowledge Check
Which of the following shows how to create a new Flask server?
Adding Different Routes
Join Shaun Wassell as he shows you how to add different routes and handlers to a Flask server.
Knowledge Check
Which of the following demonstrates the correct syntax for adding a new route handler to a Flask app?
Customizing Responses
Join Shaun Wassell as he shows you how to use Flask's make_response function to create customized responses inside Flask routes.
Knowledge Check
The status code indicating that everything is OK is ________.
Responding with Templates
Join Shaun Wassell as he introduces you to the concept of templates in Flask and shows you how to render a template and send it back as a response.
Knowledge Check
Which of the following shows how to use Flask's render_template function and replace all occurrences of {{ name }} with "Bob"?
A Different Way of Separating Routes
Join Shaun Wassell as he shows you how to create a "catch-all" route that handles every server request, and how to execute different logic inside this route depending on the request path.
Knowledge Check
Which of the following shows the necessary decorators to create a "catch all" route handler in Flask?
Conclusion
I hope this has been informative for you and I would like to thank you for consuming.
View Transcript
Introduction
0:00[AUDIO LOGO] Hi, everyone. Shaun Wassell here. One of the main advantages of working with the Python language, as I'm sure you've seen by now, is its versatility. It can be used for a very wide variety of different applications. Now, one application that's particularly important if you want to get into things like back-end development is creating web servers using Python. And in the Python ecosystem, there are several different libraries that are available to us that we can use to quickly and easily create web servers.
0:35And the one that we're going to take a look at here today is a library called Flask. Now, Flask is well known in the Python ecosystem for being very easy to get up and running. And that's what we're going to take a look at here today. We're going to see how to create a very basic web server with Flask and just some of the details of working with this library. So without further ado, let's jump right in.
Creating and Running a Flask Server
0:00[AUDIO LOGO] All right, so to get started here, the first thing that we're going to want to do is set up a basic project that will be writing all of our Python flask code inside of. And this will involve doing things like creating a virtual environment to keep track of our dependencies, and creating a few files that we'll actually be writing our code inside of. So the first thing that you're going to want to do is open up whatever your favorite IDE for Python development is.
0:34I'm going to be using Visual Studio Code, which is free to download. And it's my personal favorite for doing pretty much any kind of web development, just because it's easy to work with. And the next thing that you're going to want to do is open up a terminal, so that we can do things like set up our project. So in Visual Studio Code, in case you haven't worked with it before, you can do this by just going to Terminal, New Terminal. If your IDE doesn't have a built-in terminal, you're just going to want to work with whatever your computer's built in terminal happens to be.
1:07So command prompt if you're on Windows, or just regular terminal if you're on Mac. And just as a reminder, I am going to be developing all of this on a Mac. So a few of the commands like doing things like creating directories with mkdir d might be different on your operating system if you're using something like Windows. So that's just something to keep in mind. But as far as the different Python specific commands go, they're going to be pretty much the same for you no matter what operating system you're on. So you shouldn't have to worry about that too much.
1:38Cool. So anyway, now that you've done that, the first thing that we're going to want to do is create a new directory. And currently, I'm inside this Python directory, which is just where I like to keep all of my Python projects. But you can create this directory wherever you want. And I'm going to create a new directory by saying mkdir. This might be a little bit different on Windows. So if worst comes to worst, you can always just do File, and then do Open, and create a new folder that way. And then what we're going to do is call this project something like flask-basics.
2:14And now that we've created that new folder, what we're going to do is change directories into that folder. Again, this command might be a little bit different if you're on Windows. So you can always just do File, Open up here if you want to. And in order to open this in Visual Studio Code, if you have this capability set up in Visual Studio code, which I do, you can just type code and then dot to open up this folder in Visual Studio Code. Otherwise, again, you can just do File, Open, and that will open up that project for you.
2:45All right, so anyway, what we're left with now is just an empty directory. And what we're going to do next is set up this directory with a virtual environment. And we can do that by running the command python3-m, and then venv and venv. And what that'll do is it'll generate this new folder for us called venv. And that just includes a lot of the dependencies for Python. So anyway, now that you've done that, the next thing that we're going to want to do is activate this virtual environment, so that we can do things like install the dependencies for this project, including probably the most important dependency, which is going to be the flask library itself.
3:29So in order to do that, all you have to do is run dot, and then vnev/bin/activate. This might be different depending on your operating system. But all you have to do is activate a virtual environment. So just google that if you have trouble with it. And what that will do is it will put our terminal into a virtual environment, which you can see over here on the left-hand side. So what this means is that we can now install things like flask, which you can do by running pip install flask, for example.
4:00And what that will do is it'll install all of those packages into our project, specifically, and not into our entire local machine, which would work as well if you wanted to do it that way. But almost always, it's considered a good idea to keep your different dependencies for your projects segregated in their own directories using some kind of environment like virtual in. All right, so anyway, now that we've done that, we should be able to create our first file and our first flask server, which we'll call something like hello-world.py.
4:35And that will open up that file in our window here. So writing a flask server is actually incredibly easy. And you can do it using probably about four lines. We'll see how many lines exactly we have. But I think it's about four lines more or less most of the time. So the first thing that we're going to want to do in almost all of our flask projects is import flask from the package that we installed. So what that's going to look like is we're going to say from Flask import-- capital F, Flask.
5:06All right, and this flask thing is an object that we use to create new flask servers. And the way that we do that is simply by saying app equals Flask, with a capital F, that is. Make sure you capitalize this and don't try and use this lowercase f, flask. That's just the package name. And then what we're going to do is call Flask with a single argument, and that's going to be __name__. Now what we're doing here is we're basically telling Flask where to start when we want to tell it later on to look for things like static files and templates.
5:43So all that we're doing with this __name thing is, as I said, just letting flask know where exactly it's running. What directory we want to use as the base for all of the paths that we'll use. So now that we've created a new flask app, what we're going to do is add our first route to this server. Routes are basically just different pieces of functionality that can be accessed by sending network requests to our server, which I'll show you how to do very shortly if you haven't worked with that before.
6:15So what this is going to look like is we're going to say @app.route. And we're just going to add a slash here. And under that, we're going to say def, and we'll just call this function something like hello_world. And then what we're going to do is just say return. And we'll return a string that says "Hello, world." So yep, sure enough, with five lines of code. I was off by one line. But with five lines of code, we've created a new flask server.
6:47And I'll explain what's going on here with this app.route thing a little bit later on. But first, let's run our server. And we can do that just by opening up our terminal. And you are going to want to make sure that your virtual environment is active for this because otherwise, it won't work. What you're going to do is run flask --app. And then we need to tell flask where the main app is in our files. So we're just going to say hello-world. And you can put .py. But you don't need to.
7:18Flask will understand it either way. And then we're just going to say run and hit Enter. And what that will do is it will print out some stuff here that says serving Flask hello-world debug mode-- off. And it says running on HTTP and gives you this IP address with port 5,000 after it. So if you want to actually send a request to our server now, we've created a single route, which is just being served on the home route of our server. So if you want to actually send a request and see this response, what you're going to want to do is open up a web browser and type in localhost 5,000 up at the top and hit Enter.
7:54And sure enough, what you'll see is that it says hello, world in the page. All right. So what's happening here is when we type localhost-- 5000 into our browser, our browser is actually sending a request to our server that's running, our flask server. It's being handled by this route that we defined here. And what we returned from this function is sent back automatically to the client as a response. So our server sends back hello, world to the browser. And that's what gets displayed in the page.
8:26And we'll discuss the actual route definition in much more detail shortly. But for now, we have our first flask server up and running. So congratulations on that. And as I said, we're going to be learning a lot more about how to work with flask servers as we continue. So I hope this has been informative for you, and I'd like to thank you for viewing.
Adding Different Routes
0:09So now that we've seen how to create and run our very first flask server, the next thing that we're going to do is take a closer look at how to define different routes for a flask server and some of the things that we can actually use those routes for. So as we already saw, the way that we can define routes on a flask server is by using this little @app.route thing. And this is what's referred to as a decorator in Python. Don't worry too much if you haven't worked with those before. But for now, just know that this is how we add routes to our application, to our flask server up here-- is by using this app.route decorator.
0:47Now, this app.route decorator is a function. And as you can see, the argument that we pass into it is the path that this given route is going to listen on. So as we saw, by passing just the slash for this argument, that means that-- let's say if our server is running on localhost 5000, which is the default place for a flask server to run, then by sending a request to this-- basically, the slash just means there's no extra segments that come after this URL-- will activate the functionality inside this hello_world function.
1:25So the reason that the decorator is above this function is because the function down below, which we can call pretty much whatever we want, anything that makes sense to you-- this function down here is what's going to be called whenever our server receives a request on this specified path. So as we already saw, when our server receives a request on localhost 5000, this function is going to run. So if we were to print something out from inside the function, let's say, which you can do by just saying print, and we'll say "Received a request," you'll see that this will be executed in addition to this return statement.
2:07Now, the return statement of this function is the data that ends up getting sent back to the client side. We already discussed this. And we already saw that when you send a request from, let's say, a browser, this string was received by the browser and displayed in the window. Now, in this case, we just sent back a simple string. But there's plenty of other things that you can send back as well. You can send back JSON data. You can send back files. And that's all stuff that we'll take a look at very shortly as well. So anyway, just to review the different parts of a route, you have up here the definition for what the path, what the URL that the route is going to listen on, will be.
2:48Under that, you have the function that's going to be executed when a request on that path is received. And the function body is all, of course, going to be executed when we receive that request. And whatever the function returns will be sent back to the client, the person who sent the request in the first place, as a response. So now that we've seen how to define one route in our flask server, let's just define a few more routes. And actually, let's change this hello_world route from just having a slash as the path to something like /hello.
3:22And let's also define another route. And we'll say something like app.route. And we'll say /goodbye. So we have two routes now, a hello route and a goodbye route. And for the functionality of our goodbye route, what we're going to do, again, is just define a simple function, which we can call goodbye or, really, whatever makes sense to you. And what this is going to do is it's just going to say "return Goodbye!" And while we're at it, let's just print something out inside this function.
3:53So we'll say "print." And we'll say "Received a request on /goodbye." And we'll change this thing up here so that we can actually tell where the request is being received. So we'll say "Received a request on /hello." Now, what you're going to see is if we restart our server-- you will have to restart the server, by the way, in order for these changes to take effect. I'll show you how to get around that very shortly, too, if that bothers you. So let's just restart it. And what you're going to see now is if we open up our browser again and send a request to localhost 5000/goodbye-- let's just test our goodbye route first-- what you're going to see is, sure enough, we get the response "Goodbye!" displayed in our browser.
4:35And if you go back and take a look in the terminal where we actually ran our server, you're going to see that it says "Received a request on /goodbye." So that's this line of code being executed and printing out in the server console. So if we go back to our browser now and say /hello, what we're going to see is that, sure enough, we get the same response. It says "Hello, World!" And sure enough, back in our terminal, we see that it printed out "Received a request on /hello." So anyway, if this is your first experience working with web servers, then probably a good way of thinking about routes just while we're getting started here is that the routes that we've defined here are sort of like functions that can be called remotely from a client somewhere.
5:20So if you want to picture our browser here calling these functions directly and just getting the return value sent back, that's more or less what's going on here. I found that that was a helpful way to think about it when I was first getting started with creating web servers way back when. Just think of these as remote functions that could be called by sending a request to a specific path. Now, one last thing that I wanted to show you here was if we send a request to something like localhost 5000 without any path after it, what you're going to see now is that it says "Not Found.
5:53The requested URL was not found on the server." And the same thing is going to happen if we send a request to slash blah, blah, blah. If you just type in random letters, we get the same response. If you type in "abc," then you're going to see that we get the same response. Basically, when we haven't defined a route for a specific path, such as /abc, our server is going to automatically send back this "Not Found" response to the client side. Now, that may or may not be what you want.
6:24And we'll see later on some ways to customize this functionality if you want it to behave differently. But anyway, that's just something to keep in mind. If you see this, chances are you just typed in the wrong path in your browser. So anyway, that's how to add multiple routes to a server. And you could really add as many routes as you want. And production servers tend to have quite a few different routes for different pieces of functionality. So if we wanted to create this abc route now, we could just say define abc. And we could say something like-- we'll just say return ABCDEFG, blah, blah, blah.
6:58And now if we restart our server, what you're going to see is that those changes will take effect. And if we send a request to /abc now, we'll get that as a response. So anyway, that's how to add different routes to a flask server and how to send requests to those different routes. I hope this has been informative for you. And I'd like to thank you for viewing.
Customizing Responses
0:00[AUDIO LOGO] All right, so now that we've seen how to define multiple routes on a Flask server, the next thing that I want to take a look at is how to have our routes return different types of data, because currently, each of our routes has just been returning a string. And as we've seen, whenever we send a request to these routes from, let's say, a browser, this string is all that gets sent back. Now, as a matter of fact, this is almost never what you'll want on a real-world server.
0:34You'll usually want to send back things like files. So you might want to send back an HTML file or an image. Or very often, you'll want to send back things like JSON data. If you're writing a rest API of some sort, you'll want to have your routes return JSON data that the front end of your application can actually use. So anyway, what I want to do here is take a look at how to return those different types of things-- so how to return things like HTML and how to return JSON. But before we do that, what I want to show you first is how to have your server automatically restart whenever we make changes, because currently, what we've had to do whenever we make changes to our server is we've had to actually manually stop our server and rerun flask --app hello-world run.
1:19OK, and that's obviously not ideal, because more often than not, I just forget to restart my server. And I wonder why some kind of change that I made isn't taking effect. So in order to have your server automatically restart, it's actually very, very simple. Instead of running flask --app hello-world run, you're just going to need to add the --debug flag to this command. OK, so just add --debug into the command. And now what you'll see is if we make some kind of change to our code-- so let's say that we want to change this /abc route to something else.
1:53We'll say /hello-again. And we'll return "Hello again." OK, now we can just go straight over to our browser and test this route out by saying /hello-again, like so. And we'll see that that change has already taken effect. And in fact, if you open up your terminal here, you'll see that whenever you make a change, it says something along the lines of detected change in blah, blah, blah, the path to the file that you're running. And it'll say that it's reloading. And you'll see that it says that it's restarting the server and that it's active, which means that you can send requests and test out the updated code that you wrote.
2:32So anyway, that's just a very useful thing to do when you're developing Flask applications. Nobody likes to have to restart their server manually every change they make. So I highly recommend that you use that debug flag for every application that you develop, at least in development. You don't want to use it in production, but that's something we'll get to later on. So anyway, now that we've seen how to have our server automatically restart, let's take a look at how to return different types of data. And what I'm actually going to do here is create a new file, which we'll call something like returning-data.py.
3:07And you can call this whatever you want. You can even just write it all in the same file. But I'm just going to start over here because all of the code that we're going to write here is going to be quite a bit different from what we had in hello-world. Plus, I just don't like having a file called hello-world hanging around for too long in a course. So anyway, now that we've done that, let's just create a new server. It's very quick to set up. We'll just say, from flask import capital F Flask. And in addition to this capital F Flask now, what we're also going to import are two other things.
3:41The first thing is going to be called make_response. You'll see how that's used very shortly. And the second thing that we're going to import here is something called render_template. So now that we have all of those things-- we'll see how they're used in just a minute here-- let's create our app by saying app equals Flask, and then underscore, underscore, name, underscore, underscore, which again just tells Flask where our current directory is so that it can look for things like static files, which we actually will be doing here.
4:15OK, so now that we've created our app, the first thing that we're going to do is see how to send back JSON data to the client. And in order to do that, let's just pretend that we're creating a simple REST API for managing user data. All right, so the idea here will be that a client, a front-end application of some sort, can send a request to our server and load data about different users. So we'll just say /users, and that will be the route that the front end can send requests to, to load data.
4:47So in this case, we would probably want to send back some sort of user data in the form of a JSON object. And in Python, of course, we represent those usually as dictionaries. So a user might have an id property of something like 123. They might also have a name property. So we'll just say name, and I'll just use my own name here. And of course, you can have as many other properties as makes sense for your application. So what we're going to do here is just create a simple route that will give us this kind of functionality.
5:22And obviously, in the real world, you'll probably want to do things like have your server interface with a database and load the data from there. But again, just to keep it simple for now, we'll just assume that we're sending back data directly from inside our code. So what we're going to do is we'll just say, app.route and we're going to say /users. OK, so that's the path for this route here. And then we'll define a function underneath that that will get called when we receive that request. And let's call our function something like get_users.
5:54Now, the actual name of this function doesn't really matter. And in fact, you probably noticed back in the hello_world function that I didn't even change the name of this function down here when I changed the path to /hello-again from abc. And while it's definitely not ideal to have these randomly named functions sitting around, they're really not going to change the functionality of your application, at least not at the point we're at currently. So obviously, we'd want to change this to something like hello_again just to give us an idea of what the function's doing. But just coming back to our returning-data.py file, we could call this load_users.
6:29We could call this just plain users. We could call this basically whatever the function is supposed to be doing. So let's just call it get_users for now. And then what we're going to do is we're going to define a user inside this function. So we'll just create this as a simple dictionary. And we'll give the user an id property, which will be something like 123, and a name property, which I'll use my own name for like so. And that's the data that we'll send back to the user. OK, now, at this point, we have the data we want to send back to the client.
7:02And the good news here is that if the only functionality that you need is to send back a simple JSON object like this one, you can just say, return user, and Flask will automatically take care of processing this dictionary and sending it back as JSON data for you. So there's nothing specific that you have to do in Flask to convert a Python dictionary into a JSON response. However, in many cases, what you'll want to do is do things like set headers on your response.
7:32Or you might want to set a specific status code on your response. And the way that you do that is by using this make_response thing that we're importing from Flask. So in other words, instead of just sending back user, let's say that we want to set some different headers on our response. And the idea behind headers is just that they make it easier for the client to know exactly what it's dealing with in our response. All right, so let's say something like response equals make_response.
8:02And this is actually a function that takes a few different arguments. The first argument is going to be the data that you want to send back. So if we want to send back this user data, all we'll have to do is pass user as the first argument. Now, the second argument to this function is the status code that we want to send back to the client. And there's lots of different status codes out there. The most common one is 200, which just means that everything went OK on the server. You've probably also seen the 404 response code, which means that whatever resource the client is trying to load wasn't found.
8:36We'll be dealing with this status code a lot more in the future. And there's a multitude of other status codes out there for different situations. So anyway, for now, let's just say 200, which means, again, that everything was OK on the server and that the request was handled properly. And that's about it. Now, this response thing here is an object that we can set different properties on. So we can do things like set headers. We can set cookies. We can modify the data that we're sending back in the response, et cetera. And we're going to talk about all of those things later on.
9:09But the first thing that I'd like to show you right now is how to set different headers on the response. So headers are just extra pieces of information about the data that we're sending back. So for example, we might want to tell the client side that the data that's included is JSON data. And the way that we would do that is by saying response.headers. And this headers thing is basically just a dictionary that we can set different headers on. So if we wanted to set a Content-Type header, we could just say Content-Type like so.
9:43And we would say equals, and then if we wanted to set the Content-Type to application/json, that would be how we would do that. OK, so now that we've done that, all we have to do is return this response. And that will have a similar effect to what we had earlier when we just returned the data that we wanted to send back, except now the response will have these extra pieces of data on it, such as the status code, the headers, et cetera. So let's just say return response, like so. And if we run our app now-- currently, we're just running hello-world.py.
10:17So let's just exit out of there and run returning-data.py by saying flask, and then we'll say --app returning-data. And then we'll say --debug and say run, and that will run our returning-data server. So now if we head back to our browser and reload localhost:5000/users, what you're going to see is that we get back this JSON data. And if you open up the inspector window in your browser, which you can do by right-clicking and clicking on Inspect, if you go to the Network tab, what this will actually allow you to do is see the responses that your browser is getting in more detail.
10:57So if we refresh this again, what you'll see is this request shows up under this list. And if we click on it, you can see that, sure enough, it has the status code of 200 OK. And if we scroll down to the headers, and if you scroll down to the Response Headers, you'll see that Content-Type is application.json. And you'll also see a lot of other headers that are just included automatically as well by Flask. All right, so for example, it tells the client what type of server is actually running here, the date that the response happened, et cetera.
11:30All right, so that's how to use the make_response function in Python to create a custom Flask response. The next thing that we're going to take a look at is how to use this render_template function to send back things like HTML to the client side. So I hope this has been informative for you, and I'd like to thank you for viewing.
Responding with Templates
0:00[AUDIO LOGO] So now that we've seen how to customize the responses that our server sends back by using this make_response function that flask provides us, the next thing that we're going to take a look at is how to respond with templates using this render_template function up here. So if you want to think about it this way, there's really three different types of responses that our flask server is going to respond with.
0:33The first one is just responding with simple data. So sending back something like a string, as we saw, such as hello, world. The second one is responding with some kind of JSON data. And in that case, we'll generally want to use this make_response function here. So that's the second one, is sending back some sort of JSON data. And the third one, which is what we're going to see here is we'll often want our server to respond with some HTML data that the browser can actually render.
1:05So we'll have some HTML document that we send back. So those are really the three main things that we'll be sending back from our server on a regular basis. Before we get started, seeing how to use this render_template function that we imported from flask, let's actually talk about what a template is in the first place. So let's imagine that we want to use flask to build a very simple website, and we want to have several different pages that all display some title.
1:37So we'll say title up here, and some content underneath that title, some piece of text. Well, before templates, what you would have to do in this case, if you wanted to have, let's say, three different pages like this that all displayed a different title and a different piece of content, is you would actually have to create three separate HTML documents. So you'd have something like page1.html, you'd have page2.html over here with some different title.
2:13We'll just say title2, to show that it's different from this one over here. And then you'd have page3.html, and that would have yet another title, which we'll call title3. And of course, these two pages here would also have different content underneath that title. Now the problem with this is that it's messy and it's repetitive because what all of these would look like is they'd probably have an h1 tag with the title in their, whatever that happens to be.
2:44And underneath that, they would have a series of paragraph tags with the actual content of the page in between them. And this is obviously a pretty simple page. But if you start talking about pages that are much more complex, such as page 4 displaying the details of a product on an e-commerce site, well, you're going to have a lot of repetitive HTML structure that you're going to have to go through and change if you want to change the way that the page actually looks. So anyway, coming back to templates, templates allow us to specify the HTML structure of a page without actually specifying the exact data that's contained in that structure.
3:26Now to get started with templates in our current project here, the first thing that you're going to want to do is create a new folder inside this flask basics folder, or whatever you ended up calling it. And we're going to call that folder templates. Now the name of this folder is actually important because this is the default name that Python will actually look for our templates inside of. So you need to call it templates. If you want to call it something else, there's just one small change you have to make, which I'll show you later on.
3:57So inside this templates thing now, what we're going to do is say New File, and we'll create a template, which we'll just call something like article.html. And inside this now, what we're going to do is just create a very simple HTML layout. So we'll just say HTML, we'll want to put the dock type thing up at the top, and then we'll want to have a head and body of our HTML document. And for now, let's just add a title to the head.
4:28So we'll say something like this is an article. And then for the body, what we're going to do is we're going to specify those two pieces of HTML, those two HTML elements. The title, as I was talking about before, and the paragraph, which contains the content. Now again, if we weren't using templates and we were just specifying our site statically by creating different HTML files, one HTML file for every page on our site, then what we'd have to do is we'd have to put the first title for our article in between these h1 tags.
5:03So we'd say something like this is my first article. And then we'd have the content here, which would be blah, blah, blah. And then if we wanted to create another article, what we'd have to do is actually duplicate this file. So we'd have to say copy and paste. And we'd rename this something like article2.html, and then we just have to make those changes inside h1. So we'd say this is article number 2.
5:34And then presumably, we'd have some different content in there as well. And then we'd have to do the same thing for all of the articles that we wanted on our site. So anyway, that's not ideal because it makes it very hard to make changes to our page. So what templates allow us to do instead is simply leave blanks in our HTML structure that we can fill in later on using server-side logic. So instead of actually specifying the hardcoded title and content inside article.html, we can instead just use these double curly braces, which are referred to as handlebars.
6:10And we can just give this blank, which we're leaving a name. So we're going to say title here. And in between these two paragraph tags, we'll say content. And once we've done that, we should be able to go back to returning-data.py, and render this template with different pieces of data for the title and the content. And by the way, don't worry if this isn't making sense quite yet. Once we've actually written the code for rendering this template, you'll see how that works. So anyway, what we're going to do here, is we're going to create a new route.
6:44So we'll say app.route. And we'll start off by creating a route for our first article. So we'll just say /article-1. And underneath that, we'll define a function called article1. And inside here, what we're going to do is use this render-template function up at the top to actually render this HTML document that we created with a specific title and content. So here's how this is going to work. And actually, before we get into the title and content stuff, let's just comment that out.
7:16And we'll start off even simpler by just saying, "Hello, I'm a Template." OK. So even simpler, we're just going to start off like that. All that we have to do in order to send this article back to the client side is return the render_template function called with the name of the template we want to return. And in this case, it's going to be article.html. So we'll say article.html. And that's all we have to do. So let's go back now to our browser, and we'll send a request to /article1 and hit Enter.
7:53And oops, it looks like I forgot the dash. I put a dash between article and 1. So let's fix that here. And we'll say article-1. And sure enough, what we see is the HTML gets sent back to us saying, "Hello, I'm a template. If you want to see the HTML in more detail, you can just say inspect, and that'll show you the HTML document here so that you can actually see what all was in that document. So anyway, that's how to send back a simple template to the client side. And granted this template was just an HTML document.
8:25So let's now see how to render the title and content values into this template. Well, all that you have to do for that is pass some extra keyword arguments to this render template function. And those keyword arguments are going to have the same names as you gave to the blank spaces that we left in our template. So we're going to want to have a keyword argument called Title. And we're going to want a keyword argument called Content. And what that's going to look like is we'll say title equals. And then for the title, we'll just say "My first article" or something like that.
9:00You can put on whatever you want. And here, let's make sure we have commas in between these arguments. And then we'll say content. And then in here, we'll say thank you for reading. This is my first article. OK. Cool. So what's going to happen now is the value that we pass to both of these, title, and content is going to be inserted into this template. And basically, the handlebars section here. The double curly braces is going to be removed and replaced with that value.
9:32So if we go back now to our browser and reload our article1, what we'll see is that sure enough, we get an HTML document that says my first article. Thank you for reading this my first article. And if you open up the inspector window again, you can see that in the HTML, there's no handlebars as there were before. We just have our heading that says "My first article," and we have our content inside the paragraph tag. Now if you wanted to have multiple articles on here, what you could do is you could simply say app.route, and add another route.
10:06So we'll say article-2. And inside here, we'll say define article2. And then we'll do the same thing that we did up here with article1, except with a different value for title and content. So we're going to be rendering the same template with different data. So for the title, we can say my second article, and then we'll just change this to my second article. And these could be completely different. I'm just being a little bit lazy here and keeping most of the content in the title the same.
10:40But you could render two completely different articles in here as well. And in fact, let's just create a third one while we're at it. And we'll call this one article-3. And we'll call the function article3. And by the way, it is important that these functions have different names. If you happen to copy and paste a route like I just did, you're going to want to remember to change that function name because otherwise, that will cause an error. And now what we're going to do is just say title and we'll change this one to my third article.
11:10And we'll say thank you for reading. This as my third article. Cool. So now what happens is we go back to our browser and send a request to article 2, we'll see that it gives us the same HTML, but with different values inside the h1 and paragraph tags. And if we go to article-3, the same thing is going to happen there. So anyway, that's how to render templates in flask and send them back to the client side with different data. And this is obviously just the tip of the iceberg for working with templates in Flask.
11:44We'll see some much more detailed examples later on. But for now, I hope this has been informative for you, and I'd like to thank you for viewing.
A Different Way of Separating Routes
0:00[AUDIO LOGO] All right, so now that we've seen how to send back customized responses using this make_response function and send back templates from Flask using this render_template function, the last thing that I want to take a look at is a slightly different way that you might implement different routes on a Flask server. So currently, whenever we've wanted to add another route to our server, we add a new @app.route thing with a new path inside of it, and add a function underneath that.
0:39And basically, what this means is for each and every route, there's going to be one and only one function that handles that route. However, there are certain situations where you actually want to create a route that handles more than one path. Now obviously, things like URL parameters, which we'll talk about later on, are an example of this. But for now, let's just say that we want to have a single function that handles all of these different routes, instead of one individual function for each route for a total of four different functions.
1:12So just to make this a little bit more clear, let's say that we want to create a new route. And this is going to look a little bit different here. For now, I'm just going to put the dot, dot, dot there to signify that I'm going to come back to that later. That's not an actual Flask syntax. And underneath this, we would say something like define handle_request. And then inside here, what we would do is we would handle any request that our server receives. So in other words, if we were to say something like print "I got a request," and then return something like "Thank you for your request."
1:50Let's say that we want this to happen for each and every request that the server receives, regardless of the path that request is sent to. Well, what you can do in Flask, and I'm just going to comment out all of these things up here for the time being, what you can do in Flask is you can actually define what's referred to as a catchall route. And all that, that means is that the function that's associated with that route is going to be called on every request that's received. So what this is going to look like, it does look a little bit funny.
2:21So don't worry too much about the syntax. We're going to say app/route/ and then we're going to add a second argument here, which is a keyword argument called defaults. And we'll say path. And we're just going to pass an empty string there. And then underneath that, we're actually going to say app.route. And here's where the syntax starts to look a little bit funny. We're going to say slash. And then in triangle braces, we're going to say path:path and closing braces. And that's all we need to do there. So don't worry too much about this syntax here.
2:52We'll go into much more detail on what these things like defaults and this path:path later on. But for now, just know that this creates a catchall route that will respond to any request. So now if we go back to our server, what we're going to see is if we send a request to any path. And oops, it looks like that actually gives me an error. And that's just because we need to add an argument to this handle_request function called path. Again, don't worry about that too much right now. Just know that we'll need that for later.
3:23So now if we go back to our browser and refresh, what you'll see is that it says thank you for your request no matter what route you send a request to. As long as it's on localhost 5000, you're going to see that you get that response. So you can literally send it anywhere you want. And you'll get the same response every time. And if you go back to the server and take a look at the console, you'll see that it says I got a request, I got a request, I got a request each time we send a request to it. So anyway, now that we have this catchall route that handles requests no matter what, let's take a look at how we could refactor this route handler to behave in a similar way to what we had with all of our separate routes up here.
4:02Well, if you take a look at this path argument, what you're going to see-- let's just print this out here, we'll turn this into a template string, and we'll say I got a request on. And then we'll insert the value of path into this so we can see what that is. What you're going to see is that this path thing-- if we go back to here and just refresh it, if you open up your terminal, you're going to see that it says I got a request on abc. So basically, path is the value that comes after this slash in the route. So maybe you see where I'm going with this. We can actually now use this path argument to change the functionality of this handle_request route just by using simple if statements.
4:40So let's just take a look at what that might look like. We'll say if path, and let's try just our first path up here, which was article-1. We'll say if path is equal to article-1, then what we would want to do is we would want to say return. And we would want to render that template like we had here. So we can just copy that and actually paste that in that spot. And we'll want to uncomment that, of course, like so. And adjust the indentation. And there we go.
5:10And we can do the same thing with article-2 and article-3 as well. So we can say if path is equal to article-2, we'd want to do the same thing. So we'll just copy the return statement from article-2 up here and paste that down here. So let's add the colon there. And then we'll paste it. And uncomment it. And adjust the indentation. And there we go. And let's do the same thing now for article-3. I'm just going to copy and paste that whole thing. And actually these two should be elifs.
5:41So else if path equals article-2, else if path equals article-3. And in that case, we're going to say title my third article and thank you for reading. This is my third article. Now if you wanted to provide a default path, all you would have to do is just say else. And this would just be the server's response if the request didn't match any of these paths up above. So we could say something like return.
6:11And we'll just say something along the lines of nope, that's not a route. And because we have a single quote in a single quote string, we just have to escape that with a backslash like so. And there we go. So if we test this out now, let's go back to our browser and we'll start off by sending a request to /article-1. And sure enough, whoops, it looks like we have my third article up there. And that's just because of how I copied and pasted it. That should be my first article. Apparently, I copied and pasted the wrong thing.
6:42So let's just try that again because that was a little bit confusing. So now if we hit Refresh and send a request to article-1, we see that, that comes up with my first article. If we send a request to my article-2, we'll see that it says my second article. And if we send a request to article-3, we'll see that, that has my third article. And last but not least, if we send a request anywhere else, it could be slash blah, blah, blah, blah, blah, we'll see that we get the response saying, nope, that's not a route. So anyway, the point of this is just to show you a different way of handling routes on a Flask server.
7:16And generally, you will want to use this sort of route up here. But if you ever have a need to catch all the requests that are coming to a server and handle them differently according to their path, then this would be one possible way of doing that. So anyway, what I'm going to do here is just remove all of this code. You can feel free to keep it around or comment it out for reference later. And I'm going to uncomment all of the code above. And that should bring our server back to normal. So anyway, I hope this has been informative for you, and I'd like to thank you for viewing.
Frequently asked questions
What does the Build Webservers with Flask: The Basics lesson cover?
In 51 minutes, the team member sets up a Flask project with a virtual environment, runs the server with the flask --app run command on localhost port 5000, and adds multiple routes verified from the browser and server console. The lesson also covers the --debug flag, returning JSON with make_response, and rendering HTML pages with render_template.
What Python experience should a developer have before starting this Flask lesson?
The Python Flask Tutorial is built for software development teams that already have Python experience, and it suits associate and intermediate practitioners, especially developers with roughly 3 to 5 years of Python web framework exposure. The trainer works in Visual Studio Code on a Mac. Python-specific commands are essentially the same on any operating system, though commands such as creating directories may differ on Windows.
Why use the Flask --debug flag in development but not in production?
With --debug enabled, Flask detects code changes, reloads, and restarts the server automatically, so developers can test updated code without manual restarts. The trainer recommends it for every application in development and explains that it should stay out of production.
What does passing __name__ to the Flask constructor do?
Passing __name__ tells Flask where the app is running, which sets the base directory Flask uses when it later looks for templates and static files. This lesson walks through it while creating the first Flask app and its home route.
How does this basics lesson fit into the 13-hour Python Flask Tutorial course?
This lesson establishes the foundation of building and running simple Flask webservers. The course then moves into request handling, URL and query parameters, cookies, REST APIs, middleware, MongoDB integration, and front-end interaction, with practice apps such as a blog site, to-do list, shopping cart, and tic-tac-toe game API.
How can a Training Manager assign and track this Flask lesson across a development team?
Team Leads can sequence the course modules with CBT Nuggets Playlists to align developers on common Flask patterns during onboarding. Team reporting gives Training Managers per-learner progress and completion, cohort and group views, and completion exports for audit evidence.
Team training path
Turn this skill into assignable team training
This free skill is a preview of the courses your team can assign, track, and report on with CBT Nuggets.
Free training library
More free lessons in Python
Python
Introduction to Programming and Python
Free lesson from Certified Associate in Python Programming (PCAP) · 57m
Python
Introduction to Python
Free lesson from Python for Network Engineers · 59m
Python
Understand Functions in Python
Free lesson from Python Functions Tutorial · 54m
Python
Understand Object-Oriented Programming Basics
Free lesson from Certified Professional in Python Programming 1 (PCPP1) · 1h 4m
Python
Writing and Running Python Code
Free lesson from Certified Entry-Level Python Programmer (PCEP™) · 1h 4m
Python
Intermediate Behavior-Driven Development Concepts
Free lesson from Certified Associate Tester with Python (PCAT™) · 51m
$59
seat / mo, billed annually
