Friday, September 16, 2022

Flask Tutorial for beginners - Part 5

At this point you are ready to start the webserver and make sure your application is working. From the command line run the app.py file.

python app.py

You'll see output that looks like the following.


Note a couple of warnings regarding the fact that this is a development server.

Note the command I used to run the application.

Now using your web browser, go to the link specified. In the example above, it's 

http://127.0.0.1:5000

There's another way to run the application. Stop the current process using the CTRL+c keystroke. Now start the application again by typing:

flask run

You'll see something like the following.


The information here is similar, except for a couple of things. Firstly, the port number has changed, also, you can see two addresses to get to the application. This is because I have set a couple of environment variables before typing in flask run.

To set the environment variables on Linux/Mac, I typed:

export FLASK_DEBUG=1
export FLASK_APP=app.py
export FLASK_RUN_HOST=0.0.0.0
export FLASK_RUN_PORT=8080

The first export (DEBUG) runs the application in debug mode. This means that errors in the application will be displayed, not just on the console, but also in the web browser. This setting should not be enabled on a production server since users will also be able to see details on all errors.

The second export (APP) tells the command (flask run) which flask module to run.

The third export (RUN_HOST) indicates that the application should be accessible on all available addresses. This is useful if you need to access the application from a machine different from your development machine.

Last export (RUN_PORT) specifies the port that the application should listen to. You won't see this port on regular web requests since most browsers know that http is port 80 and https is port 443.

EXERCISES

You can now run a simple response application. Make the following changes to the application.

  1. Change the response string - instead of Hello World! return something like "Thanks for visiting"
  2. In your response, make one of the words bold (use HTML).
  3. In your response send a HTML link to a website so that when the user clicks on it, they are redirected to that page.
Can you find out how to make the environment variables permanent on your system?










No comments:

Post a Comment