An Easy introduction to Flask Framework for Beginners
Introduction
Developing dynamic and interactive web applications has become crucial in the current digital era, and Flask, a flexible and lightweight Python framework, is a great place to start for people who are new to web programming. This article will give you a strong foundation to start your Flask Python journey, whether you’re an experienced programmer exploring new technologies or a coding enthusiast taking your first steps.
We’ll delve into the fundamental concepts, guide you through setting up your development environment, and empower you to build your first web application with Flask. Get ready to unlock the potential of web development as we demystify Flask and pave the way for your exciting learning experience.
This article was published as a part of the Data Science Blogathon.
Table of contents
What is Flask?
Python’s Flask micro web framework can be used to build web-based apps for interacting and displaying data-driven content. Although Flask is more frequently associated with web development, it can also be used in data science to create straightforward web interfaces, APIs (Application Programming Interfaces), and visualisation tools that enable data scientists and analysts to present their data and analyses in a user-friendly and interactive way.
What is Flask Python Used For?
Python’s Flask micro web framework is well-liked and frequently used to create online apps. It offers a straightforward and adaptable method for developing Python-based web applications and APIs (Application Programming Interfaces). Flask is renowned for its straightforward design, which gives developers the freedom to select the elements they desire and customise their apps to meet their needs.
Common Uses of Flask
Here are some common uses of Flask:
- Web Applications: Flask builds various types of web applications, including blogs, e-commerce sites, social media platforms, and more. Its simplicity and flexibility make it suitable for both small projects and larger, more complex applications.
- API Development: Create RESTful APIs that enable communication between different software systems. Use these APIs to share data, perform actions, and integrate various services.
- Prototyping: Flask’s lightweight nature makes it a great choice for quickly prototyping web-based ideas and concepts. It allows developers to rapidly create and test their ideas without the overhead of more complex frameworks.
- Microservices: Flask lends itself well to constructing microservices, which constitute small, autonomously deployable constituents within more extensive applications. Developers can construct each microservice utilizing Flask to offer distinct functionalities.
- Webhooks: Webhooks function by obtaining data from external services upon the occurrence of particular events. Flask enables the creation of endpoints capable of listening for these events and initiating actions within your application.
- Interactive Dashboards: Flask can be used to build interactive dashboards that visualize data in real-time. This is useful for data analysis, reporting, and monitoring purposes.
- Educational Projects: Flask is often used in educational settings to teach web development concepts due to its simplicity and clear structure. Students can quickly learn about routes, templates, and interactions between the front end and back end.
- Small to Medium-sized Websites: For websites that don’t require the complexity of larger frameworks, Flask provides a lightweight alternative that still supports various features.
- Integration with Data Science and Machine Learning: Flask empowers the creation of web interfaces for data science and machine learning models, facilitating user interaction and utilization of these models without the necessity of comprehending the underlying code.
What is a Framework?
The framework is the basis upon which software programs are built. It serves as a foundation for software developers, allowing them to create a variety of applications for certain platforms. A set of functions and predefined classes used to connect with the system software and handle inputs and outputs. The life of a developer while giving them the ability to use certain extensions and makes the online applications scalable and maintainable.
Frontend Development vs Backend Development
- The front end of a website is the area with which the user immediately interacts. It contains everything that users see and interact with: text colours and styles, images and videos, graphs and tables, the navigation menu, buttons, and colours. HTML, CSS, and JavaScript are used in developing the front end. Some of the frameworks for frontend are:
- AngularJS
- Sencha Ext JS
- React
- The backend of a website refers to the server-side of the website. It saves and organizes data and ensures that everything on the client-side of the website functions properly. It is the section of the website that you are unable to interact with or access. It is the part of the software that has no direct communication with the users. Back End development is done using Java, Python, C#, and JavaScript. Some of the framework for the backend are :
- Flask
- Tornado
- PyramidArmin Ronacher
- Django
Flask Framework
Flask is used for developing web applications using python, implemented on Werkzeug and Jinja2. Advantages of using Flask framework are:
- There is a built-in development server and a fast debugger provided.
- Lightweight
- Support Secure cookies
- Templating using Jinja2
- Request dispatching using REST
- Support for unit testing is built-in
Installation of Flask
Python Version
Install the latest version of Python or at least use a version >= Python 3.7
Creating Virtual Environment
Virtual environments are separate collections of Python libraries, one for each project. Installed packages for one project do not affect other projects or the operating system’s packages. Python has the venv package, which allows you to build virtual environments.
For Windows
> mkdir myproject
> cd myproject
> py -3 -m venv venv
For Mac
$ mkdir myproject
$ cd myproject
$ python3 -m venv venv
Make the Environment Active
Before you begin working on your project, turn on the environment:
For Windows
> venvScriptsactivate
For Mac
$ . venv/bin/activate
The name of the current active environment will be shown in your shell prompt.
Install Flask
Run the following command in the active environment to install Flask:
<div>
<div>
<pre>$ pip install Flask</pre>
</div>
</div>
Creating Our First Flask App
Let’s make our first flask app now. Flask application may look like this:
Python Code:
If everything works fine this will start a built-in server, which is used for testing but probably not suitable for production usage, your console will show the following output:

