Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Web Applications

Here are resources that you can use to build your web project:

00:00 Next, let’s take a look at coding the application for the web. Now, you’re going to see that simple addition program created for the web using flask. If you’re not aware of how flask works, Real Python has many courses available to get you up to speed. Firstly, we’ll import all the required elements from flask.

00:22 Next, the Flask application is created. To allow for safe use of the session cookie we’ll need to add a .secret_key, and obviously, in a real application, that would be kept secret from everyone.

00:37 Now, you’ll see a definition of the application’s routes by creating functions which are wrapped in the @app.route. This function will output a simple HTML form, which I’m going to wrap in triple quotes (""").

00:53 I’m going to paste in the code necessary for brevity. As you can see, it’s a simple HTML <form> which returns two values "a" and "b" when the form is submitted.

01:06 Next, it’s simply a case of getting the function to return that HTML output. Next up, an @app.route, which is going to accept the information from that form.

01:21 Here, the request.method is going to be checked by the function, and if it’s a "POST", the values of 'a' and 'b' will be collected and placed into the session cookie.

01:36 Once this has been done, we will be redirected to the results page. If this wasn’t a "POST", i.e. it was a "GET", then we’ll redirect the user back to the root of the site for the HTML form.

01:50 Finally, the result page needs to be added. Here, the values of 'a' and 'b' will be taken from the session cookie and cast into integers.

02:03 The result is calculated and the result is then returned to the user. In this case, there’s not any HTML formatting, but you can imagine there would be even more overhead if a fully-formatted HTML page was going to be returned to the user.

02:19 Finally, let’s add some code that will simplify running this directly from Python, and now we’re ready to see that in action.

02:34 Here, you can see the URL that’s needed for the browser…

02:41 and now you can see the web version. Entering two numbers… 3 and 7. We press submit. And as you can see, the addition has been calculated and we’re forwarded to the new page with the result.

Become a Member to join the conversation.