Linking together the back-end with the front-end
Darren Vong
@mrdarrenv
Throughout the session, put up your:
At the end, write at least one good and bad things about the session on the post-it notes!
If at any point during this session you are finished with the live coding exercises we are doing...
... then check out the bonus exercises linked in each section.
Pretty much all of this!
i.e. Don't do this!
Create a file named session2_recap.py and enter the following:
It should print Hello world!
followed by
9
on the next line.
Replace the content of session2_recap.py with the following:
It should print The second instructor in the list is Kat
.
Commonly used to go through each item in a collection of items, such as a list or a dictionary.
Since we saw how to loop through a list last time, for completeness, let's see an example on how to loop through a dictionary...
It is a data structure where each value in it is linked to a key.
Replace the content of session2_recap.py with the following:
It should print The instructor's name is Darren.
followed by
The instructor's favourite language is Python.
Let's see our final recap example before moving on...
Replace the content of session2_recap.py with the following:
It should print Drink responsibly (if you must)!
...that you know some Python, for the rest of the course, we will take a look at specific things we can do with it!
Specifically, in the next two sessions, we'll be looking at how to have more control of the back-end using Flask!
Before we cover Flask in more details, there are some important concepts we need to go through first, such as...
A server is used so we can share our web application with the world over some network.
But... how does it help make our application accessible over the Internet?
To understand that, we need to take a look at what actually happens when we try to access our application through our browser.
https://google.com
<!DOCTYPE html>
<html>...</html>
Your pretty HTML pages are actually being run (served) over the GitHub server, which is what allowed you to see your projects publicly online!
Before we begin with our first Flask app, we'll set up a new git repository together to make sure your app has the right folder structure that can be used for your competition entry.
We'll be following the same steps on how to create and clone your repository as covered in the Collaborating with GitHub slides.
As a reminder, here are the steps to follow for this task:
3. Inside the repo folder, create more files and folders using your text editor (see next two slides for more info) until it has the following folder structure:
It's very important you name the folders exactly the way they are shown in this diagram!
The easiest way to create the files and folders is to have the repo folder opened in your text editor.
Your text editor also provides a more reliable way to check that your repository has all the required files and folders.
This is because files beginning with a dot
(such as .gitignore
) doesn't show up (correctly) when viewed through
File Explorer/Finder.
In the templates/index.html file, put in some bare minimal HTML like the following (so we can push this to GitHub later):
Then, start the app by the usual drift: cd
to change your terminal
into the repo folder, then type
python app.py
If you get that, great! Let's commit and push this to the git repo we just made together...
... then we'll dissect what all of that code did.
First of all, check that you can see hello world! by typing
localhost:5000
in your web browser.
Since Flask is an external library, we have to import it first before we can use it.
The next line creates a new copy of a Flask app that we can then work with.
The @app.route("/")
line (which has to be above a function definition)
decorates our normal Python
function so that it's capable of responding to our request at
localhost:5000
The final app.run(debug=True)
line starts up a web server
controllable by Flask each time we type python app.py
in the
terminal.
Including the debug=True
part in the function call tells Flask to
automatically restart the program each time we made changes to our Python code.
... we visit some random URL, like localhost:5000/qwerty
?
We got a Not Found error as we haven't specified in our
code on how to respond to localhost:5000/qwerty
.
But we haven't written in localhost:5000
anywhere in our code,
so why did that work?
That's because Flask uses relative URLs, and by default runs (hosts)
the app at localhost
under port 5000.
This means the "/"
in app.route("/")
translates to localhost:5000/
!
localhost:5000
is the same as
localhost:5000/
!
Flask uses relative URL so our app will work in a consistent way, no matter where it's being hosted.
To find out the relative URL of a web address, look out for the value after the first single slash including the slash itself.
For example, the relative URL localhost:5000/qwerty
is
/qwerty
.
To stop Flask returning the Not Found error we saw earlier,
we need a function with @app.route("/qwerty")
above it so Flask knows how to respond when a user visits that particular URL.
@app.route
to accept
any value (except slash) after the first slash!
So far, we've been returning simple text as response to the browser when we visit our Flask app.
But that's not very good when we want to display complex web pages.
We need a way to return the pages in HTML instead, as you know them from the beginner's course!
Save the file, go to localhost:5000
again and you should see
a larger "Hello world!" coming from the HTML we made earlier!
Apart from seeing a larger "Hello world", the HTML page still looks no different from our simple text response...
So let's glam it up a bit by changing the font...
...and just to show CSS works, we'll turn the page pink!
Create a new CSS file called app.css inside the static folder, then put in something like this in the CSS file:
head
tag in
templates/index.html, add in the following line:
The url_for
function comes from Flask: it ensures
full URLs to resources (CSS, JavaScript) to always be
generated correctly...
... as long we put the CSS in the static folder!
If you followed along correctly, your page should now look like this:
.gitignore
file in your git repository!
localhost:5000/whatever
with any value
in the "whatever" part, it won't lead to an error page.
localhost:5000/1/2
, you can easily capture
the sum of the two numbers after the first slash and return it onto the page.
3.* Modify the function in exercise 2, and adapting the simple HTML page we made earlier, return the answer with the HTML instead.
4. Write another function, decorate it with an almost identical routing pattern used
in exercise 2, so that it returns "Not a number" when you visit URLs with
non-numerical values after the first slash, like localhost:5000/p/2
5. Create another HTML page called error.html inside the templates folder.
Then, write a function with @app.errorhandler(404)
above it so that when you visit
an unknown URL, your error.html is shown rather than Flask's
Not Found error page.
6.** If you've done the Beginners course, adapt the website you made for your competition such that the HTML, CSS and JavaScript files would load in correctly with Flask!