Unlock the Power of Flask: Building a flask Mini App Beginner Guide
We all know April Fools’ Day is approaching, but before you get fooled, let’s speak about a prank that has grown to the point of being an application. Armin Ronacher of Pocoo invented Flask as a joke and ended up with a Python-based microframework. See https://en.wikipedia.org/wiki/Flask_(web_framework)#:~:text=Flask%20was%20created%20by%20Armin,make%20into%20a%20serious%20application for more information on flask.
Creating a mini app with flask is an easy beginner task.First of all it is necessary to create an environment to avoid conflicts between files:
$ mkdir myproject
$ cd myproject
$ python3 -m venv .venv
Then activate the environment:
$ . .venv/bin/activate
Now download your flask into the file you’re coding from within the environment:
$ pip install Flask
Once the download is complete you are ready to create you’re first mini application.
First we import the flask class and secondly create an instance of the class:
from flask import Flask
app = Flask(__name__)
Creating routes is one of the base routes of flask.Below we will create a route that just says hello world:
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
route()
decorator to tell Flask what URL should trigger our function.The symbol ’/’ just represents the home page of the application which will display Hello World!
To run the Flask application:
if __name__ == '__main__':
app.run(debug=True, port=5070)
In the context of a Flask application, app.run()
is a method that starts the Flask development server. By using if __name__ == '__main__':
, you ensure that the Flask development server starts only when the script is run directly (i.e., as the main program), not when it's imported as a module into another script.
For the final sample,you will have an app.py file and in it you will have:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
if __name__ == '__main__':
app.run(debug=True, port=5070)
And there you go your first flask miniapp. If you get stuck feel free to ask.