Tehnologii Web/2022-2023/Laborator 7

Flask Framework

edit

For this, we need:

  • a local Python3 programming environment,
  • an understanding of basic Python3 concepts such as data types, lists, functions, and other similar concepts,
  • an understanding of basic HTML5 concepts.

Flask installation

edit

Following this step, we will enable the appropriate Flask Python environment. It is necessary to install Flask using the pip3 package installer.

First, open the programming environment, for example, PyCharm, and create the project directory: flask_app. Next, install Flask using pip3 install in PyCharm's terminal:

pip3 install flask

In the process of installing Flask are also installed other libraries. These libraries are dependencies that Flask needs to perform various functions.

Note. If a Flask application is opened in PyCharm Professional, this library is automatically installed.

Creating a simple application

edit

In the flask_app directory, open the file named app.py. If it does not exist, it will be created by: right click on the directory -> New -> Python File.

Enter the following code in the app.py file:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return '<h1>Hello, World!</h1>'

In the code block above, the Flask object from the flask package is first imported. It is then used to instantiate the Flask application, giving it the name app. The special variable __name__ will be passed as a parameter, which holds the name of the current Python module. This name indicates the instance; this is needed because Flask creates some paths behind the scenes. Once we create the application instance, we can use it to handle incoming web requests and send responses to the user. @app.route is a decorator that turns a Python function into a Flask view function, which converts the function's return value into an HTTP response that will be displayed by an HTTP client such as a web browser. Pass the value "/" to @app.route() to signify that this function will respond to web requests for the / URL, which is also the main URL. The hello() view function returns the string Hello world! as the HTTP response. We now have a simple Flask application in a Python file called app.py. In the next step, we will run the application to see the output of the hello() view function rendered in a web browser.

Run the application

edit

After you create the file containing the Flask application, you'll run it using the terminal in PyCharm to start the development server and render the HTML code you wrote to the browser as the return value for the hello() view function. To be sure that the correct path has been found, we first enter:

* for Unix 
$ export FLASK_APP=app
*for Windows
$ set FLASK_APP=app

And then specify the running mode of the application, i.e. development, to use the debugger to catch errors. The following line of code is used:

* for Unix
$ export FLASK_ENV=development
*for Windows
$ set FLASK_ENV=development

Finally, the application is run using:

$ flask run

The output will have information such as:

  • The name of the application being run ("app").
  • The environment in which the application is run (development).
  • Debug mode: on means the Flask debugger is running. This is useful in development as it provides detailed error messages.
  • The application runs locally on the URL localhost:5000/.

Open a browser and enter the URL localhost:5000/ or click on it. You will see the text Hello, World! in the header as a response. This confirms that the application is running successfully.


To stop the server, press: CTRL+C

Note. Cannot run two Flask applications on the same port. This can be changed to :5001 using flask run -p 5001 and the second application will run without any problem.

Statement. Now there is a small Flask web application. The application ran and displayed information in the web browser. Next, you'll learn about routes and how to use them to have multiple web pages.

View routes and functions

edit

In this step, we will add some routes to the application to display different pages depending on the requested URL. We will also learn about the view features and how to use them. A route is a URL that can be used to determine what the users get when they visit the web application in their browser. For example, localhost:5000/ is the main route that can be used to display an index or home page. The URL localhost:5000/about can be another route, used to give the visitor some information about the web application. Similarly, a route can be created to allow users to log in to the application by following an authentication procedure: login or registration, at localhost:5000/login or localhost:5000/register. The Flask app currently has one route, with the root URL (localhost:5000/). To demonstrate how to add a new web page to the application, we will edit the app.py file to add another route that provides information about the web application at localhost:5000/about.

The code will look like this:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello():
    return '<h1>Hello, World!</h1>'


@app.route('/about/')
def about():
    return '<h4>This is a Flask web application.</h4>'

We added a new function called about(). This function is decorated with the @app.route('/about/') decorator which turns it into a view function that handles requests for the localhost:5000/about endpoint.

Question. What will happen if an additional decorator is added to the main route function, hello()?

@app.route('/')
@app.route('/index/')
def hello():
    return '<h1>Hello, World!</h1>'

We notice that the @app.route('/index/') decorator has been added

After adding this new decorator, it will be possible to access the Hello, World! to both localhost:5000/ and localhost:5000/index.

Dynamic routes

edit

In this step, we will use dynamic routes to allow users to interact with the application. It will transform a route that is lowercase to uppercase through different URLs, and a route that adds two numbers and displays the result.

Note. Normally, users do not interact with a web application by manually editing the URL. Rather, the user interacts with elements on the page that lead to different URLs depending on user input and action, but just for a demonstration, we will edit the URL to prove how to make the app respond differently to different URLs.

If you allow the user to submit something to your web application, such as a value in the URL, as you will in the next edit, you should always keep in mind that your application should not directly display unsafe data (the user submits data). To display user data safely, use the escape() function that comes with the markupsafe package, which was installed with Flask.

from markupsafe import escape
from flask import Flask


@app.route('/capitalize/<word>/')
def capitalize(word):
    return '<h1>{}</h1>'.format(escape(word.capitalize()))

With the development server running, open the browser and visit the following URLs. You can replace the highlighted words with any word of your choice.

http://127.0.0.1:5000/capitalize/testing
http://127.0.0.1:5000/capitalize/verify
http://127.0.0.1:5000/capitalize/words

This new route has a <word> variable section. This tells Flask to take the value from the URL and pass it to the view function. The <word> URL variable passes a keyword argument to the capitalize() view function. The argument has the same name as the URL variable (word). With this, we can access the passed word via URL and respond with an uppercase version using the capitalize() method in Python.

Also, multiple variables can be used in a route. To demonstrate this, we will create a route that adds two positive integers and displays the result.

@app.route('/add/<int:n1>/<int:n2>/')
def add(n1, n2):
    return '<h1>{}</h1>'.format(n1 + n2)

In this route, a special int converter is used with the URL variable (/add/<int:n1>/<int:n2>/) which only accepts positive integers. By default, URL variables are assumed to be strings. With your development server running, open the browser and visit the following URL:

http://127.0.0.1:5000/add/7/8/

The result will be 15, which is the sum of the two entered numbers.