Python Flask Framework

 Overview of Python Flask Framework

Web apps are developed to generate content based on retrieved data that changes based on a user’s interaction with the site. The server is responsible for querying, retrieving, and updating data. This makes web applications to be slower and more complicated to deploy than static websites for simple applications. There are two primary coding environments for the whole web app ecosystem. In this  will give an overview of the Python Flask Framework and Its best practices.

Client-side Scripting
The code executed on the user’s browser visible to anyone who has access to the system, generating the first results.
Server-side Scripting
This type of code is run on the backend on a web server. To enable developers to design, build, maintain, host web apps over the internet, a web framework necessary.

What is Web Framework?
A web framework is an architecture containing tools, libraries, and functionalities suitable to build and maintain massive web projects using a fast and efficient approach. They are designed to streamline programs and promote code reuse. To create the server-side of the web application, you need to use a server-side language. Python is home to numerous such frameworks, famous among which are Django and Flask. Its framework is a lightweight micro-framework based on Werkzeug, Jinja2. It is called a micro framework because it aims to keep its core functionality small yet typically extensible to cover an array of small and large applications. It depends on two external libraries: The Jinja2 template, Werkzeug WSGI toolkit. Even though we have a plethora of web apps at our disposal, Flask tends to be better suited due to -Built-in development server, fast debugger.

Integrated support for unit testing.
RESTful request dispatching.
Jinja2 Templating.
Support for secure cookies.
Lightweight and modular design allows for a flexible framework.


What is Flask Over Django?

Django is a full-stack web framework, while Flask is a micro lightweight f/w. But in recent times, Flask seems to have outdone Django, with more and more developers focusing on microservices and micro-frontends to reduce the loading time of a webpage. All of the user capability is available on a compact yet powerful f/w in Flask as compare to a host of additional resources in Django. Ease of development and faster deployment times in Flask.

What are the critical elements of the Python Flask Framework?
Initialization: flask applications must create an application instance. The web server passes all the requests it receives from clients to objects for handling using a protocol for WSG from flask import Flask app = Flask (__name__) (An application instance is an object of class Flask.)

The layout of the Python Flask Framework
Module Init - (project_root/app_name/admin/__init__.py) - required to enable the app
Module URL - (project_root/app_name/admin/url.py) - Url definitions of each module
App root Init - (project_root/app_name/__init__.py) - Not necessary to define the entire app within __init__.py
Module Views - (project_root/app_ame/admin/views.py) - Defines views for each module. Separate ‘.py.’ Files as the project scale to ensure they are accessible to URLs.
Module Templates - (project_root/app_name/admin/templates/admin/main.html) - Normal template folder.

Your 1st Flask Application
Hello World

Great! Now that everything is installed you can create your first Flask App.

Use the line below to import Flask in Python.
from flask import Flask

Create app, that hosts the application
app = Flask(__name__)

Then you need a route that calls a Python function. A route maps what you type in the browser (the url) to a Python function.
@app.route('/')
def index():

#The function should return something to the web browser,
    return 'Web App with Python Flask!'

Almost done, the server needs to be started. This starts the web app at port 81.
app.run(host='0.0.0.0', port=81)

Enter the url http://localhost:81/ in your web browser.

You can also add variables in your web app, well you might be thinking about how it’ll help you, it’ll help you to build a URL dynamically. So let’s figure it out with an example.

from flask import Flask
app = Flask(__name__)

@app.route('/hello/<name>')
def hello_name(name):
return 'Hello %s!' % name

if __name__ == '__main__':
app.run()

And go to the URL http://127.0.0.1:5000/hello/Binu it’ll give you the following output.

Hello Binu

We can also use HTTP methods in Flask let’s see how to do that
The HTTP protocol is the foundation of data communication on the world wide web. Different methods of data retrieval from specified URL are defined in this protocol. The methods are described down below.


GET : Sends data in simple or unencrypted form to the server.
HEAD : Sends data in simple or unencrypted form to the server without body.
HEAD : Sends form data to the server. Data is not cached.
PUT : Replaces target resource with the updated content.
DELETE : Deletes target resource provided as URL.

By default, the Flask route responds to the GET requests. However, this preference can be altered by providing methods argument to route() decorator. In order to demonstrate the use of the POST method in URL routing, first, let us create an HTML form and use the POST method to send form data to a URL. Now let’s create an HTML login page.

Below is the source code of the file: HTML
<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<p>Enter Name:</p>

<p><input type = "text" name = "nm" /></p>

<p><input type = "submit" value = "submit" /></p>

</form>
</body>
</html>
Now save this file HTML and try this python script to create the server.

from flask import Flask, redirect, url_for, request
app = Flask(__name__)


@app.route('/success/<name>')
def success(name):
return 'welcome %s' % name


@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success', name=user))
else:
user = request.args.get('nm')
return redirect(url_for('success', name=user))

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

After the development server starts running, open login.html in the browser, enter your name in the text field and click submit button

Comments

Popular posts from this blog

Programming in Python CST 362 KTU CS Sixth Semester Elective Notes

Image Processing

Turtle Graphics