flask
Web Application framework for Python
What is Flask
Micro web framework written in Python - "micro" because it does not require particular tools or libraries. Flask supports extensions that can add application features as if they were implemented in Flask itself. Extensions exist for object-relational mappers, form validation, upload handling, various open authentication technologies and several common framework related tools.
Applications that use the Flask framework include Pinterest, LinkedIn and the community web page for Flask itself.
Why we want to use Flask
Easy to use
Built in development server and debugger
Integrated unit testing support
RESTful request dispatching
Uses Jinja2 templating
Support for secure cookies (client side sessions)
100% WSGI 1.0 compliant
Unicode based
Extensively documented
Google App Engine compatibility
Extensions available to enhance features desired
Installing Flask
Installing Flask is very simple, use the following command (you can create a virtual environment for you project)
pip install Flask |
Hello World
Create a directory that will hold your project. You can do this using Terminal/Command Promt
mkdir HelloWorld |
Alternatively you can use an IDE, in our case we used PyCharm CE. Click on File→NewProject , select location for your project and name it HelloWorld
Note: PyCharm CE doesn't have in-built support for Flask framework.
Inside your project (or folder if you're using Terminal/Command Prompt) create a file called helloworld.py. In the simplest form, it's enough for our web application to contain the following code
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run() |
Let's have a look at what the code actually does:
First we imported the
Flask
class. An instance of this class will be our WSGI application.Next we create an instance of this class. The first argument is the name of the application’s module or package. If you are using a single module (as in this example), you should use
__name__
because depending on if it’s started as application or imported as module the name will be different ('__main__'
versus the actual import name). This is needed so that Flask knows where to look for templates, static files, and so on. For more information have a look at theFlask
documentation.We then use the
route()
decorator to tell Flask what URL should trigger our function - binds any incoming HTTP requests coming to the root URL to the function called helloThe function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user’s browser.
To run this application type the following command into your Terminal/ Command Prompt:
Note: Many examples you can find online use the environemnt variable called FLASK_APP to specify the file to run as a flask application. We don't need to do it, as we added the if statement (mentioned in point 2 above) at the end of our code. We can use the same place to also specify the runtime environment - for example a particular IP:<port> address as below:
We can now open an internet browser and navigate to http://localhost:5000/ . You should see something similar to the following screenshot
Return Type
In the example above, for every HTTP request we receive we return a String. However, we can return also larger amount of data - formatted as JSON for example, or even views (HTML).
JSON
If we want to send JSON data back to the client, we can use dumps() method provided in the json module which is part of the Standard Library. Here is an example code, we create a dictionary collection holding information about some European countries and their capitals, we include it in the response in JSON format.
Notice the additional import statement at the top of the page. If we navigate to the same URL (http://localhost:5000/) we will be presented with the following data
View
Instead of sending bare data back to the clint, we can serve back a view (HTML+CSS) which would display the data in a nice way. To do so, we need to create a HTML page (let's call it capitals.html) in a templates folder. We also need to import and additional package from the flask module - render_template - which will help us to not only return the data but also a name of template which can display it. The amended code will look like this
Flask leverages Jinja2 as template engine which means that we can combine HTML and Python in a neat way - i.e. we can access data that has been returned and needs to be displayed, we can easily loop through collections, we can use the usual Python structures and built-ins. Here is an example of the capitals.html page which uses jinja template
The {% symbols denote Python code. Running our flask application now and navigating to http://localhost:5000/ will give this result
http://flask.pocoo.org/docs/1.0/quickstart/
https://pythonspot.com/flask-hello-world/
https://en.wikipedia.org/wiki/Flask_(web_framework)