In this lesson, you will learn how a flask web app works. The code we have so far is a typical flask script that builds a simple website. So, we’re going to explain what that code does line by line. This is what we have so far:
from flask import Flask
app = Flask(__name__)
return "Hey there!"
if __name__ == '__main__':
In line 1 you are making available the code you need to build web apps with flask. Flask is the framework here, while Flask is a Python class datatype. In other words, Flask is the prototype used to create instances of web application or web applications if you want to put it simple.
So, once we import Flask, we need to create an instance of the Flask class for our web app. That’s what line 3 does. __name__ is a special variable that gets as value the string "__main__" when you’re executing the script. We’ll go back to that in a moment.
In lines 5-7, we are defining a function that returns the string “Hey there!”. That function is mapped to the home ‘/’ URL. That means when the user navigates to localhost:5000, the home function will run, and it will return its output on the webpage. If the input to the route method was something else, let’s say ‘/about/’, the function output would be shown when the user visited localhost:5000/about/. How practical is that?
Then we have the mysterious lines 9 and 10. Something you should know is that Python assigns the name "__main__" to the script when the script is executed. If the script is imported from another script, the script keeps it given name (e.g. hello.py). In our case, we are executing the script. Therefore, __name__ will be equal to "__main__". That means the if conditional statement is satisfied and the app.run() method will be executed. This technique allows the programmer to have control over the script’s behavior.
Notice also that we are setting the debug parameter to true. That will print out possible Python errors on the web page, helping us trace the errors. However, in a production environment, you would want to set it to False as to avoid any security issues. So far, so good!
We have a running website with some content returned by the Python function. As you can imagine, returning plain strings from a function doesn’t take us anywhere far.
If you want to make something more serious and more visually appealing, you would want to incorporate HTML files along your Python file and have your Python code return HTML pages instead of plain strings.
You will do just that in the next lesson.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.