Flask is a Python which is based on Werkzeug, Jinja 2 and good intentions. Using Flask we can build Web and Restful applications with Python in an extraordinarily simple way.
In today’s example we are going to have a first contact with the microframework by building a Hello World with Python Flask.
The first thing will be to install the microframework, to do this we use the pip command.
pip install flask
Now we create a Python file called helloworld.py. The first thing we will do is import Flask.
from flask import Flask
The next thing will be to create the Flask application.
app = Flask(__name__)
Flask relies on the definition of routes or routes to implement endpoint implementations. A method is created with an implementation that ends up returning some type of content and a route is assigned to said method.
For example, we are going to create a method helloworld that simply returns a text with “Hello World!”.
def helloworld():
return 'Hello World!'
Now we are going to indicate that this method will be the one that responds to requests from the root of our server.
@app.route('/')
def helloworld():
return 'Hello World!'
We see that we have used the .route method with the route as a parameter to be able to assign said route.
We will only have to launch the application using the .run() method.
if __name__ == '__main__':
app.run()
When we run our python application.
python helloworld.py
We will have the web server running at:
http://127.0.0.1:5000/
So now we only have to run it in the browser to see our Hello World working with Python Flask.
