An Easy introduction to Flask Framework for beginners

Source Node: 1878430

  • What is a Framework
  • FrontEnd vs BackEnd
  • What is Flask Framework
  • Installation of Flask
  • Creating our first Flask app
  • Routing
  • Static Route vs Dynamic Route
  • HTML Injections
  • HTML Escaping
  • Hypertext Transfer Protocol
  • GET and POST Methods

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. It is a set of functions and predefined classes used to connect with the system software and handle inputs and outputs.

It simplifies 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

  1. 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
  2. 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

  • Secure cookies are supported.

  • 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:

$ pip install Flask

Creating our first Flask app

Let’s make our first flask app now. Flask application may look like this:

from flask import Flask

app = Flask(__name__)

@app.route(“/”)
def home():
return “Hello, World! This is our first Flask app.”

if __name__ == “__main__”:
app.run(debug=True)


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:

Flask Framework Output

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:

  1. We started by importing the Flask class.
  2. We then make an instance of this class. The ‘__name__’ argument is passed 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.
  3. The route() decorator is then used to inform Flask which URL should activate our method.
  4. This method returns the message that should be shown 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.

Routing in Flask

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:

  1. app.route(‘/’) will route to the home page URL, trailing slash ‘/’is generally used as a convention for the home page.
  2. 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.

@app.route('/post/')
def show_post(post_id): return f'Post ID is: {post_id}' @app.route('/path/')
def show_subpath(subpath): return f'The given subpath is: {subpath}'

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 well-designed query can result in the insertion of attacker-controlled HTML elements into a web page, changing the way application content is displayed on the web.

HTML Escaping

To guard against injection attacks, all user-provided values rendered in the output must be enclosed when returning the HTML (the default response type in Flask).

The escape() function can be used 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 used 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 commonly used methods.

GET Method

GET is used to fetch information from a certain website.

POST Method

POST is used 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':
eturn 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 be used to handle discussed HTTP methods.

After reading this article, I recommend that you should practice running each code in your system so that you can get used to it.

I hope you enjoyed reading the article. If you found it useful, please share it among your friends and on social media. For any queries, suggestions, or any other discussion, please ping me here in the comments or contact me via Email or LinkedIn.

Contact me on LinkedIn – www.linkedin.com/in/ashray-saini-2313b2162

Contact me on Email – [email protected]

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Source: https://www.analyticsvidhya.com/blog/2021/10/easy-introduction-to-flask-framework-for-beginners/

Time Stamp:

More from Analytics Vidhya