0% found this document useful (0 votes)
71 views7 pages

Flask - V Unit

First of all I really thankful to my Lovely Professional University because of them 1 could achieve the target. I express my sincere thanks to my project guide Mrs. Deepika Dhall who had guide to me throughout my project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views7 pages

Flask - V Unit

First of all I really thankful to my Lovely Professional University because of them 1 could achieve the target. I express my sincere thanks to my project guide Mrs. Deepika Dhall who had guide to me throughout my project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Flask Web Development Frame Work

Web Development:
● A web application framework is a collection of libraries and modules which
helps developers write the business layer without worrying about the
protocol, thread management, etc.
● 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
● Django follows a traditional web framework which is also called an
enterprise framework.
● famous Web Development Frame Works are Django and Flask

Micro Frame Work:

In contrast to a traditional web framework, a micro-framework is a minimalistic


framework where developers are provided with a lot of freedom to build the web
application layer. As compared to an enterprise framework, a developer would not
need to set up many things in a micro-framework to get the web app hosted and
running. This is incredibly useful in cases of small web app development where the
needs are not the same as an enterprise-level framework which would save lots of
development ~ maintenance time and money as a consequence.

It is called a micro framework because it aims to keep its core functionality small

Flask

● Flask is Python’s micro-framework for web app development


● Flask consists of Werkzeug WSGI toolkit and Jinja2 template engine

Major advantages of Flask are:

1. Ease of setup and use.


2. Freedom to build the structure of the web application.

What is WSGI?

Web Server Gateway Interface (WSGI) is the standard for Python web application
development. WSGI is a specification for a universal interface between the web
server and the web applications
What is Jinja 2?
Jinja 2 is a template rendering engine. It renders the web pages for the server with
any specified custom content given to it by the webserver. Flask renders its HTML
based templates using Jinja 2.

Flask Routes and View Function


In Flask, routes are used to map URLs to view functions. The view functions are
responsible for processing the request and returning a response. Here's a simple
example to illustrate how routes and view functions work in a Flask application:

From flask import Flask


app = Flask( __name__ )
@app.route(‘/‘)
Def index():
Return ’ <h1> Hello World <h1> ‘

Let’s understand the syntax of the program


1. The first line of code `from flask import Flask` is basically importing
Flask package in the file.
2. We next create an object of the flask class using `app = flask()`
3. We send the following argument to the default constructor `__name__`,
this will help Flask look for templates and static files.
4. Next, we use the route decorator to help define which routes should be
navigated to the following function. `@app.route(/)`
5. In this, when we use `/` it lets Flask direct all the default traffic to the
following function.
6. We define the function and the action to be performed.
7. The default content type is HTML, so our string will be wrapped in HTML
and displayed in the browser.
8. In the main function created, `app.run()` will initiate the server to run on
the local development server.

If __name__ == ‘__main__’:

App.run(debug=True)

Server Startup - The application instance has a ‘run’ method that launches flask’s
integrated development webserver –

Once the script starts, it waits for requests and services in a loop.

Local-Host - Run a python script in a virtual environment. Flask starts the server
listening on 127.0.0.1 and port 5000 by default. To accept connection from any
remote address, use host = ‘0.0.0.0.’
What is a Context?

In order to execute the code that you write, it needs data to process. This
data could be configuration data, input data, data from the database, and so
on.

Contexts are used to keep track of the data that your code needs to execute.

In Flask, contexts are used to provide the necessary data to process


requests and command-line interface (CLI) commands.

While this article focuses on processing requests, the concepts presented


also apply to CLI commands.

Request Processing

Let's start with how a request is processed from a high-level:

So, a request is sent from the browser to the web server (like Nginx or
Apache) to request a specific URL ('/' URL in the above diagram). The web
server then routes this request to a WSGI server for processing.

WSGI, which stands for Web Server Gateway Interface, is an interface


between a web server and a Python-based web application. It's required
since a web server cannot talk directly to a Python application. For more,
review WSGI.
The WSGI server tells the Flask app to process the request.

The Flask app generates a response, which is sent back to the WSGI server
and back to the web server and, ultimately, back to the web browser.
These steps describe the request-response cycle, which is a key function of
how a request is processed via a web server, WSGI application server, and a
web application.

Contexts in Flask

