HTTP ans HTTPS are the most commonly used network protocols, powering nearly all web traffic. HTTP has more network overhead than MQTT and does not feature QoS features but has some other advantages. First of all, HTTP is rarely blocked by network firewalls, it is simple to test and well understood by many developers, features many libraries and frameworks to build solutions with it, and is more reliable if wanting to transmit data from the centralized infrastructure to the edge device.
Always keep security in mind when building web applications. If you write a web application, you are probably allowing users to register and leave their data on your server. The users are entrusting you with data. And even if you are the only user that might leave data in your application, you still want that data to be stored securely.
Flask protects you against one of the most common security problems of modern web applications: cross-site scripting (XSS). Unless you deliberately mark insecure HTML as secure, Flask and the underlying Jinja2 template engine have you covered.
Flask is no different from any other framework in that you the developer must build with caution, watching for exploits when building to your requirements.
Next chapters are based on https://data-flair.training/blogs/python-flask-tutorial/
A micro web framework itself written in Python, Flask is BSD-license. It was developed by Armin Ronacher, and is by Pocco- an international group of Python enthusiasts. It is based on the Werkzeug toolkit and Jinja2 template engine. Now, the latest stable version is 1.0, released in April 2018. Top applications that use it include Pinterest, LinkedIn, and the community page for Flask.
Since it does not need any tools or libraries, we can also call it a micro-framework. It also has no database abstraction layer or form validation. But we can find these features as extensions. These include form validation, upload handling, object-relational mappers, open authentication technologies, and common framework tools.
Here, some names around Python Flask include:
WSGI - (Web Server Gateway Interface the standard Python interface between applications and servers.
Werkzeug – A WSGI toolkit implementing requests, response objects, and other utility functions.
Jinja 2 – is a template language (engine) that renders the pages your application serves.
MarkupSafe - comes with Jinja. It escapes untrusted input when rendering templates to avoid injection attacks.
ItsDangerous - securely signs data to ensure its integrity. This is used to protect Flask’s session cookie.
Click - is a framework for writing command line applications. It provides the flask command and allows adding custom management commands.
SimpleJSON - is a fast JSON implementation that is compatible with Python’s json module. It is preferred for JSON operations if it is installed.
Flask is often referred to as a micro framework. It aims to keep the core of an application simple yet extensible. Flask does not have built-in abstraction layer for database handling, nor does it have form a validation support. Instead, Flask supports the extensions to add such functionality to the application. Some of the popular Flask extensions are discussed later in the section.
Python 2.6 or higher is usually required for installation of Flask. Although Flask and its dependencies work well with Python 3.x.
virtualenv is a virtual Python environment builder. It helps a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries.
The following command installs virtualenv:
pip install virtualenv
pip install command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If you are on Windows, log in as Administrator. On Ubuntu virtualenv may be installed using its package manager.
sudo apt-get install virtualenv
Once installed, new virtual environment is created in a folder.
mkdir newproj
cd newproj
virtualenv venv
To activate corresponding environment, on Linux/OS X, use the following −
venv/bin/activate
On Windows, following can be used
venv\scripts\activate
We are now ready to install Flask in this environment.
pip install Flask
The above command can be run directly, without virtual environment for system-wide installation.
Let's test
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello World"
if __name__ == '__main__':
app.run()
Importing flask module in the project is mandatory. An object of Flask class is our WSGI application.
Flask constructor takes the name of current module (__name__
) as argument.
The route()
function of the Flask class is a decorator, which tells the application which URL should call the associated function.
app.route(rule, options)
The rule parameter represents URL binding with the function.
The options is a list of parameters to be forwarded to the underlying Rule object.
In the above example, ‘/’ URL is bound with hello_world()
function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered.
Finally the run()
method of Flask class runs the application on the local development server.
app.run(host, port, debug, options)
Picture 3. Connection parameters.
The flask.Flask
object is a WSGI application, not a server. Flask uses Werkzeug's development server as a WSGI server when you call python -m flask run
in your shell. It creates a new WSGI server and then passes your app as parameter to werkzeug.serving.runsimple_. So, we have to do that manually.
#In order to test Flask installation, type the following code in the editor as Hello.py
#When using Jupyter Notebook, we can use these kind of command to install nessessary environment:
import sys
!{sys.executable} -m pip install virtualenv
!{sys.executable} -m pip install Flask
from flask import Flask, escape, request # pip install Flask, escape and request
# Pass in name to determine root path, then Flask can find other files easier
app = Flask(__name__)
# Route - mapping (connecting) a URL to Python function
@app.route('/')
def hello():
name = request.args.get("name", "Hello Pakistan, Greetings from Finland!")
return f'Hello, {escape(name)}!'
# http://127.0.0.1:5000/
Output when run command line:
$ env FLASK_APP=Hello.py flask run
* Serving Flask app "Hello"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
A Flask application is started by calling the run()
method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors in the application, if any.
The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run()
method.
app.debug = True
app.run()
app.run(debug = True)
Web frameworks use the routing technique to help a user remember application URLs. It is useful to access the desired page directly without having to navigate from the home page.
The route()
decorator in Flask is used to bind URL to a function.
@app.route('/hello')
def hello_world():
return "hello world"
Here, URL /hello
rule is bound to the hello_world()
function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world()
function will be rendered in the browser.
The add_url_rule()
function of an application object is also available to bind a URL with a function as in the above example, route()
is used.
A decorator’s purpose is also served by the following representation:
def hello_world():
return "hello world"
app.add_url_rule('/', 'hello', hello_world)
It is possible to build a URL dynamically, by adding variable parts to the rule parameter. This variable part is marked as variable-name. It is passed as a keyword argument to the function with which the rule is associated.
In the following example, the rule parameter of route()
decorator contains __name__
variable part attached to URL /hello
. Hence, if the http://localhost:5000/hello/Pakistan_VU is entered as a URL in the browser, ‘Pakistan VU’ will be supplied to hello()
function as argument.
@app.route('/hello/<name>')
def hello_name(name):
return 'Hello %s!' % name
if __name__ == '__main__':
app.run(debug = True)
Save the above script as hello.py and run it from Python shell. Next, open the browser and enter URL http://localhost:5000/hello/Pakistan_VU.
The following output will be displayed in the browser.
Hello Pakistan VU!
Flask’s documentation can be found here and very useful Flask tutorial is here.