<div class="medium-insert-images">
<figure></figure>
</div>
This means that our app is running on http://127.0.0.1:5000/. Here 127.0.0.1 is the default IP address.
Now let’s understand the code:
- We started by importing the Flask class.
- We then make an instance of this class. Pass the ‘__name__’ argument which is the name of the application’s module or package. Flask needs this to know where to look for resources like templates and static files.
- Use the route() decorator to inform Flask which URL should activate our method.
- This method returns the message that should in the user’s browser.
Debug Mode
The flask run command is capable of doing more than simply starting the development server. When we enable debug mode, the server will immediately reload if the code changes, and an interactive debugger will appear in the browser if an error occurs during a request.
Creating fixed URLs is so damn simple. Users are more likely to enjoy and return to a website if it has a meaningful URL that they can remember and use to get directly to the page. To assist users, modern online apps employ meaningful URLs. To tie a function to a URL, use the route() decorator.
@app.route('/')
def index():
return 'This is Home Page'
@app.route('/hello')
def hello():
return 'This is Hello, World Page'
Now let’s understand the code:
- app.route(‘/’) will route to the home page URL, trailing slash ‘/’is generally used as a convention for the home page.
- app.route(‘/hello’) will route to the hello page URL.
In this way, we can render as many distinct web page URLs we want.
Static Routes vs Dynamic Routes in Flask
Static Route
As we can understand from the name that static routes are fixed routes i.e. for each route functionalities we have to explicitly define the same function for each URL route.
@app.route('/Elon')
def greet():
return 'Welcome Elon. What would you like to order.'
@app.route('/John')
def hello():
return 'Welcome John. What would you like to order.'
This code will greet different users with the same message.
Although implementing the same function for multiple routes isn’t a big problem until you get to a certain number of routes. It quickly becomes a frantic process when we are dealing with hundreds of routes.
Dynamic Route
Instead of defining the same function for each route, we can add variable sections to a URL by annotating sections with . The variable name is then sent to the defined function as the parameter.
@app.route('/')
def greet(name):
return f'welcome {name}. What would you like to order.'
in the route captures a value from the URL and passes it to the function. So even if million of users route this web page we can handle all the routes by defining merely one function.
We can also use a converter to define the type of the parameter, such as.
Defining datatype along with variable name enforces the user to follow the convention while passing the route name to the server.
Converter Types
int | only accepts positive integers |
float | only accepts positive floating-point values |
string | accepts text (by default) without a slash |
path | like string but also accepts slashes |
uuid | accepts UUID strings |
HTML Injections
HTML injection is a way of modifying a web page that an application presents to its users by using non-validated input. If a program does not validate the user data, an attacker can send a malicious text in HTML format which can modify the content of the site, seen by other users. A query can result in the insertion of attacker-controlled HTML elements into a web page, changing the way application content is on the web.
HTML Escaping
To defend against injection attacks, it’s essential to enclose all user-provided values when rendering output in HTML (the default response type in Flask).
Use the escape() function manually. Most examples remove it for brevity, but you should always be mindful of how you’re accessing untrusted data.
from flask import escape
@app.route("/")
def hello(name):
return f"Hello, {escape(name)}!"
Hypertext Transfer Protocol
When we are searching for any web pages, to access their server and client employs several HTTP methods to communicate. As you work with Flask, you should become familiar with the HTTP methods.
The Hypertext Transfer Protocol (HTTP) is a protocol that allows clients and servers to share information. HTTP is a request-response protocol to communicate between a client and a server. A client (browser) sends an HTTP request to the server, and the server answers.
HTTP Methods
- GET
- POST
- PUT
- HEAD
- DELETE
- PATCH
- OPTIONS
Currently, we will look at GET and POST, these are the most common methods.
GET Method
Use GET to fetch information from a certain website.
POST Method
Use POST to send data to a server to update or create a resource.
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
A route, by default, only responds to GET queries. The route() decorator’s methods parameter may handle HTTP methods.
Conclusion
In the realm of Python web development, Flask shines as a light of simplicity and versatility. Whether it’s a prototype, a microservice, or a small-to-medium-sized web platform, its basic approach empowers developers to create applications that closely match their requirements. Flask promotes creativity and innovation by providing a balance between flexibility and structure, allowing developers to concentrate on their concepts and solutions rather than the specifics of the framework itself. Flask is quite versatile and use it for data research, API development, and more, making it a crucial tool for anyone looking to use Python in the dynamic world of web development.
Frequently Asked Questions
With its straightforward and adaptable Flask framework, use Python to construct web apps and APIs that are interactive and data-driven.
A flexible and minimalist micro web framework for Python, Flask is lightweight. A high-level web framework called Django has more pre-built capabilities and conventions for quick development.
The choice between Flask and Django depends on project complexity; Flask suits smaller, custom applications, while Django offers more features for larger, structured projects.
Use Flask in Python to create simple to fairly complex web applications or APIs that suits your own requirements. Flask is a lightweight and versatile framework.
The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.