FLASK is a extensible micro-web application framework. It is a collection of libraries and modules which enables us to write code without managing or worrying about low level details such as protocols, thread management etc.
Ex: Flask, Django, TurboGears , web2py etc.
All these frameworks are WSGI(web server gateway interface) combined which is the standard prescribed for python based we app.
But ,wait! What does extensible micro here means????
This means that Flask does not provide all the facilities of web development .
example, validating of forms or database handling.
Then, why are we using it???
The answer is that using some extensions we can implement these functionalities , hence the term extensible. Ex: For validation in forms we can use WTFORMS extension and for database handling we can use SQLALCHEMY extension which we will be discussing later on in this article.
Flask is based on Werkzeug toolkit and Jinja2 template engine , both of which are Pocco Projects.
Werkzeug is a toolkit to implement request and response objects. It enables web frameworks to work on top of it. It also does HTTP header parsing and provides unicode, session and cookie support to us.
Jinja2 is a web templating system which combines template with a certain data source to render dynamic web pages. It helps us to represent data in different forms which are attractive and readable. Combining data and template gives us final output.
Now , let’s set the environment for Flask.
Setting Environment for FLASK
First step is to create a virtual environment to save us from any dependency problems.
To do this, we first install virtualenv and then create the environment in the project directory .
Now, we activate this environment and install flask.
Now, check if flask is working or not by using import statement. If no errors come then , we are good to go for our first flask app.
HelloWorld App in Flask
Now , we create our first app.
Create a file named Hello.py and write the following code in it:
Flask constructor here takes the name of the current module(__name__) as argument.
route() function is a decorator which tells the app which URL should call the associated function.
rule tells us about the URL binding and options is a list of parameters to be forwarded to underlying rule object which we will see after some time.
Finally, run method used runs the flask app on the local sever by default.
Default host is 127.0.0.1 and port is 5000and debug is false by default.
So, now let’s run this app.
Go to 127.0.0.1:5000 from browser to see the output.
Now, make some change in the code and save it. However, we will see that these changes are not reflected in our app on browser.
But , if we close the app and restart the app and refresh the page in browser we will see the changes.
Now, set the debug as True and do the same thing, we will see that we don’t need to restart the app to see the changes on the browser. As soon as we save the code, changes will be reflected on the browser.
This is used quite often in development part of app to save time as Flask automatically restarts the app.
However, development environment is present only on local server and we cannot use this when we use 0.0.0.0in host as it is used to make our app available externally. Therefore , in that case don’t use debug=True.
Routing in Flask
Routing is used to remember URLs and are used for direct navigation to pages.
Route() decorator is used to find URL to a function.
Let’s see how this happens.
Here , / rule is binded to hello function and /Hello rule is binded to hello_new function.
So, if client comes on 127.0.0.1:5000/ , output of hello function will be seen and if client comes on 127.0.0.1:5000/Hello then output of hello_new function can be seen.
It is possible to build URL dynamically by adding variable part to rule parameter. <> is used for the variable part and is passed as keyword argument.
Let’s see how this is done and how dynamic URL will be created.
Now, if client access 127.0.0.1:5000/hello/abhi, then abhi is passed in <name> and we see abhi in the webpage. If we pass,127.0.0.1:5000/hello/rohit , then we will see rohit in the web page.
Flask URL Binding
url_for(function,variable_part) function is used to build URL dynamically for a specific function.
It will allow us to change URLs at one go, without having to remember URLs.
URL binding will handle escaping of special characters and Unicode data.
Let’s see how this works.
Here, the user needs to remember only 1 URL i.e. 127.0.0.1:5000/guest/ .
When he enters the /admin after , he gets the output of /admit route and when he enters something else , he sees output /guest/<guest> output.
redirect function is used to redirect the output to a different route which is fetched from url_for funcion.
GET-The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data.
HEAD-Same as GET, but transfers the status line and header section only.
POST-A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms.
PUT-Replaces all current representations of the target resource with the uploaded content.
DELETE-Removes all current representations of the target resource given by a URI.
CONNECT-Establishes a tunnel to the server identified by a given URI.
OPTIONS-Describes the communication options for the target resource.
TRACE-Performs a message loop-back test along the path to the target resource.
By default, Flask responds only to GET request. However ,we can alter this by providing parameters in route() decorator.
Let’s create a form and submit it using POST method and see how Flask will act upon it.
Here, we are submitting using POST request method and the submitted value is retrieved in flask code using request object . This is done as:
Similarly , if we use GET method, then we will get the same output but
then the parameter is retrieved by:
TEMPLATES IN FLASK
Let’s see how can we include HTML in our Web App:
But, when the code becomes too large for HTML, this is not the preferred practice as it reduces readability of code.
So, a better option is to create a HTML file first. For this, in our project folder create a folder called templates and put there the index.html file and then we will use render_template function to render html file.
Now, let’s see how can we add CSS or JS in our HTML code.
For this, create a folder called static in project directory and put the CSS or JS code there.
Here, static is a special endpoint which refers to static folder and it’s value is obtained by url_for function.
Let’s see how this can be done:
Let’s see the output and see the output of JS.
Request Object in Flask
Data from client’s web page is sent to server as a global request object.
Important attributes of this Request object are: Form(Post or Put), args (get), values(form and args both), cookies, headers, data , files(when files are uploaded by client), environ, method, module, routing_exception.
When HTML form is submitted by POST method, this is used.
Function bound to URL receives form data in request.form object.
Let’s create a form and submit all the values and print them on our webpage in form of table.
This will also help in introducing the Jinja Template.
Here, we used jinja template in table.html where it is printing variables from the python file.
Let’s see how we can use if-else in jinja template to give title to our webpage.
To read more about Jinja2:
Cookies are stored on client’s computer as a text file. It’s task is to remember and track the data pertaining to client’s usage for better visitor experience.
Request Object contains a cookie attribute. It is a dictionary object and has values that cookies transmitted. Cookie also stores it’s expiry time, path and domain name of site.
In flask , cookies are set on response object.
We use make_response() function to get response object from return value of view function.
We use set_cookie() of response object to store a cookie.
get() method is used to read a cookie.
Let’s see how to set cookie and read it.
Setcookie.html is actually the form displayed in the background.
Unlike cookie, session data is stored on the server. Session is the time interval between client logs in and logs out of it.
Data needed to be held across a session is stored at a temporary location on the server. Session with each client has a Session ID.
Session data is stored on top of cookies and server signs them cryptographically.
For encryption , Flask needs a SECRET_KEY.
Session object is also a dictionary object with session variables ad their corresponding values.
To set secret key:
To set session variable:
To release a session variable:
Flask will take the values that we initialize in session object and serialize them into cookies.
Next, time we will see that user has already logged in as we have set the cookie.
FLASK REDIRECTS AND ERRORS
REDIRECT function of flask returns a response object and redirects user to other target with specified status code.
Here, location is the parameter which is the URL where response is directed.
Status code is sent to browser’s header(default=302). To read more about status codes:
response parameter is used to instantiate response.
Flask also has a abort() for early exit with a error code.
A good GUI application provides feedback to user about the interaction.
Flashing system makes it possible to create a message in one view and render it in view function called next.
message is the actual message to be displayed and category is either error , info or warning.
To remove message from session, template calls get_flashed_message(with_categories, category_filter).
Here ,we see that if we pass the wrong username and password , a message is displayed on the browser itself.
Uploading Files in FLASK
HTML form with type set to ‘multipart/form-data’ and method attribute set to POST are used to upload files.
The URL handler fetches file from request.files object and saves it to desired location.
Name of destination-file can be hardcoded or can be retrieved by request.files[file] object for same name as client’s computer.
However , a more secured version is used.
from werkzeug import secure_filename
Each file is first uploaded to a temporary location and then saved to a final location.
app.config[‘UPLOAD_FOLDER’] is used to set upload folder.
app.config[‘MAX_CONTENT_PATH’] tells maximum file size to be uploaded.
Let’s see how this is done:
Now, just select the file and upload the file. Uploaded file will be seen in the project directory.
Flask extensions are just python modules which provide additional functionalities to flask.
They are downloaded by pip utility.
We will discuss Flask Mail, WTForms, SQLAlchemy and SQLite in this article first.
First install Flask-Mail using pip.
Flask-Mail is configured through the standard Flask config API.
- MAIL_SERVER : default ‘localhost’
- MAIL_PORT : default 25
- MAIL_USE_TLS : default False
- MAIL_USE_SSL : default False
- MAIL_DEBUG : default app.debug
- MAIL_USERNAME : default None
- MAIL_PASSWORD : default None
- MAIL_DEFAULT_SENDER : default None
- MAIL_MAX_EMAILS : default None
- MAIL_SUPPRESS_SEND : default app.testing
- MAIL_ASCII_ATTACHMENTS : default False
Also , remember to allow less secure apps from google account settings to enable python use the account.
FLASK WTF Extension
This extension is used for validation of forms and provides UI for form rendering.
It helps in creating forms dynamically.
This extension has a Form class which is used as parent for user defined form.
Also, here a hidden field for CSRF token is created automatically. This is done to prevent cross side forgery attack.
validate() function of form object validates form data and throws validation error if validation fails. Error messages are sent to template.
In HTML, error messages are rendered dynamically.
Let’s see the output now,
To read more about WTF-extension, refer to:
SQLite is a self-contained server-less, zero-configuration transactional SQL DB Engine. They are fully ACID-complaint.
Also, sqlite3 is preinstalled so we don’t need to install it.
conn = sqlite3.connect('database.db')
print "Opened database successfully";
conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)')
print "Table created successfully";
Follow along this brilliant article to see the connection of SQL with flask:
For your easiness , I am uploading all the code inside my GitHub :
Most of the programming languages today are OOPs based but data in RDBMS is stored in terms of tables.
So, Object Relational Mapping(ORM) is a technique of mapping object parameters to underlying DBMS table structure.
An ORM API provides methods to perform CRUD operations without having to write raw SQL statements.
SQLAlchemy provides a method of associating Python Class with DB table and objects with rows in their corresponding tables.
Let’s us see how this can be done:
First let us install SQLAlchemy:
Object of SQLAlchemy class has helper functions for ORM operations.
It also provides a parent Model using which all user defined models are build.
Each model is a table in the database.
URI of Database can be set as:
Here, student is our database name.
To create the database mentioned in URI: db.create_all() is run, where db is sqlalchemy class object.
ORM’s handle to the database is the Session.
db.session.add(model obj): inserts a record into mapped table.
db.session.delete(model obj): deletes record from table.
model.query.all(): retrieves all records from the table.
model.query.filter(condition): Applying filter to retrieved records.
Here, db.model is the base class for every other model that we want to make.
To create the database, we use create_all() -
Now, use will see students db in your flask app directory.
GitHub Code for above files are:
To read more about SQLAlchemy on how to create relationships, refer to:
The deployment of Flask can be done on AWS, GCP using App Engine , Heroku and Docker Container.
To read more about it:
Also , giving credit where credit is due, I would suggest to go through Miguel’s blog to know about BEST practices to use Flask , Database Migrations, Template inheritance and other features cause there’s a lot what you can do with Flask.
Or you can also checkout Corey Schfaer’s Youtube playlist on Flask now that you read many things about Flask.