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