When a request is received, Flask provides two contexts:

Context Description Available


Objects
Application Keeps track of the application-level current_app , g
data (configuration variables,
logger, database connection)
Request Keeps track of the request-level request , session
data (URL, HTTP method, headers,
request data, session info)

It's worth noting that each of the above objects are often referred to as
"proxies". This just means that they are proxies to global flavors of the
objects. We'll dive more into this shortly.
Flask handles the creation of these contexts when a request is received.
They can cause confusion as you don't always have access to a particular
object depending on which state your application is in.

Overview Diagram

The following diagram illustrates how contexts are processed when a request
is handled:
There's a lot going on in this diagram, so we'll walk through each step in
detail.

Step 1 - Web and WSGI Servers

Everything starts when a request is received by the web server:

The job of the web server is to route incoming HTTP requests to


WSGI server.

Step 2 - Worker
In order to process the request, the WSGI server spawns a worker to handle
the request:

The worker can be a thread, process, or coroutine. For example, the workers
would be threads if you're using the Flask Development Server with its
default configuration.

For this explanation, the worker type is not important; the key point about
the worker is that it handles one request at a time (hence the need for more
than one worker).

Step 3 - Contexts

Once execution switches to the Flask app, Flask creates


the Application and Request contexts and pushes them onto their respective
stacks:

To review, the

 Application context stores application-level data, such as the


configuration variables, database connection, and logger.
 Request context, meanwhile, stores the request-specific data that
needs to be processed in order to generate a response.

Step 4 - Proxies

Now that the Flask app is ready to process the data (in the view function)
and the data is ready in the Application and Request context stacks, we
need a way to connect these two pieces... proxies to the rescue!

Proxies are used by the view functions to access the Application (stored in
the Application context stack) and Request contexts (stored in the Request
context stack):
Steps in Request Response Life Cycle

In a Flask web application, the application stack and request stack play
important roles in managing the flow of control during the request-response
life cycle. Here are the steps, incorporating the application stack and request
stack:

1. Client Sends a Request:


 The client sends an HTTP request to the Flask server.
2. Application Stack Initialization:
 When the Flask application is started, an application stack is created.
This stack contains the Flask application instance and any extensions
or middleware that have been registered.
3. Request Object Creation:
 When a request is received, Flask creates a Request object to
encapsulate the details of the incoming request. This object is specific
to the current request and is pushed onto the request stack.
4. Request Middleware (Optional):
 If you have registered middleware in your application, it is executed.
Middleware functions can perform tasks such as modifying the
request or response objects. Each middleware function has access to
the request stack.
5. Routing:
 Flask uses its routing mechanism to determine which view function
should handle the incoming request. This involves matching the URL
in the request to a route defined in the application.
6. Request Context Push:
 Before the view function is called, Flask pushes a request context onto
the request stack. This context contains information about the current
request, such as the Request object and other request-specific data.
7. View Function Execution:
 The view function associated with the matched route is executed. This
function has access to the request stack, allowing it to retrieve the
Request object and other request-specific data.
8. Application Context Push (Optional):
 If your view function interacts with the application context (e.g., using
Flask extensions), an application context may be pushed onto the
application stack.
9. Processing the Request:
 Inside the view function, you can access and process the data from
the Request object and perform any necessary operations, such as
querying databases or interacting with other services.
10. Template Rendering (Optional):
 If applicable, the view function may use a template engine to
dynamically generate HTML content. Data can be passed from the
view function to the template.
11. Response Object Creation:
 The view function returns a Response object, which encapsulates the
data to be sent back to the client. This response object is pushed onto
the request stack.
12. Application Context Pop (Optional):
 If an application context was pushed onto the application stack, it is
popped off.
13. Request Context Pop:
 The request context is popped off the request stack. This ensures that
resources associated with the current request are properly cleaned up.
14. Sending the Response:
 Flask takes the Response object from the top of the request stack and
sends it back to the client as an HTTP response.
15. Client Receives the Response:
 The client (browser) receives the HTTP response and processes it. If
the response includes HTML content, the browser renders the page
accordingly.

This breakdown emphasizes the use of both the application stack and
request stack in managing the request-response life cycle in a Flask web
application. The stacks help maintain context and isolate resources between
different requests.

You might also like