Now that Flask is installed, let's write our first application. This will be a very simple application that returns the famous programming statement - Hello World!
WEBSERVER
One of the great things about developing using Python and Flask is that you get a free development web server while you are developing your application. We will use this to test our application.
A small note on additional tools. I've left out a discussion on what tools you can use to write code. I use Visual Studio Code - the free version - to do most of my work. This code editor is extremely powerful, popular and works on most operating systems. It is definitely available on Windows, Mac and Linux.
However, for most of the work we'll be doing, you can use Notepad on Windows, and any text editor on Mac or Linux. Python comes with a free code editor called Idle. I found this tutorial at Idle at RealPython to be the most informative. But a quick Google search for Python Idle and you will find a ton of resources.
COMMAND PROMPT
Open a command prompt and create a folder for your work. Then inside that folder, create a text file. I normally name my main Python/Flask application file app.py.
Open app.py and type in the following code - we'll discuss it line by line.
Line Number | Description |
---|---|
1 | This is the import line that imports the flask module into our application. |
3 | This creates a Flask object. You'll need exactly one of these in your application. This Flask object handles all the requests from the user on the other side of the Internet. |
5 & 6 | Line 5 is syntax you may not be used to. This is called a decorator. It's job is to add some special features to the function defined right after it. In this example, the decorator says that the route specified by the backslash should be handled by this function. The Python function (created using the def keyword) can be called anything. In our example, we've called it index. In our web application, this means that the user will go to my.website.com/ - note the trailing slash. Line 6 is the definition of the actual function that processes the request from the user. In this case, it's only one line, that returns a string - "Hello World!" |
10 - 11 | These are our typical Python execution lines. If you haven't seen them before, they execute if the module (in this case app.py) is called directly from the command line - but not execute if called from a different module. |
That's it. We have some working code, hopefully no syntax error bugs.
Next step is to start the webserver which will run our application and then using a web browser we will test the code.
LOCAL TESTING
As you develop your application, you'll use the special address for your local computer - 127.0.0.1 (or localhost). The Python/Flask environment will make sure that the correct settings (such as opening a port for your browser) are configured.
Let's see how that works in the next tutorial.
No comments:
Post a Comment