Flask is a Python-written web development framework (It is created by Armin Ronacher). A web application framework is a set of libraries and modules that helps a web application developer to create apps.
The WSGI toolkit and Jinja2 template engine are made for Flask. A web templating system combines a template with data to render dynamic web pages.
Related course: Python Flask: Create Web Apps with Flask
python flask app
First install the Flask module using pip or easy_install. Write this code into the IDE to test the installation of Flask. Save it as hello.py
from flask import Flask |
It is required to import the Flask module.
from flask import Flask |
Create your Flask app object:
app = Flask(__name__) |
The Flask @route
decorator associates the function with the URL.
|
The ‘/‘ URL is linked to the hello_world()
function in this example.
The function return, returns output to the web browser.
return 'Hello World’ |
The call .run()
starts a local web server, where your Flask app runs.
The Python script can be executed from the shell of from a Python IDE.
python hello.py |
A message tells you that the server is running on your computer
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) |
In a web browser, open the URL localhost:5000/ and the text ‘Hello World’ will appear.
Btw, you can easily Deploy your Flask app
debug mode
The run() method is used to initiate a Flask app. The program needs to be manually restarted for each change, the debug function stops this inconvenience. When you change the code, the server reloads itself.
Instead of app.run()
you can do one of these:
app.debug = True |
routing
Web frameworks use routing to help users remember URLs. It is convenient to access the requested page immediately without the need to browse the home page.For example, it’s easier to remember /register/ or /videos/ than an URL like ?pageId=5&x=3.
The Flask .route()
decorator connects the URL to the function.
|
The ‘/hello’ URL route is linked to the function hello_world()
.
If a user types localhost:5000/hello
in the web browser, it shows the output of the function.
Each route should have a unique function name.
Related course: Python Flask: Create Web Apps with Flask